Keras – 从目录结构中获取字符串标签

我正在尝试使用Keras编写一个卷积神经网络(CNN)。我的数据集包含20,000张图片,分为250个类别,目录结构如下:

dataset/    class1/        1.png        2.png        ...    class2/        ...    ...

据我所知,加载图片和标签最简单的方法是结合使用ImageDataGeneratorflow_from_directory()。以下是一个最简工作示例:

from keras.layers import Activation, Convolution2D, MaxPooling2Dfrom keras.models import Sequentialfrom keras.preprocessing.image import ImageDataGeneratorif __name__ == '__main__':        # 输入图像尺寸    img_rows, img_cols = 225, 225    input_shape = (img_rows, img_cols, 1)    model = Sequential()    model.add(Convolution2D(64, 15, 15, input_shape=input_shape, subsample=(3, 3)))    model.add(Activation('relu'))    model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))    model.compile(loss='hinge', optimizer='adadelta', metrics=['accuracy'])    data = ImageDataGenerator()    train_data = data.flow_from_directory(directory='dataset', color_mode='grayscale', target_size=(img_rows, img_cols))    model.fit_generator(train_data, 100, 12)

然而,这会导致以下错误:

Exception: Error when checking model target: expected maxpooling2d_1 to have 4 dimensions, but got array with shape (32, 250)

其中32是batch_size,250是类别数量。

这是我获取图片/标签的方式有问题吗?


回答:

我的问题并不是标签是字符串,而是CNN架构错误。在MaxPooling2D之后添加一个Flatten()层后,我现在能够将网络的输出映射到我的标签上。

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

发表回复

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