我在使用Tensorflow 1.5处理Mnist数据集时遇到问题。当我尝试拟合模型时,出现以下错误:
期望dense_input具有2个维度,但得到的数组形状为(60000, 28, 28)
请看我的代码
import tensorflow as tf(train_imgs, train_labels ) , (test_imgs , test_labels ) = tf.keras.datasets.mnist.load_data()model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(512,activation=tf.nn.relu,input_shape = (784,)))model.add(tf.keras.layers.Dense(256,activation=tf.nn.relu) )model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax))model.compile(loss='categorical_crossentropy' , optimizer='adam')model.fit(train_imgs,train_labels,epochs=5)
这是由于版本依赖还是代码错误导致的?
还是我需要重塑数据集?
回答:
import tensorflow as tf(train_imgs, train_labels ) , (test_imgs , test_labels ) = tf.keras.datasets.mnist.load_data()
你需要重塑数据。像你这样的多层感知机(MLP)不接受二维数组。通过以下方式重塑:
train_x = train_imgs.reshape(60000, 28*28)test_x = test_imgs.reshape(10000, 28*28)# 你需要对标签进行独热编码from sklearn.preprocessing import LabelEncoder, OneHotEncoderdef one_hot_encode(labels, universe=None): """ 这个独热编码器可以处理分类和数值数据。 如果标签不包含所有类别/数字,或者你希望独热编码按特定顺序(而不是自动的字母顺序)进行,请使用`universe=`。 `labels=` 是要进行独热编码的类别/数字标签。 """ if universe is None: universe = sorted(list(set(labels))) nums = LabelEncoder().fit(universe).transform(labels) one_hot = OneHotEncoder(sparse=False).fit(np.array(universe).reshape(-1, 1))\ .transform(np.array(nums).reshape(-1, 1)) return one_hottrain_labels_1h = one_hot_encode(train_labels)test_labels_1h = one_hot_encode(test_labels)# 定义轮数epochs = 5# 定义模型def create_model(): model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(512,activation=tf.nn.relu,input_shape = (784,))) model.add(tf.keras.layers.Dense(256,activation=tf.nn.relu) ) model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) model.compile(loss='categorical_crossentropy' , optimizer='adam') return model# "实例化"一个模型model = create_model()# 然后运行model.fit(train_x, train_labels_1h, epochs=epochs)
然后使用它们进行训练和测试。