Skip to content Skip to main navigation Skip to footer

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

参考了李航老师的《统计学习方法》第二章,利用Python简单写了一个感知机算法,但是画图真是部分真是不太会(丑哭了)。

代码运行过程中会画出分类界面:

最后紫色的是收敛后的解。

Perceptron

Python

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&#91;0&#93; * row&#91;1:&#93;
            b = b + eta * row&#91;0&#93;
            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

原创文章,转载请注明:转载自magic282.me

本文链接地址: 感知机学习算法原始形式

文章的脚注信息由WordPress的 wp-posturl插件自动生成

原文:http://magic282.me/2015/05/perceptron/

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.