Cookbook for Practice 4.1
Cong Li 李聪
实践4.1攻略
Classification Data 分类数据 (1)
Start a new file ‘classificationData.py’ w/ a new class. Later we will use this class for data in classification
创建一个包含新的类型的新文件“classificationData.py”。以后的分类中,数据都会用到这个类型。
In the initialization function, initialize two empty arrays. One for class labels & one for attribute data for each item.
在初始化函数中,初始化两个数组。一个存储每条数据的真实类别,另一个存储每条数据用于分类的属性数据
Classification Data 分类数据 (2)
Write a member functions add a data item
写一个成员函数,用来添加一条数据
Write 3 member functions to retrieve the total number of data items, the attributes (features) & label of a certain data item
写三个成员函数,获取总数据量以及某条数据的属性(特征)和类别
Evaluation 评估
Modify the class ‘Tester’ w/ a new member function, taking the training data for training & test data for evaluation
修改“Tester”类型,加一个新的成员函数,接收训练数据用以训练和测试数据进行评估
Training
训练
Evaluation
评估
Configure Data Size 设置数据量
Start a new file ‘test.py’, import ‘argparse’, follow Practice 2.1 to use a mandatory command line argument to input the training data size, & hard-code the test data size
新开一个“test.py”文件,导入“argparse”,参照实践2.1用一个必要命令行参数来输入训练数据量,将测试数据量设为100
Generate 1 Data Item 生成一条数据 (1)
Import ‘random’ & ‘numpy’. Before the main section, define a new function ‘generate_data’. In the function, generate 2 random numbers (-3~3 & -15~15)
导入“random”和“numpy”。在main部分前声明一个函数“generate_data”。产生两个随机数( -3~3和-15~15 )
Generate 1 Data Item 生成一条数据 (2)
Take the 1st random number as the attribute (but leave the 2nd one for future use, just to make the random series fixed) & determine the class label. Return the data item (x in numpy array type)
以第一个随机数作为属性(把第二个留到将来,仅仅为了保证随机序列的确定性),确定类别。返回该数据(x为numpy数组类型)
Training & Test Data �训练和测试数据
Import ‘classificationData’ 导入“classificationData”
In the main section, initialize the random seed. Generate test data first (to make the data the same for different training data size) & then the training data 在main部分中,初始化随机数。先生成测试数据(以保证不同训练数据量下测试数据相同),然后生成训练数据
Generate test data 生成测试数据
Training & Test Data �训练和测试数据
Import ‘classificationData’ 导入“classificationData”
In the main section, initialize the random seed. Generate test data first (to make the data the same for different training data size) & then the training data 在main部分中,初始化随机数。先生成测试数据(以保证不同训练数据量下测试数据相同),然后生成训练数据
Generate training data 生成训练数据
Run It 运行之
Import ‘tester’ & ‘nearestNeighbor’
导入“tester”和“nearestNeighbor”
Create an instance of ‘NearestNeighbor’ class, an instance of ‘Tester’, & evaluate the classification accuracy
生成“NearestNeighbor”类型的实例和“Tester”类型的实例,评估分类准确率
Try training data size of 20, 40, 60, 80, 100, 120
尝试不同的训练数据量:20,40,60,80,100,120
The End