Python 으로 BP 신경 망 실현(코드 첨부)
BP 신경 망
모든 코드
https://github.com/lawlite19/MachineLearning_Python/blob/master/NeuralNetwok/NeuralNetwork.py
신경 망 모델
먼저 3 층 의 신경 망 을 소개 하 는데,아래 그림 과 같다.
입력 층(input layer)에는 유닛 이 세 개 있 습 니 다(

보충 하기 위 한 bias,보통 1)

j 층 의 i 번 째 격려 를 나타 내 는 것 을 유닛 유닛 유닛 이 라 고도 부른다.

j 층 에서 j+1 층 까지 비 치 는 가중치 행렬 은 각 변 의 가중치 이다.

그래서 얻 을 수 있다.
내포 층:



출력 층

,
그 중 S 형 함수

격려 함수
알 수 있다

3x4 를 위 한 행렬,

1x4 행렬

==>j+1 의 단원 수 x(j 층 의 단원 수+1)
대가 함수
마지막 출력 을 가정 합 니 다.

즉,출력 층 에 K 개의 단원 이 있 음 을 나타 낸다

,
그 중

i 개 단원 출력 과 논리 회 귀 를 대표 하 는 대가 함수

차이 가 많 지 않 습 니 다.모든 출력 을 누적 하 는 것 입 니 다.(모두 K 개의 출력 이 있 습 니 다)
정규 화
L-->모든 층 의 개수

-->제 l 층 유닛 개수
정규 화 후의 대가 함 수 는?


모두 L-1 층 이 있 고 그 다음 에 각 층 에 대응 하 는 theta 행렬 을 누적 합 니 다.편향 항목 에 대응 하 는 theta(0)를 포함 하지 않도록 주의 하 십시오.
정규 화 된 대가 함수 구현 코드:
#
def nnCostFunction(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):
length = nn_params.shape[0] # theta
# theta1 theta2
Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1)
# np.savetxt("Theta1.csv",Theta1,delimiter=',')
m = X.shape[0]
class_y = np.zeros((m,num_labels)) # y 0-9, 0/1
# y
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1) # reshape(1,-1)
''' theta1 theta2 , 1 '''
Theta1_colCount = Theta1.shape[1]
Theta1_x = Theta1[:,1:Theta1_colCount]
Theta2_colCount = Theta2.shape[1]
Theta2_x = Theta2[:,1:Theta2_colCount]
# theta^2
term = np.dot(np.transpose(np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1)))),np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1))))
''' , 1 bias'''
a1 = np.hstack((np.ones((m,1)),X))
z2 = np.dot(a1,np.transpose(Theta1))
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m,1)),a2))
z3 = np.dot(a2,np.transpose(Theta2))
h = sigmoid(z3)
''' '''
J = -(np.dot(np.transpose(class_y.reshape(-1,1)),np.log(h.reshape(-1,1)))+np.dot(np.transpose(1-class_y.reshape(-1,1)),np.log(1-h.reshape(-1,1)))-Lambda*term/2)/m
return np.ravel(J)
역방향 전파 BP위의 정방 향 전 파 는 J(θ),경사도 하강 법 을 사용 하려 면 그것 의 경사도 를 구 해 야 한다.
BP 역방향 전파 의 목적 은 바로 대가 함수 의 경사도 를 구 하 는 것 이다.
4 층 의 신경 망 을 가정 하면,

l 층 j 개 단원 의 오차

《===》

(양 적 으로)


없다

입력 에 오차 가 없 기 때 문 입 니 다.
S 형 함수 때문에

의 역수:

,
그래서 위 에 거.

화해시키다

전방 향 전파 에서 계산 할 수 있다
역방향 전파 계산 경사도 의 과정 은:

(

대문자 입 니 다.

)
for i=1-m:-

-정방 향 전파 계산

(l=2,3,4...L)
-역 계산

、

...

;
-

-


마지막.

