Perceptron-AND运算符

问题描述 投票:0回答:2

我使用此代码来实现AND运算符,但是不能正确计算出分隔区域的行。它正在通过点[1,0]和[0,1]。为了正确分隔区域该怎么办?

from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
import numpy as np
from itertools import product

data = [[0,0],[1,0],[0,1],[1,1]]
labels_and = [0, 0, 0, 1]

x = [points[0] for points in data]
y = [points[1] for points in data]

plt.scatter(x, y, c = labels_and)
plt.show()

classifier = Perceptron()
classifier.fit(data, labels_and)

print(classifier.score(data, labels_and))

result = classifier.decision_function([[0, 0], [1, 1], [0.5, 0.5]])
print(result)

x_values = y_values = np.linspace(0, 1, 100)
point_grid = list(product(x_values, y_values))
distances = classifier.decision_function(point_grid)
abs_distance = [abs(x) for x in distances]

distance_matrix = np.reshape(abs_distance, (100, 100))

heatmap = plt.pcolormesh(x_values, y_values, distance_matrix)
plt.colorbar(heatmap)
plt.show()

Screenshot here

python perceptron
2个回答
0
投票

决策边界是正确的,因为所有内容>都归为1类,所有内容<=都归为0类。但是,您将分类器预测结果的绝对值可视化的方式可能会引起误解?


sklearn文档参考英文维基文章,该文章对感知器使用以下定义:

enter image description here

因为唯一的1类标签是点(1,1),所以我们可以选择右上角即w = [2,2]b=-2来正确分类(1,1) as 1(0,0), (0,1), (1,0) as 0

(1,0)和(0,1)点位于2*0+2*1-2 =0以来的决策边界上。但是,我们也可以选择b=-3,并且分类问题仍然可以正确解决。区别在于,由于2*0+2*1-3 <0,点(1,0)和(0,1)不再直接位于边界上。

让我们看看我们训练有素的感知器学习了哪些参数!要访问它们,您可以从sklearn docs

中看到
w = classifier.coef_[0]  
b = classifier.intercept_   

如果打印它们,则可能会获得w=[2,2]b=-2。要导出表示相应决策边界的线,可以考虑w0*x + w1*y + b == 0的边际情况并求解x。您将获得:

enter image description here

因此绘制此图将导致类似以下内容:

m = -weight[0]/weight[1]   
n = -b/weight[1]    
plt.plot(x_values, m*x_values+n)   

enter image description here

这是您在图片中看到的深蓝色山谷。我们的点(1,0)和(0,1)也在边界上。您可以使用b=-3进行测试,在其中可以获得可能期望的具有较高y截距的行?


0
投票

决策边界的计算正确,但是我希望它会有所不同。 @ v.tralala对此问题的解答中对此进行了详细说明。我同时发现,如果random_state的值不是零(例如random_state = 100),则将计算不同的截距和权重值,因此决策边界将更接近点(1,1)。 enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.