import numpy as np import matplotlib.pyplot as plt
#输入数据 X = np.array([[1,3,3], [1,4,3], [1,5,7], [1,1,1]]) #标签 Y = np.array([[1,1,1,-1]]) #权值初始化,1行3列,取值范围-1到1 W = (np.random.random((1,3))-0.5)*2 print(W.shape) #学习率设置 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*(np.dot((Y-O.T) , 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
#正样本
top_x = [3,3,5]
top_y = [4,3,7]
#负样本
below_x = [1]
below_y = [1]
#计算分界线的斜率以及截距
#分类问题中,分界线的预测值为0,分界线上面的点为正,下面的负
#分界线的方程为:w0 + w1x1 + w2x2 = 0
#斜率为:x1=-w2/w1-w0/w1或者x2=-w1/w2-w0/w2
k = -W[0][2]/W[0][1]
d = -W[0][0]/W[0][1]
print('k=',k)
print('d=',d)
#生成0-5之间实数,第三个参数为生成多少个,默认50个,作为斜率的x的值
xdata = np.linspace(0,5)
plt.figure()
plt.plot(xdata,xdata*k+d,'r')
plt.plot(top_x,top_y,'bo')
plt.plot(below_x,below_y,'yo')
plt.show()

单层感知器只能解决简单的线性问题,对于非线性的如异或问题就无法解决; 异或问题如下图所示,简单的线性函数无法将这四个点分成两类;
#正样本 top_x = [1,0] top_y = [0,1] #负样本 below_x = [1,0] below_y = [1,0] plt.figure() plt.plot(top_x,top_y,'bo') plt.plot(below_x,below_y,'yo') plt.show()

对平面上的坐标点(x1,y1),引入三个非线性输入:x1x1,x1y1,y1*y1;
#输入数据
X = np.array([[1,0,0,0,0,0],
[1,0,1,0,0,1],
[1,1,0,1,0,0],
[1,1,1,1,1,1]])
#标签
Y = np.array([-1,1,1,-1])
#权值初始化,1行3列,取值范围-1到1
W = (np.random.random(6)-0.5)*2
print('初始化的权值为:\n' , W)
#学习率设置
lr = 0.11
#计算迭代次数
n = 0
#神经网络输出
O = 0
def update():
global X,Y,W,lr,n
n+=1
O = np.dot(X,W.T)
W_C = lr*((Y-O.T).dot(X))/int(X.shape[0])
W = W + W_C
for _ in range(100000):
update()#更新权值
#正样本
x1 = [0,1]
y1 = [1,0]
#负样本
x2 = [0,1]
y2 = [0,1]
'''
计算平面图像上y的坐标
将输入替换为平面坐标系上的点后可以得到方程:
w0+w1x+w2y+w3x*x+w4xy+w5y*y = 0
化简得到
w5y*y + (w2+w4x)y + w0+w1x+w3x*x = 0
通过二次方程求根公式即可得到x对应的y值
'''
def calculate(x,root):
a = W[5]
b = W[2]+x*W[4]
c = W[0]+x*W[1]+x*x*W[3]
if root==1:
return (-b+np.sqrt(b*b-4*a*c))/(2*a)
if root==2:
return (-b-np.sqrt(b*b-4*a*c))/(2*a)
#确定图像上平面坐标系里x的范围
xdata = np.linspace(-1,2)
plt.figure()
plt.plot(xdata,calculate(xdata,1),'r')
plt.plot(xdata,calculate(xdata,2),'r')
plt.plot(x1,y1,'bo')
plt.plot(x2,y2,'yo')
plt.show()
print('循环结束后的权值为:\n' ,W)
O = np.dot(X,W.T)
print('循环结束后的预测值为:\n' , O)
注:理论上用LMS做为损失函数时,预测值会越来越接近真值,但不会等于真值,计算机实际执行时,当精度超过计算机能表达的极限时,就会等于真值;