单层感知器2

2018-03-09  本文已影响0人  平衡WorkLife

题目

假设平面坐标系上有几个点(3,3), (4,3)这三个点的标签为1,
(0,1),(1,1)这两个点的标签为-1,构建神经网络来分类

思路:

代码

import numpy as np
import matplotlib.pyplot as plt

X=np.array([[1,3,3],
           [1,4,3],
           [1,1,1]])

Y=np.array([1,1,-1])
### 产生三个随机权值,范围在 -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)
  if(O==Y.T).all():
    print('Finished')
    print('epoch:',n)
    break

#diagram to show
#the category as 1, [3,3], [3,4]
x1=[3,4]
y1=[3,3]

#the category as -1 [1,1]
x2=[1]
y2=[1]
#斜率和截距
k=-W[1]/W[2]
d=-W[0]/W[2]

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

公式

  1. O=np.sign(np.dot(X, W.T))


    image.png
  2. 学习率乘输入


    image.png
  1. 斜率和截距


    image.png
image.png image.png
  1. 结果:很好地区分开了这两类数据


    image.png
上一篇 下一篇

猜你喜欢

热点阅读