[英]Neural network always predicts the same class in each epoch
我正在嘗試使用 DNN 實現一個 mnist 分類器。 然而,我得到的結果很奇怪。 在此處輸入圖片說明
在這個時代,這個模型只能正確預測數字“0”,而對所有其他數字的預測都是錯誤的。 該模型只能預測每個時期的特定數字。 (這樣的預測數在每個時期都不一樣)
這就是我獲取數據集的方式。
from sklearn.datasets import fetch_openml
from keras.utils.np_utils import to_categorical
import numpy as np
from sklearn.model_selection import train_test_split
import time
x, y = fetch_openml('mnist_784', version=1, return_X_y=True)
x = (x/255.).astype('float32')
y = to_categorical(y)
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.15, random_state=42)
對於這部分,這是我的模型。 具有 Relu 和 softmax 激活函數的兩隱藏層 DNN,誤差函數的交叉熵損失。 我不確定我的反向傳播是否正確。 我認為這里有問題。
import numpy as np
class NN():
def __init__(self, input_size, hidden_1_size, hidden_2_size, output_size):
self.input_data = np.random.randn(1, input_size)
self.w1 = np.random.randn(input_size, hidden_1_size)
self.b1 = np.random.randn(1, hidden_1_size)
self.w2 = np.random.randn(hidden_1_size, hidden_2_size)
self.b2 = np.random.randn(1, hidden_2_size)
self.w3 = np.random.randn(hidden_2_size, output_size)
self.b3 = np.random.randn(1, output_size)
def Sigmoid(self, z):
return np.clip(1 / (1.0 + np.exp(-z)), 1e-8, 1 - (1e-7))
def Softmax(self, z):
y_logit = np.exp(z - np.max(z, 1, keepdims=True))
y = y_logit / np.sum(y_logit, 1, keepdims=True)
return y
def Relu(self, z):
return np.maximum(z, 0)
def acc_test(self, input_data):
tmp_h1 = self.Relu(input_data.dot(self.w1) + self.b1)
tmp_h2 = self.Relu(self.h1_out.dot(self.w2) + self.b2)
tmp_out = self.Softmax(self.h2_out.dot(self.w3) + self.b3)
return tmp_out
# Feed Placeholder
def forward(self, input_data):
self.input_data = input_data
self.h1_out = self.Relu(input_data.dot(self.w1) + self.b1)
self.h2_out = self.Relu(self.h1_out.dot(self.w2) + self.b2)
self.output_layer = self.Softmax(self.h2_out.dot(self.w3) + self.b3)
# Backward Propagation
def backward(self, target):
# corss_entropy loss derivative
Loss_to_z_grad = (self.output_layer - target) # correct
self.b3_grad = Loss_to_z_grad
self.w3_grad = self.h2_out.T.dot(Loss_to_z_grad) # correct
Activation_2_grad = Loss_to_z_grad.dot(self.w3.T) # correct
Activation_2_grad[Activation_2_grad<0] = 0
self.b2_grad = Activation_2_grad
self.w2_grad = self.h1_out.T.dot(Activation_2_grad)
Activation_1_grad = Activation_2_grad.dot(self.w2.T)
Activation_1_grad[Activation_1_grad<0] = 0
self.b1_grad = Activation_1_grad
self.w1_grad = self.input_data.T.dot(Activation_1_grad)
# Update Weights
def update(self, learning_rate=1e-06):
self.w1 = self.w1 - learning_rate * self.w1_grad
self.b1 = self.b1 - learning_rate * self.b1_grad
self.w2 = self.w2 - learning_rate * self.w2_grad
self.b2 = self.b2 - learning_rate * self.b2_grad
self.w3 = self.w3 - learning_rate * self.w3_grad
self.b3 = self.b3 - learning_rate * self.b3_grad
# Loss Functions
def cross_entropy(Y, Y_prediction):
return -(np.matmul(Y, np.log(Y_prediction)) + np.matmul((1-Y), np.log(1-Y_prediction)))
def print_accuracy(self):
correct = 0
loss = 0
for i in range(y_val.shape[0]):
self.acc_test(x_val[i])
index = self.output_layer
one_hot = 0
for check in range(y_val[i].shape[0]):
if y_val[i][check] == 1:
one_hot = check
break
if np.argmax(index) == one_hot:
correct += 1
# print('correct: ',check)
# else:
# print('incorrect: ', check)
print('accuracy = ', correct/y_val.shape[0])
import random
mnist_nn = NN(input_size = 784, hidden_1_size = 200, hidden_2_size = 200,output_size = 10)
for i in range(1000):
for j in range(2000):
index = random.randint(0,x_train.shape[0]-1)
mnist_nn.forward(x_train[[index]])
mnist_nn.backward(y_train[index])
mnist_nn.update()
print(i)
mnist_nn.print_accuracy()
准確度非常低,因為它只能預測一個數字。 我看過這篇文章, 神經網絡總是預測同一個類,我確實將Relu更改為leaky Relu,但它並沒有真正起作用。
我認為我的數據集應該沒問題,因為我使用相同的數據集來訓練帶有 pytorch 的 DNN,並且它有效。 此外,權重和偏差的初始值是隨機值。
我快速瀏覽了您的代碼,如果我理解正確,那么可能存在一些問題:
y * log(y_pred)
,然后取整個批次的平均值,因此最終得到標量值損失。Activation_2_grad[Activation_2_grad<0] = 0
應該是Activation_2_grad[self.h2_out < 0] = 0
。嘗試使用 tanh 來確保算法正常工作。 Relu 可能很挑剔,只有在您可以控制數據集的情況下才能真正處理它,因為它需要類的相當均勻的分布。 (Leaky_relu 也很難衡量)
就您的反向傳播是否正常工作而言,您最好使用 keras 順序模型,即:
model = tf.keras.Sequential([
input_layer,
tf.keras.layers.Dense(128, activation="tanh"),
tf.keras.layers.Dense([number of outputs], activation='softmax'),
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.