据: 吴恩达在网易云课堂的《神经网络和深度学习》 3.9 神经网络的梯度下降法 唐宇迪在网易云课堂的《深度学习入门视频课程》18 动手实现简易神经网络整理得到一个简单的单层神经网络,现附上代码如下:
# -- coding=utf-8 -- import numpy as np # 非线性函数 def nonlin(x,deriv=False): # 反向传播时 if(deriv==True): return x*(1-x) # 正向传播时 return 1/(1+np.exp(-x)) x = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) print 'x.shape: ', x.shape y = np.array([[0], [0], [1], [1]]) print 'y.shape: ', y.shape # np.random.seed(1) # 生成(-1,1)之间的随机数 w1 = 2*np.random.random((3,4)) - 1 w2 = 2*np.random.random((4,1)) - 1 print 'w1.shape: ', w1.shape print 'w2.shape: ', w2.shape for i in xrange(80000): l1 = x # 输入层 l2 = nonlin(np.dot(l1,w1)) # 隐藏层 l3 = nonlin(np.dot(l2,w2)) # 输出层 # 损失值loss loss = l3 - y # loss = y - l3 # 反向求dz2,dw2 dz2 = loss * nonlin(l3, deriv=True) dw2 = l2.T.dot(dz2) # 反向求dz1,dw1 dz1 = dz2.dot(w2.T) * nonlin(l2, deriv=True) dw1 = l1.T.dot(dz1) # 对w1,w2作出调整 w2 -= dw2 # w2 += dw2 w1 -= dw1 # w1 += dw1 # 循环输出loss值 if(i % 10000 == 0): print "LOSS: ", np.mean(np.abs(loss)) # np.mean()求平均值
简单的单层神经网络的实现,附代码
最新推荐文章于 2024-09-25 19:10:42 发布