深度学习入门系列之单层感知器

# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
#输入数据
X = np.array([[1,3,3],
              [1,4,3],
              [1,1,1],
              [1,2,3],
              [1,1,4],
              [1,5,7]])
#标签
Y = np.array([1,1,-1,-1,1,1])
#权值初始化,1行3列,取值范围-1到1
W = (np.random.random(3)-0.5)*2
print(W)
#学习率设置
lr = 0.11
#计算迭代次数
n = 0
#神经网络输出
O = 0
def update():
    global X,Y,W,lr,n
    n+=1
    O = np.sign(np.dot(X,W.T))
    W_C = lr*((Y-O.T).dot(X))/int(X.shape[0])
    W = W + W_C
for _ in range(100):
    update()#更新权值
    print(W)#打印当前权值
    print(n)#打印迭代次数
    O = np.sign(np.dot(X,W.T))#计算当前输出
    if(O == Y.T).all(): #如果实际输出等于期望输出,模型收敛,循环结束
        print('Finished')
        print('epoch:',n)
        break
#正样本
x1 = [3,4,1,5]
y1 = [3,3,4,7]
#负样本
x2 = [1,2]
y2 = [1,3]
#计算分界线的斜率以及截距
k = -W[1]/W[2]
d = -W[0]/W[2]
print('k=',k)
print('d=',d)
xdata = np.linspace(0,5)
plt.figure()
plt.plot(xdata,xdata*k+d,'r')
plt.plot(x1,y1,'bo')
plt.plot(x2,y2,'yo')
plt.show()

 

仿真结果 

[-0.94520602 -0.04836318 0.40122124]
[-0.98187269 -0.12169651 0.29122124]
1
[-0.90853935 0.13497015 0.51122124]
2
[-0.94520602 0.06163682 0.40122124]
3
[-0.98187269 -0.01169651 0.29122124]
4
[-0.90853935 0.24497015 0.51122124]
5
[-0.94520602 0.17163682 0.40122124]
6
[-0.98187269 0.09830349 0.29122124]
7
[-1.01853935 0.02497015 0.18122124]
8
[-0.90853935 0.31830349 0.54788791]
9
[-0.94520602 0.24497015 0.43788791]
10
[-0.98187269 0.17163682 0.32788791]
11
[-1.01853935 0.09830349 0.21788791]
12
[-0.94520602 0.24497015 0.47455457]
13
[-0.98187269 0.17163682 0.36455457]
14
[-1.01853935 0.09830349 0.25455457]
15
Finished
epoch: 15
k= -0.3861784330473465
d= 4.001261257610323

猜你喜欢

转载自www.cnblogs.com/277223178dudu/p/9833323.html