대가 함수 의 경사도
구현 코드:
#
def nnGradient(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):
length = nn_params.shape[0]
Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1)
m = X.shape[0]
class_y = np.zeros((m,num_labels)) # y 0-9, 0/1
# y
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1) # reshape(1,-1)
''' theta1 theta2 , 1 '''
Theta1_colCount = Theta1.shape[1]
Theta1_x = Theta1[:,1:Theta1_colCount]
Theta2_colCount = Theta2.shape[1]
Theta2_x = Theta2[:,1:Theta2_colCount]
Theta1_grad = np.zeros((Theta1.shape)) #
Theta2_grad = np.zeros((Theta2.shape)) #
Theta1[:,0] = 0;
Theta2[:,0] = 0;
''' , 1 bias'''
a1 = np.hstack((np.ones((m,1)),X))
z2 = np.dot(a1,np.transpose(Theta1))
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m,1)),a2))
z3 = np.dot(a2,np.transpose(Theta2))
h = sigmoid(z3)
''' ,delta ,'''
delta3 = np.zeros((m,num_labels))
delta2 = np.zeros((m,hidden_layer_size))
for i in range(m):
delta3[i,:] = h[i,:]-class_y[i,:]
Theta2_grad = Theta2_grad+np.dot(np.transpose(delta3[i,:].reshape(1,-1)),a2[i,:].reshape(1,-1))
delta2[i,:] = np.dot(delta3[i,:].reshape(1,-1),Theta2_x)*sigmoidGradient(z2[i,:])
Theta1_grad = Theta1_grad+np.dot(np.transpose(delta2[i,:].reshape(1,-1)),a1[i,:].reshape(1,-1))
''' '''
grad = (np.vstack((Theta1_grad.reshape(-1,1),Theta2_grad.reshape(-1,1)))+Lambda*np.vstack((Theta1.reshape(-1,1),Theta2.reshape(-1,1))))/m
return np.ravel(grad)
BP 는 경사도 의 원인 을 구 할 수 있다.실제로는 체인 식 구도 법칙 을 이용 했다
다음 층 의 단원 은 윗 층 의 단원 을 입력 으로 계산 하기 때문이다.
대체적인 유도 과정 은 다음 과 같다.최종 적 으로 우 리 는 함수 가 이미 알 고 있 는 y 와 매우 가깝다 는 것 을 예측 하고 자 한다.평균 분산 의 경사도 가 이 경사도 방향 을 따라 대가 함 수 를 최소 화 할 수 있다.위 에서 경사도 를 구 하 는 과정 을 대조 할 수 있다.

오 차 를 더 상세 하 게 유도 하 는 과정:

경사도 검사
BP 를 이용 하여 구 하 는 경사도 가 정확 한 지 검사 하 다.
도수 정의 로 검증:

구 한 수치 경사도 는 BP 가 구 한 경사도 와 매우 비슷 해 야 한다.
BP 가 정확 하 다 는 것 을 검증 한 후 에는 검증 경사도 의 알고리즘 을 더 이상 실행 할 필요 가 없다.
구현 코드:
#
#
def checkGradient(Lambda = 0):
''' , , '''
input_layer_size = 3
hidden_layer_size = 5
num_labels = 3
m = 5
initial_Theta1 = debugInitializeWeights(input_layer_size,hidden_layer_size);
initial_Theta2 = debugInitializeWeights(hidden_layer_size,num_labels)
X = debugInitializeWeights(input_layer_size-1,m)
y = 1+np.transpose(np.mod(np.arange(1,m+1), num_labels))# y
y = y.reshape(-1,1)
nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1))) # theta
'''BP '''
grad = nnGradient(nn_params, input_layer_size, hidden_layer_size,
num_labels, X, y, Lambda)
''' '''
num_grad = np.zeros((nn_params.shape[0]))
step = np.zeros((nn_params.shape[0]))
e = 1e-4
for i in range(nn_params.shape[0]):
step[i] = e
loss1 = nnCostFunction(nn_params-step.reshape(-1,1), input_layer_size, hidden_layer_size,
num_labels, X, y,
Lambda)
loss2 = nnCostFunction(nn_params+step.reshape(-1,1), input_layer_size, hidden_layer_size,
num_labels, X, y,
Lambda)
num_grad[i] = (loss2-loss1)/(2*e)
step[i]=0
#
res = np.hstack((num_grad.reshape(-1,1),grad.reshape(-1,1)))
print res
무 작위 초기 화신경 망 은 논리 적 회귀 처럼 theta 를 0 으로 초기 화 할 수 없다.각 변 의 가중치 가 0 이면 모든 신경 원 이 같은 출력 이 고 역방향 전파 에서 도 같은 경사도 를 얻 을 수 있 으 며 최종 적 으로 한 가지 결과 만 예측 할 수 있 기 때문이다.
그래서 0 에 가 까 운 숫자 로 초기 화 해 야 돼 요.
구현 코드
# theta
def randInitializeWeights(L_in,L_out):
W = np.zeros((L_out,1+L_in)) # theta
epsilon_init = (6.0/(L_out+L_in))**0.5
W = np.random.rand(L_out,1+L_in)*2*epsilon_init-epsilon_init # np.random.rand(L_out,1+L_in) L_out*(1+L_in)
return W
예측 하 다.정방 향 전파 예측 결과
구현 코드
#
def predict(Theta1,Theta2,X):
m = X.shape[0]
num_labels = Theta2.shape[0]
#p = np.zeros((m,1))
''' , '''
X = np.hstack((np.ones((m,1)),X))
h1 = sigmoid(np.dot(X,np.transpose(Theta1)))
h1 = np.hstack((np.ones((m,1)),h1))
h2 = sigmoid(np.dot(h1,np.transpose(Theta2)))
'''
h
- np.max(h, axis=1) h ( )
- where ( )
'''
#np.savetxt("h2.csv",h2,delimiter=',')
p = np.array(np.where(h2[0,:] == np.max(h2, axis=1)[0]))
for i in np.arange(1, m):
t = np.array(np.where(h2[i,:] == np.max(h2, axis=1)[i]))
p = np.vstack((p,t))
return p
출력 결과경사도 검사:

무 작위 로 100 개의 필기 숫자 를 표시 합 니 다.

theta 1 가중치 보이 기

훈련 집 예측 정확도

귀 일화 후 훈련 집 예측 정확도

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.