Tensorflow 当predict_generator在多类分类问题的同一数据集上工作时,为什么keras predict_类失败?

Tensorflow 当predict_generator在多类分类问题的同一数据集上工作时,为什么keras predict_类失败?,tensorflow,keras,Tensorflow,Keras,我有6类图像,正在尝试使用基于MobileNetv2的迁移学习来训练模型 我首先创建一个ImageDataGenerator,然后使用“子集”功能将其拆分为单独的序列和测试流 # Rescale all images by 1./255 and apply image augmentation train_test_datagen = keras.preprocessing.image.ImageDataGenerator( rescale=1./255, validation_

我有6类图像,正在尝试使用基于MobileNetv2的迁移学习来训练模型

我首先创建一个ImageDataGenerator,然后使用“子集”功能将其拆分为单独的序列和测试流

# Rescale all images by 1./255 and apply image augmentation
train_test_datagen = keras.preprocessing.image.ImageDataGenerator(
    rescale=1./255,
    validation_split=0.5)

# Flow training images in batches of 20 using train_datagen generator
train_generator = train_test_datagen.flow_from_directory(
                train_test_dir,  # Source directory for the training images
                target_size=(image_size, image_size),
                batch_size=batch_size,shuffle=True,
                class_mode='categorical',
    subset='training')

# Flow validation images in batches of 20 using test_datagen generator
validation_generator = train_test_datagen.flow_from_directory(
                train_test_dir, # Source directory for the validation images
                target_size=(image_size, image_size),
                batch_size=1,shuffle=False,
                class_mode='categorical',
    subset='validation')

然后创建并训练模型:

# Create the base model from the pre-trained model MobileNet V2
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                               include_top=False,
                                               weights='imagenet')

class_count = len(train_generator.class_indices)

model = tf.keras.Sequential([
  base_model,
  keras.layers.GlobalAveragePooling2D(),
  keras.layers.Dense(class_count, activation='softmax')
])

model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.0001),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

epochs = 5
steps_per_epoch = train_generator.n // batch_size
validation_steps = validation_generator.n // batch_size

history = model.fit_generator(train_generator,
                              steps_per_epoch = steps_per_epoch,
                              epochs=epochs,
                              workers=4,
                              #pickle_safe=True,
                              validation_data=validation_generator,
                              validation_steps=validation_steps)

到目前为止还不错。但是,尽管我可以从
predict\u生成器
获得原始softmax输出:

class_predictions = model.predict_generator(
    validation_generator,
    20)
我无法从预科班得到任何东西:

class_predictions = model.predict_classes(
    validation_generator
)
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
1类预测=模型。预测类(
---->2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.2.2.2.2
3 )
预测类中的~/anaconda3/envs/tensorflow\u p36/lib/python3.6/site-packages/tensorflow\u core/python/keras/engine/sequential.py(self、x、批大小、详细)
324类预测的numpy数组。
325     """
-->326 proba=self.predict(x,批大小=批大小,详细=详细)
327如果概率形状[-1]>1:
328返回概率argmax(轴=-1)
预测中的~/anaconda3/envs/tensorflow\u p36/lib/python3.6/site-packages/tensorflow\u core/python/keras/engine/training.py
924最大队列大小=最大队列大小,
925名工人=工人,
-->926使用多处理=使用多处理)
927
928 def重置_指标(自我):
预测中的~/anaconda3/envs/tensorflow\u p36/lib/python3.6/site-packages/tensorflow\u core/python/keras/engine/training\u generator.py
637名工人=1人,
638使用多处理=假):
-->639模型。验证或推断批次大小(批次大小,步骤,x)
640返回预测单元发生器(
641型,
~/anaconda3/envs/tensorflow\u p36/lib/python3.6/site-packages/tensorflow\u core/python/keras/engine/training.py in\u validate\u或\u expert\u batch\u size(self、batch\u size、steps、x)
1831'不能为给定的指定'batch_size'参数'
1832'输入类型。收到的输入:{},批处理大小:{}。格式(
->1833 x,批次(单位尺寸)
1834年回归
1835
ValueError:不能为给定的输入类型指定'batch\u size'参数。收到的输入:,batch\u size:32
这对于以前的二进制交叉熵模型很有效,但是对于这个分类交叉熵模型,predict类不起作用


知道会出什么问题吗?

predict\u classes
仅适用于顺序模型,需要一个numpy数组而不是生成器对象

Arguments
x   input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs).
batch_size  integer.
verbose     verbosity mode, 0 or 1.
最好避免这种情况,正如医生所说:

警告:此函数已弃用。它将在2021-01-01之后删除。更新说明:请改用:*np.argmax(model.predict(x),axis=-1),如果您的模型进行多类分类(例如,如果使用softmax最后一层激活)。*(model.predict(x)>0.5)。astype(“int32”),如果您的模型进行二进制分类(例如,如果使用sigmoid最后一层激活)


ref:

目前在线文档中缺少弃用消息,但上述方法仍然可用。
Arguments
x   input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs).
batch_size  integer.
verbose     verbosity mode, 0 or 1.