簡體   English   中英

使用 Keras 無效維度錯誤的神經網絡

[英]Neural Nets using Keras invalid dimensions error

我正在為 Mnist 數據集開發 Tensorflow 1.5。 當我擬合我的模型時,它說

預期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)

# you need to 1-hot encode your labels
from sklearn.preprocessing import LabelEncoder, OneHotEncoder

def one_hot_encode(labels, universe=None):
    """
    This one hot encoder works with categorical and numeric data, both.
    `universe=` you use, if labels don't contain all categories/numbers.
    Or if you want the 1hot encoding to be in a special order (not the
    automatic alphabetic order).
    `labels=` are the categories/numbers as labels to be 1hot encoded.
    """
    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_hot

train_labels_1h = one_hot_encode(train_labels)
test_labels_1h  = one_hot_encode(test_labels)

# define epochs
epochs = 5

# define model
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

# "instanciate" a model
model = create_model()

# then run
model.fit(train_x, train_labels_1h, epochs=epochs)

然后將它們用於訓練和測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM