【发布时间】:2018-07-16 02:50:41
【问题描述】:
我正在尝试实现一个感知器。我已经加载了一个 0 到 100 之间值的 100x2 数组。数组中的每个项目都有一个 -1 或 1 的标签。
我相信感知器正在工作,但是我无法绘制决策边界,如下所示:plot decision boundary matplotlib
当我运行我的代码时,我只看到单一颜色的背景。我希望看到两种颜色,一种颜色用于我的数据集中的每个标签(-1 和 1)。
My current output, I expect to see 2 colors for the background (-1 or 1)
An example of what I hope to see, from the sklearn documentation
import numpy as np
from matplotlib import pyplot as plt
def generate_data():
#generate a dataset that is linearly seperable
group_1 = np.random.randint(50, 100, size=(50,2))
group_1_labels = np.full((50,1), 1)
group_2 = np.random.randint(0, 49, size =(50,2))
group_2_labels = np.full((50,1), -1)
#add a bias value of -1
bias = np.full((50,1), -1)
#add labels, upper right quadrant are 1, lower left are -1
group_1_with_bias = np.hstack((group_1, bias))
group_2_with_bias = np.hstack((group_2, bias))
group_1_labeled = np.hstack((group_1_with_bias, group_1_labels))
group_2_labeled = np.hstack((group_2_with_bias, group_2_labels))
#merge our labeled data and shuffle!
merged_data = np.vstack((group_1_labeled, group_2_labeled))
np.random.shuffle(merged_data)
return merged_data
data = generate_data()
#load data, strip labels, add a -1 bias value
X = data[:, :3]
#create labels matrix
l = np.ravel(data[:, 3:])
def perceptron_sgd(X, l, c, epochs):
#initialize weights
w = np.zeros(3)
errors = []
for epoch in range(epochs):
total_error = 0
for i, x in enumerate(X):
if (np.dot(x, w) * l[i]) <= 0:
total_error += (np.dot(x, w) * l[i])
w = w + c * (x * l[i])
errors.append(total_error * -1)
print "epoch " + str(epoch) + ": " + str(w)
return w, errors
def classify(X, l, w):
z = np.dot(X, w)
print z
z[z <= 0] = -1
z[z > 0] = 1
#return a matrix of predicted labels
return z
w, errors = perceptron_sgd(X, l, .001, 36)
# X - some data in 2dimensional np.array
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, .2), np.arange(y_min, y_max, .2))
# here "model" is your model's prediction (classification) function
Z = classify(np.c_[xx.ravel(), yy.ravel()], l, w[:-1]) #strip the bias from weights
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
plt.axis('off')
#Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=l, cmap=plt.cm.Paired)
【问题讨论】:
-
虽然这是非常易读的代码,但很难验证您的问题,因为我们没有您的输入数据。你能提供一个Minimal, Complete, and Verifiable 来解决你的问题吗?在我看来,这可以通过
two-valued array和带有Paired颜色图的contourf绘图轻松完成。 -
@ThomasKühn 我添加了一个 generate_data() 函数,以便可以执行我的代码。让我知道是否需要其他任何东西。感谢您的观看。
-
有什么理由在预测过程中去除偏差?它是学习权重的一部分。
-
@shivam 我无法让 np.dot 运行两个不同大小的矩阵。
标签: python-2.7 numpy matplotlib machine-learning perceptron