【问题标题】:Implementing my first keras model: Why am I getting a mismatch in input arrays?实现我的第一个 keras 模型:为什么我的输入数组不匹配?
【发布时间】:2020-07-17 08:47:50
【问题描述】:

我正在尝试实现我的第一个 keras 模型。 我关注了这个tutorial

我正在运行以下版本的模块:

scipy: 1.4.1
numpy: 1.18.1
matplotlib: 3.1.3
pandas: 1.0.3
statsmodels: 0.11.0
sklearn: 0.22.1
Using TensorFlow backend.
keras: 2.3.1

这是我的 createmodel.py 的代码

from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

img_rows, img_cols = 28, 28

x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)

x_train = x_train / 255
x_test = x_test / 255

from keras.utils import to_categorical
num_classes = 10

y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)

from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
     activation='relu',
     input_shape=(img_rows, img_cols, 1)))

model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Dropout(0.25))

model.add(Flatten())

model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss='sparse_categorical_crossentropy',
      optimizer='adam',
      metrics=['accuracy'])

batch_size = 128
epochs = 10

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
model.save("test_model.h5")

但是当我运行脚本时,我得到以下错误,当模型被训练时(在 model.fit 行):

ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (10,)

我了解我的数组维度不匹配。但由于我是 keras 和 python 的新手,我需要你的启动。 感谢您的帮助!

【问题讨论】:

    标签: python python-3.x keras


    【解决方案1】:
    model.compile(loss='sparse_categorical_crossentropy',
          optimizer='adam',
          metrics=['accuracy'])
    

    使用 loss=keras.losses.categorical_crossentropy 代替 loss='sparse_categorical_crossentropy'

    model.compile(loss=keras.losses.categorical_crossentropy,
          optimizer='adam',
          metrics=['accuracy'])
    

    【讨论】:

      【解决方案2】:

      好的,我会马上回答我自己的问题,这样可以帮助遇到我这种情况的其他人。

      here所述,编译模型时教程有错误-需要使用

      categorical_crossentropy
      

      当使用 one-hot-encoded 向量编译时。

      区别描述here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 1970-01-01
        • 1970-01-01
        • 2010-12-13
        相关资源
        最近更新 更多