Cookbook for Practice 5.1
Cong Li 李聪
实践5.1攻略
Binary Perceptron 两类感知器 (1)
Start a new file ‘perceptron.py’, import ‘numpy’, create a class of ‘BinaryPerceptron’, & in its initialization function take a input parameter for maximum number of rounds in training
开启一个新文件“perceptron.py”,导入“numpy”,创建“BinaryPerceptron”类型,并在其初始化函数中接受一个最大训练轮数的参数
Binary Perceptron 两类感知器 (2)
Assuming two member variables of the class, bias b & weight array w, are properly maintained, write a scoring member function to calculate the score of an input data sample
假设我们恰当地维持着偏向b和权重w数组这两个成员变量,写一个计分的成员函数来计算某个给定输入数据的得分
Member variables properly maintained for weight array & bias
恰当维持的权重数组和偏向的成员变量
Calculate w/ vector dot product
用向量点乘计算
Binary Perceptron 两类感知器 (2)
Assuming two member variables of the class, bias b & weight array w, are properly maintained, write a scoring member function to calculate the score of an input data sample
假设我们恰当地维持着偏向b和权重w数组这两个成员变量,写一个计分的成员函数来计算某个给定输入数据的得分
Write another member function for classification based on the score 再写一个成员函数,基于得分进行分类
Binary Perceptron 两类感知器 (3)
Now we write the member function for training: initialize the weight array based on the data dimension as well as the bias现在我们来写用于训练的成员函数,根据数据的维度来初始化权重数组,并初始化偏向。
Loop for the maximum number of rounds in training, keeping a temporarily variable to record whether weights & bias are updated or not in a round 循环训练的最大轮数,用一个临时变量记录在这一轮是否修改了权重和偏向
Binary Perceptron 两类感知器 (4)
Training for each data item in a round: update the weights & the bias given an error & stop training if no errors found
在一轮中对每一个数据进行训练,在做错时对权重和偏向进行更新,如果没有错误则终止训练
Error in classification w/ current weights & bias
当前权重和偏向下分类错误
Binary Perceptron 两类感知器 (4)
Training for each data item in a round: update the weights & the bias given an error & stop training if no errors found
在一轮中对每一个数据进行训练,在做错时对权重和偏向进行更新,如果没有错误则终止训练
Stop training if no errors in a round
一轮无错即终止学习
Run It 运行之 (1)
Based on Practice 4.2, in file ‘test.py’, now add a dimension parameter to the function ‘generate_data’ 基于实践4.2,在文件“test.py”中,为函数“generate_data”传入一个维度参数
Use this parameter to determine whether to add the 2nd dimension 根据该参数决定是否加入第二维
Add an optional command line argument for data dimension 为数据维度加入一个可选命令行参数
Retrieve its value after parsing 解析后获取它的值
Run It 运行之 (2)
In training & test data generation (2 places), pass in the dimension value 在训练和测试数据生成时(两处),传入维度值
Now import ‘perceptron’ & create an instance of the ‘BinaryPerceptron’ class for classification 现在,导入“perceptron”,生成“BinaryPerceptron”类型的实例,用于分类
Run w/ the command lines like below
用类似以下的命令行运行
test.py -d 2 40
The End