import numpy as np class Perceptron(object): def __init__(self, eta = 0.01, n_iter = 10): self.eta = eta self.n_iter = n_iter def fit(self, X, y): self.w_ = np.zero(1 + X.shape[1]) self.error_ = [] for _ in range(self.n_iter): errors = 0 ''' X:[[1, 2, 3], [4, 5, 6] y:[1, -1] zip(X, y):[[1, 2, 3, 1]. [4, 5, 6, -1]] ''' for xi, target in zip(X, y): ''' update = n * (y - y') ''' update = self.eta * (target - self.predict(xi)) ''' xi是一个向量 update * xi等价于 [w1 = x1*update, w2 = x2*update, ......] ''' self.w_[1:] += update * xi self.w_[0] += update errors += int(update != 0.0) self.errors_.append(errors) def net_input(self, X): ''' z = w0*1 + w1*x1 + w2*x2 +..... np.dot()是做点积 ''' return np.dot(X, self.w_[1:]) + self.w_[0] def predict(self, X): return np.where(self.net_input(X) >= 0.0, 1, -1)
测试:
import numpy as np
X = np.array([[1,2,3],[4,5,6]],dtype=int)
print(X)
输出:
[[1 2 3]
[4 5 6]]
w_ = np.zeros(1+X.shape[1])
print(w_)
print(X.shape[1])
输出:
[0. 0. 0. 0.]
3
使用python 3 ,需要写np.zeros()
而不是np.zero()
多维矩阵运算
1)a
=
np.arange(
4
)
输出:
array([
0
,
1
,
2
,
3
])
2)b
=
a
*
*
2
输出:
array([
0
,
1
,
4
,
9
])
3)
c
=
10
*
np.sin(a)
输出:
array([
0.
,
8.41470985
,
9.09297427
,
1.41120008
])
4)n <
35
输出:
array([
True
,
True
,
True
,
True
], dtype
=
bool
)
,
5)A
=
np.array([[
1
,
1
],[
0
,
1
]])
B
=
np.array([[
2
,
0
],[
3
,
4
]])
C
=
A
*
B
# 元素点乘
输出:
array([[
2
,
0
],
[
0
,
4
]])
6)D
=
A.dot(B)
# 矩阵乘法
输出:
array([[
5
,
4
],
[
3
,
4
]])
7)E
=
np.dot(A,B)
# 矩阵乘法
输出:
array([[
5
,
4
],
[
3
,
4
]])
X:[ [1,2,3] , [4,5,6] ] y:[ 1 , -1 ] zip(X,y) = [[1,2,3, 1 ] , [4,5,6 , -1]] np.zero 向量全赋零操作 np.dot(X , y) 点积 w_[1:]权重w从1到最后 np.where(x>0 , true , false) 等价于冒号表达式
import numpy as np
class perceptron(object):
'''
eta:学习率
n_iter:权重向量的训练次数
w_:神经分叉权重向量 w处理输入x
errors_:用于记录神经元判断出错次数
'''
def _int_(self,eat=0.01,n_iter=10):
self.eat=eat;
self.n_iter=n_iter;
pass
def fit(self,X,y):
"""
输入训练数据,培训神经元,X是输入的训练样本,y是对样本的正确分类
X:shape[n_samples,n_features]
n_samples:几组数据。n_features:有多少个神经分叉。
X[[1,2,3],[4,5,6]]
n_samples:2
n_features:3
y:[1,-1]
"""
'''
初始化权重向量为0
w_:是一个一位数组,代表每个神经纤维的权重向量
X.shape[1]:在计算有几个神经纤维
加一是因为前面算法提到的w0,也就是步调函数的阈值
开始的时候阈值 塞它=w0 用w0保存
'''
self.w_=np.zero(1+X.shape[1]);
self.errors=[];
for _ in range(self.n_iter):
error=0;
'''
X[[1,2,3],[4,5,6]]
y:[1,-1]
zip(X,y)=[[1,2,3,1],[4,5,6,-1]]
'''
for xi,target in zip(X,y):
'''
target:每组数据,一个个神经元 判断的正确值标准值
update=学习率*(y-y')
'''
update=self.eta*(target-self.predict(xi))
'''
predict:函数,是用来根据每个神经元输入的一组数据得到自己判断的结果
xi 是一个向量
update*xi等价:
[的它w(1)=x[1]*update,的它w(2)=x[2]*update,的它w(3)=x[3]*update,]
'''
self.w_[1:] +=update*xi
self.w_[0] +=update;
errors += int(update != 0.0)
self.errors_append(errors)
pass
pass
def net_input(self,x):
'''
完成神经元对输入信号的处理(加权点乘)
'''
return np.dot(X , self.w_[1:] + self.w_[0])
pass
def predict(self,x):
'''
加权点乘后用于与阈值判断
'''
return np.where(self.net_input(X) >= 0.0 , 1 , -1)
pass
pass