本文实例为大家分享了python感知机实现的具体代码,供大家参考,具体内容如下
一、实现例子
李航《统计学方法》p29 例2.1
正例:x1=(3,3), x2=(4,3),
负例:x3=(1,1)
二、最终效果
三、代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import numpy as np import matplotlib.pyplot as plt p_x = np.array([[ 3 , 3 ], [ 4 , 3 ], [ 1 , 1 ]]) y = np.array([ 1 , 1 , - 1 ]) plt.figure() for i in range ( len (p_x)): if y[i] = = 1 : plt.plot(p_x[i][ 0 ], p_x[i][ 1 ], 'ro' ) else : plt.plot(p_x[i][ 0 ], p_x[i][ 1 ], 'bo' ) w = np.array([ 1 , 0 ]) b = 0 delta = 1 for i in range ( 100 ): choice = - 1 for j in range ( len (p_x)): if y[j] ! = np.sign(np.dot(w, p_x[ 0 ]) + b): choice = j break if choice = = - 1 : break w = w + delta * y[choice] * p_x[choice] b = b + delta * y[choice] line_x = [ 0 , 10 ] line_y = [ 0 , 0 ] for i in range ( len (line_x)): line_y[i] = ( - w[ 0 ] * line_x[i] - b) / w[ 1 ] plt.plot(line_x, line_y) plt.savefig( "picture.png" ) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/W_peijian/article/details/79098649