使用Keras进行神经网络的无效维度错误

我在使用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)

然后使用它们进行训练和测试。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注