使用fit_generator时形状不匹配的错误(Keras)

我试图构建一个简单的分类卷积神经网络(CNN),使用以下代码将1233张图像分为4个类别:

unclassified_datagen = keras.preprocessing.image.ImageDataGenerator(    rescale=1. / 255,    horizontal_flip=True)unclassified_generator = train_datagen.flow_from_directory(    'data/unclassified',    target_size=(120, 120),    batch_size=1233,    class_mode='input',    shuffle=False,)model_unclassified = keras.Sequential()model_unclassified.add(layers.Conv2D(1233, (3, 3), input_shape=(120, 120, 3), padding="SAME"))model_unclassified.add(layers.Dense(64, activation='relu'))model_unclassified.add(layers.Dense(4, activation='sigmoid'))model_unclassified.compile(loss='sparse_categorical_crossentropy',                           optimizer='rmsprop',                           metrics=['accuracy'])model_unclassified.fit_generator(unclassified_generator, epochs=1)

但我得到了以下错误: ValueError: Error when checking target: expected dense_2 to have shape (120, 120, 1) but got array with shape (120, 120, 3)

我做错了什么?


回答:

你应该添加一个Flatten层,因为Conv2D为每个样本返回一个3D数组:

model_unclassified = keras.Sequential()model_unclassified.add(layers.Conv2D(1233, (3, 3), input_shape=(120, 120, 3), padding="SAME"))model_unclassified.add(layers.Flatten())model_unclassified.add(layers.Dense(64, activation='relu'))model_unclassified.add(layers.Dense(4, activation='sigmoid'))

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中创建了一个多类分类项目。该项目可以对…

发表回复

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