题目:基于感知器的原理实现与和或的逻辑功能。
大体思路:
1)将要训练的样本用numpy.array存放。
2)建立线性回归模型,利用梯度下降进行求解。
线性模型:f(x)=th0+th1*x1+th2*x2
3)建立激活函数f(x):当x>=0.5时,f(x)=1,当x<0.5时,f(x)=0。
import numpy as np
th0 = 0
th1 = 0
th2 = 1
alpha = 0.01
J = 0
data = np.array([[0,0,0],
[0,1,0],
[1,0,0],
[1,1,1]])
def mysum(x1,x2):
return th0+th1*x1+th2*x2
def f(z):
if z>=0.5:
return 1
if z<0.5:
return 0
def traing(data,alpha,th0,th1,th2):
loss = 0
bp0 = 0
bp1 = 0
bp2 = 0
for i in data:
loss += 1/2*(mysum(i[0],i[1])-i[2])**2
bp0 += (mysum(i[0],i[1])-i[2])
bp1 += (mysum(i[0],i[1])-i[2])*i[0]
bp2 += (mysum(i[0],i[1])-i[2])*i[1]
N = len(data)
loss = loss / N
bp0 = bp0 / N
bp1 = bp1 / N
bp2 = bp2 / N
th0 = th0 - alpha*bp0
th1 = th1 - alpha*bp1
th2 = th2 - alpha*bp2
return loss,th0,th1,th2
for i in range(500):
J,th0,th1,th2 = traing(data,alpha,th0,th1,th2)
print(J,th0,th1,th2)
for j in data:
pre = f(mysum(j[0],j[1]))
print(pre)
与逻辑功能运行结果:
其中,第一行代表求解的线性回归中的th0,th1和th2,0 0 0 1为输入测试样本时输出的结果,与真实的与逻辑功能100%吻合。
x1 x2 y
0 0 0
0 1 0
1 0 0
1 1 1
或逻辑功能运行结果:
其中,第一行代表求解的线性回归中的th0,th1和th2,0 1 1 1为出入测试样本时输出的结果,与真实的或逻辑功能100%吻合。
x1 x2 y
0 0 0
0 1 1
1 0 1
1 1 1