我正在使用Python和Numpy实现一个感知机。我按照维基百科上的这篇文章中描述的算法进行训练,但得到的权重向量不能正确分类样本向量,甚至是训练集中的样本也不行。
这是我写的训练代码:
epochs = 50unit_step = lambda x: 0 if x < center else (0.5 if x == center else 1)def train(data_set, labels): number_of_samples, dimension = data_set.shape # 生成增广数据集,添加一列'1' augmented_data_set = np.ones((number_of_samples, dimension + 1)) augmented_data_set[:,:-1] = data_set w = 1e-6 * np.random.rand(dimension + 1) for _ in xrange(epochs): for sample, target in zip(augmented_data_set, labels): predicted_output = unit_step(np.dot(w, sample)) update = (target - predicted_output) * sample w += update return w
之后,我设置训练集为学习AND逻辑函数所需的向量,如下所示:
training_set = np.array([[0,0],[0,1],[1,0],[1,1]])
以及相应的类别标签如下:
labels = np.array([-1,-1,-1,1])
其中-1代表False,1代表True。
运行w = train(training_set, labels)
后,我测试了得到的权重向量,得到以下错误结果:
np.dot(w, [0,0,1]) = -1.0099996334232431
np.dot(w, [0,1,1]) = -1.0099991616719257
np.dot(w, [1,0,1]) = -1.009999277692496
np.dot(w, [1,0,1]) = -1.009999277692496
这里的错误是最后一种情况应该返回一个大于0且接近1的值。我不太清楚这里发生了什么。我错过了什么吗?
提前感谢
回答:
最明显的错误是训练集标签(-1和1)与模型输出(0, 0.5和1.0)之间缺乏统一性。将两者都改为0和1。