我从here用Python编写了Percentron示例。在
这是完整的代码
import matplotlib.pyplot as plt
import random as rnd
import matplotlib.animation as animation
NUM_POINTS = 5
LEANING_RATE=0.1
fig = plt.figure() # an empty figure with no axes
ax1 = fig.add_subplot(1,1,1)
plt.xlim(0, 120)
plt.ylim(0, 120)
points = []
weights = [rnd.uniform(-1,1),rnd.uniform(-1,1),rnd.uniform(-1,1)]
circles = []
plt.plot([x for x in range(100)], [x for x in range(100)])
for i in range(NUM_POINTS):
x = rnd.uniform(1, 100)
y = rnd.uniform(1, 100)
circ = plt.Circle((x, y), radius=1, fill=False, color='g')
ax1.add_patch(circ)
points.append((x,y,1))
circles.append(circ)
def activation(val):
if val >= 0:
return 1
else:
return -1;
def guess(pt):
vsum = 0
#x and y and bias weights
vsum = vsum + pt[0] * weights[0]
vsum = vsum + pt[1] * weights[1]
vsum = vsum + pt[2] * weights[2]
gs = activation(vsum)
return gs;
def animate(i):
for i in range(NUM_POINTS):
pt = points[i]
if pt[0] > pt[1]:
target = 1
else:
target = -1
gs = guess(pt)
error = target - gs
if target == gs:
circles[i].set_color('r')
else:
circles[i].set_color('b')
#adjust weights
weights[0] = weights[0] + (pt[0] * error * LEANING_RATE)
weights[1] = weights[1] + (pt[1] * error * LEANING_RATE)
weights[2] = weights[2] + (pt[2] * error * LEANING_RATE)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
我希望在图上绘制的点根据预期条件(x坐标>y坐标)即参考线上方或下方(y=x)将其自身分类为红色或蓝色
这似乎不起作用,在一些迭代之后,所有的点都会变红。在
我做错什么了。youtube的例子也是如此。在
我看了你的代码和视频,我相信你写代码的方式,点开始是绿色的,如果他们的猜测与目标相符,他们就会变成红色,如果他们的猜测与目标不符,他们就会变成蓝色。当他们的猜测与目标相匹配时,剩下的蓝色最终会变成红色。(不断变化的权重可能会从红色变为蓝色,但最终会得到纠正。)
下面是我对您的代码的修改,它通过添加更多的点来减慢过程:每帧只处理一个点,而不是全部:
0,不适用于特殊输入。在
底线是,如果一切正常,它们应该全部变红。如果希望颜色反映分类,则可以更改此子句:
^{pr2}$相关问题 更多 >
编程相关推荐