python - 神经网络总是在每个 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,并且它可以工作。此外,权重和偏差的初始值是随机值。
解决方案
我快速浏览了您的代码,如果我理解正确,则可能存在一些问题:
- 似乎您希望它对 10 个类进行多类分类,但是我相信您的交叉熵函数看起来像二元交叉熵,而不是一般的交叉熵。此外,您正在使用矩阵乘法,而我认为您想对
y * log(y_pred)
10 个输出概率求和,然后在整个批次中取平均值,因此您最终会得到一个标量值损失。 - 我认为,在进行 ReLU 梯度时,您应该在实际激活为负的位置进行剪辑,而不是在梯度为负的位置进行剪辑。
Activation_2_grad[Activation_2_grad<0] = 0
应该如此Activation_2_grad[self.h2_out < 0] = 0
。 - 其余的 backprop 看起来还不错。
推荐阅读
- ocaml - reasonml 中的 -> 和 |> 有什么区别?
- sql-server - 访问 INFORMATION_SCHEMA 需要哪些权限?
- ios - 每个项目的 CollectionView 分页起点
- python - TensorFlow 2.0:如何控制已保存模型的名称?
- cucumber-jvm - 如何在基于环境的黄瓜场景大纲示例中传递参数?
- c++ - 验证没有字符和负输入的输入
- reactjs - Log4js-node 找不到集群模块
- azure-devops - 如何在 Azure Devops 中显示显示构建指标的仪表板
- swift - UITableview 与单元格两个单元格
- javascript - 如何使用 autoColumns 添加标题过滤器?