# Python: 感知机学习算法原始形式

Perceptron

Python

 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 from numpy import * import numpy as np import matplotlib.pyplot as plt import time plt.ion() plt.autoscale(enable=True, tight=False) dataFn = "data.dat>" def drawSpLine(w, b):     plt.plot([-b/w[0] if w[1]==0 else 0, 10 if w[0]==0 else -b/w[0]], [10 if w[1]==0 else -b/w[1], -b/w[1] if w[0]==0 else 0])     plt.draw()     plt.show() with open(dataFn) as inFile:     data = inFile.readlines()     d = np.loadtxt(data)     for row in d:         if row[0]==1:             plt.plot(row[1], row[2], 'ro')         else:             plt.plot(row[1], row[2], 'bo')     plt.draw()     plt.show()     time.sleep(1) w = ones(2) b = random.randint(10) eta = 1 print w print b drawSpLine(w, b) time.sleep(1) while True:     isConv = True     for row in d:         if row[0]*(dot(np.transpose(w), np.transpose(row[1:])) + b) <= 0:             w = w + eta * row[0] * row[1:]             b = b + eta * row[0]             print w, b             drawSpLine(w, b)             time.sleep(1)             isConv = False             break     if isConv:         print "Converged.>"         break print "w>", w print "b>", b plt.show(block=True)

```1    1   1
1   2   1
1   1   2
-1  4   2
-1  4   3
-1  3   3```