神经网络:正向传播,反向传播
重构单节点神经网络代码:
#引入类库
from numpy import array,exp,random,dot
def fp(input):
#加载数据
X = array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])
y = array([[0,1,1,0]]).T
#设置随机权重
random.seed(1)
weights = 2 * random.random((3,1)) - 1
#循环
for it in range(10000):
#利用点乘一次性计算出四个z来
z = dot(X,weights)
#使用sigmoid函数,计算最初的output
output = 1/(1+exp(-z))
#计算结束后与实际关系进行比较得出误差
error = y - output
#计算斜率
slope = output * (1-output)
#计算增量
delta = error * slope
#更新权重
weights = weights + dot(X.T,delta)
print(weights)
多个神经元,多层神经网络
情景分析:a,b同时不去,d不去;a去,b不去,d去;a不去,b去,d去;a,b同时去,d不去
#引入类库
from numpy import array,exp,random,dot
def fp(input):
l1 = 1/(1+exp(-dot(input,w0)))
l2 = 1/(1+exp(-dot(l1,w1)))
#print(l1)
#print(l2)
return l1,l2
def bp(l1,l2,y):
#计算结束后与实际关系进行比较得出误差
error = y - l2
slope = l2 * (1-l2)
l1_delta = error * slope
l0_slope = l1 * (1-l1)
l0_error = l1_delta.dot(w1.T)
l0_delta = l0_slope * l0_error
#计算增量
return l0_delta,l1_delta
#加载数据
X = array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
y = array([[0,1,1,0]]).T
#设置随机权重
random.seed(1)
w0 = 2 * random.random((3,4)) - 1
w1 = 2 * random.random((4,1)) - 1
#循环
for it in range(10000):
l0 = X
l1,l2 = fp(l0)
l0_delta,l1_delta = bp(l1,l2,y)
#print(l0_delta)
#print(l1_delta)
w1 = w1 + dot(l1.T,l1_delta)
w0 = w0 + dot(l0.T,l0_delta)
print(fp([[1,1,0]])[1])