BP神经网络(python代码)

BP神经网络(python代码)

神经网络是深度学习的基础。个人理解神经网络就是可以拟合任何一种广义线性模型的结构,本文主要记录python代码的学习笔记。

BP神经网络原理(待补充,可以详见《数据挖掘概念与技术》P258页)

伪代码:


代码中使用的随机梯度下降,伪代码是使用整体数据做梯度下降。

[python]  view plain  copy
  1. # coding=utf-8  
  2. import numpy as np  
  3.   
  4. def tanh(x):  
  5.     return np.tanh(x)  
  6.   
  7. def tanh_deriv(x):  
  8.     return 1.0- np.tanh(x)*np.tanh(x)  
  9.   
  10. def logistic(x):  
  11.     return 1/(1+np.exp(-x))  
  12.   
  13. def logistic_derivative(x):  
  14.     return logistic(x)*(1-logistic(x))  
  15.   
  16. class NeuralNetwork:  
  17.     def __init__(self,layers,activation='tanh'):  
  18.         """ 
  19.  
  20.         """  
  21.         if activation == 'logistic':  
  22.             self.activation = logistic  
  23.             self.activation_deriv = logistic_derivative  
  24.         elif activation=='tanh':  
  25.             self.activation = tanh  
  26.             self.activation_deriv=tanh_deriv  
  27.   
  28.         self.weights=[]  
  29.         self.weights.append((2*np.random.random((layers[0]+1,layers[1]))-1)*0.25)  
  30.         for i in range(2,len(layers)):  
  31.             self.weights.append((2*np.random.random((layers[i-1],layers[i]))-1)*0.25)  
  32.             #self.weights.append((2*np.random.random((layers[i]+1,layers[i+1]))-1)*0.25)  
  33.   
  34.     def fit(self,X,y,learning_rate=0.2,epochs=10000):  
  35.         X = np.atleast_2d(X)  
  36.             # atlest_2d函数:确认X至少二位的矩阵  
  37.         temp = np.ones([X.shape[0],X.shape[1]+1])  
  38.             #初始化矩阵全是1(行数,列数+1是为了有B这个偏向)  
  39.         temp[:,0:-1]=X  
  40.             #行全选,第一列到倒数第二列  
  41.         X=temp  
  42.         y=np.array(y)  
  43.             #数据结构转换  
  44.         for k in range(epochs):  
  45.                 # 抽样梯度下降epochs抽样  
  46.             i = np.random.randint(X.shape[0])  
  47.             a = [X[i]]  
  48.   
  49.             for l in range(len(self.weights)):  
  50.                 a.append(self.activation(np.dot(a[l],self.weights[l])))  
  51.                 # 向前传播,得到每个节点的输出结果  
  52.             error = y[i]-a[-1]  
  53.                 # 最后一层错误率  
  54.             deltas=[error*self.activation_deriv(a[-1])]  
  55.   
  56.             for l in range(len(a)-2,0,-1):  
  57.                 deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))  
  58.             deltas.reverse()  
  59.             for i in range(len(self.weights)):  
  60.                 layer = np.atleast_2d(a[i])  
  61.                 delta = np.atleast_2d(deltas[i])  
  62.                 self.weights[i] +=learning_rate*layer.T.dot(delta)  
  63.   
  64.     def predict(self,x):  
  65.         x=np.array(x)  
  66.         temp= np.ones(x.shape[0]+1)  
  67.         temp[0:-1]=x  
  68.         a = temp  
  69.         for l in range(0,len(self.weights)):  
  70.             a=self.activation(np.dot(a,self.weights[l]))  
  71.         return(a)  


下面为测试“异或”数据的代码:
因为输入是2个特征的所以输入层为2,隐藏层我随意定义了12,输出层为1(因为结果为0或1所以1位就够定义了。)


[python]  view plain  copy
  1.   
[python]  view plain  copy
  1. from BPNN import NeuralNetwork  
  2. import numpy as np  
  3.   
  4. nn = NeuralNetwork([2,12,1],'tanh')  
  5. x = np.array([[0,0],[0,1],[1,0],[1,1]])  
  6. y = np.array([0,1,1,0])  
  7. nn.fit(x,y)  
  8. for i in [[0,0],[0,1],[1,0],[1,1]]:  
  9.     print(i,nn.predict(i))  

代码结果:

[python]  view plain  copy
  1. ([00], array([-0.00917032]))  
  2. ([01], array([ 0.99785397]))  
  3. ([10], array([ 0.9979288]))  
  4. ([11], array([ 0.01522156]))  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值