1. 程式人生 > 其它 >BP神經網路1

BP神經網路1

import math
import numpy as np
import pandas as pd
from pandas import DataFrame

y =[0.14 ,0.64 ,0.28 ,0.33 ,0.12 ,0.03 ,0.02 ,0.11 ,0.08 ]
x1 =[0.29 ,0.50 ,0.00 ,0.21 ,0.10 ,0.06 ,0.13 ,0.24 ,0.28 ]
x2 =[0.23 ,0.62 ,0.53 ,0.53 ,0.33 ,0.15 ,0.03 ,0.23 ,0.03 ]
theata = [-1,-1,-1,-1,-1,-1,-1,-2,-1]
x = np.array([x1,x2,theata])

W_mid = DataFrame(0.5,index=['
input1','input2','theata'],columns=['mid1','mid2','mid3','mid4']) W_out = DataFrame(0.5,index=['input1','input2','input3','input4','theata'],columns=['a']) def sigmoid(x): #對映函式 return 1/(1+math.exp(-x)) #訓練神經元 def train(W_out, W_mid,data,real): #中間層神經元輸入和輸出層神經元輸入 Net_in = DataFrame(data,index=['
input1','input2','theata'],columns=['a']) Out_in = DataFrame(0,index=['input1','input2','input3','input4','theata'],columns=['a']) Out_in.loc['theata'] = -1 #中間層和輸出層神經元權值 W_mid_delta = DataFrame(0,index=['input1','input2','theata'],columns=['mid1','mid2','mid3','mid4']) W_out_delta
= DataFrame(0,index=['input1','input2','input3','input4','theata'],columns=['a']) #中間層的輸出 for i in range(0,4): Out_in.iloc[i] = sigmoid(sum(W_mid.iloc[:,i]*Net_in.iloc[:,0])) #輸出層的輸出/網路輸出 res = sigmoid(sum(Out_in.iloc[:,0]*W_out.iloc[:,0])) #誤差 error = abs(res-real) #輸出層權值變化量 #yita =學習率 yita =0.79 W_out_delta.iloc[:,0] = yita*res*(1-res)*(real-res)*Out_in.iloc[:,0] W_out_delta.iloc[4,0] = -(yita*res*(1-res)*(real-res)) W_out = W_out + W_out_delta #輸出層權值更新 #中間層權值變化量 for i in range(0,4): W_mid_delta.iloc[:,i] = yita*Out_in.iloc[i,0]*(1-Out_in.iloc[i,0])*W_out.iloc[i,0]*res*(1-res)*(real-res)*Net_in.iloc[:,0] W_mid_delta.iloc[2,i] = -(yita*Out_in.iloc[i,0]*(1-Out_in.iloc[i,0])*W_out.iloc[i,0]*res*(1-res)*(real-res)) W_mid = W_mid + W_mid_delta #中間層權值更新 return W_out,W_mid,res,error def reault(data,W_out, W_mid): Net_in = DataFrame(data,index=['input1','input2','theata'],columns=['a']) Out_in = DataFrame(0,index=['input1','input2','input3','input4','theata'],columns=['a']) Out_in.loc['theata'] = -1 #中間層的輸出 for i in range(0,4): Out_in.iloc[i] = sigmoid(sum(W_mid.iloc[:,i]*Net_in.iloc[:,0])) #輸出層的輸出/網路輸出 res = sigmoid(sum(Out_in.iloc[:,0]*W_out.iloc[:,0])) return res for i in range(0,9): W_out,W_mid,res,error = train(W_out,W_mid,x[0:,i],y[i]) res1 = reault([0.38 ,0.49,-1 ], W_out, W_mid) res2 = reault([0.29 ,0.47 ,-1], W_out, W_mid) print(res1,res2)

 

 

結果:

0.38217388768014054 0.3785184154678706