首页 > 解决方案 > keras,使用 RNN 模型的 MNIST 分类,关于输出形状的问题

问题描述

我正在尝试使用 keras 的功能 API 来构建循环神经网络,但遇到了一些关于输出形状的问题,任何帮助将不胜感激。

我的代码:

import tensorflow as tf
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras.layers import Dense, CuDNNLSTM, Dropout
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.utils import normalize
from tensorflow.python.keras.utils import np_utils

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = normalize(x_train, axis=1), normalize(x_test, axis=1)

y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)

feature_input = tf.keras.layers.Input(shape=(28, 28))
x = tf.keras.layers.CuDNNLSTM(128, kernel_regularizer=tf.keras.regularizers.l2(l=0.0004), return_sequences=True)(feature_input)
y = tf.keras.layers.Dense(10, activation='softmax')(x)
model = tf.keras.Model(inputs=feature_input, outputs=y)
opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)
model.compile(optimizer=opt, loss="sparse_categorical_crossentropy", metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3, validation_data=(x_test, y_test))

错误:

ValueError:检查目标时出错:预期密集具有 3 个维度,但得到了形状为 (60000, 10) 的数组

标签: tensorflowkeras

解决方案


您的数据(目标)具有形状(60000, 10)

您的模型的输出(“密集”)具有 shape (None, length, 10)

其中None是批量大小(变量),length是中间维度,表示 LSTM 的“时间步长”,10 是Dense层的单位。

现在,您在 LSTM 中没有任何带有时间步长的序列来处理,这没有任何意义。它将“图像行”解释为连续时间步,将“图像列”解释为独立特征。(如果这不是您的意图,您只是很幸运,它没有给您尝试将图像放入 LSTM 的错误)

return_sequences=False无论如何,您可以使用(丢弃length序列)修复此错误。这并不意味着该模型最适合这种情况。


推荐阅读