我使用自己的数据集训练了预训练模型(densenet-121),用于二元图像分类。当我使用test_generator时,test_generator的结果看起来不错,但当我运行预测代码时,得到的输出始终是[0. 1.]
。如何解决这个问题?
from keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayfrom keras.models import load_modelimg = load_image('C:/Users/yurtt/Desktop/orkun/a/b/dataset/test2/not/159.png')# 预测类别result = model.predict(img)print(result[0])
输出:
[0. 1.]
我的模型:
from keras.applications.densenet import DenseNet121base_model = DenseNet121(weights='imagenet', include_top=False, input_tensor=Input(shape=input_shape))x = base_model.outputx = GlobalAveragePooling2D()(x)x = Dense(1024, kernel_regularizer=l2(0.0001), bias_regularizer=l2(0.0001))(x)x = BatchNormalization()(x)x = Activation("relu")(x)x = Dropout(0.5)(x)x = Dense(1024, kernel_regularizer=l2(0.0001), bias_regularizer=l2(0.0001))(x)x = BatchNormalization()(x)x = Activation("relu")(x)x = Dropout(0.5)(x)x = Dense(512, kernel_regularizer=l2(0.0001), bias_regularizer=l2(0.0001))(x)x = BatchNormalization()(x)x = Activation("relu")(x)x = Dropout(0.3)(x)prediction = Dense(output_classes, activation=tf.nn.softmax)(x)model = Model(inputs=base_model.input,outputs=prediction)
回答:
您定义了output_classes = 2
。另一方面,预测作为输出层定义为prediction = Dense(output_classes, activation=tf.nn.softmax)(x)
。因此,预测的输出具有2个维度。您可以保持现状,但需要将目标值转换为[0 1]
和[1 0]
,分别表示类别2
和类别1
。
请注意,您也可以将output_classes
设置为1
,以保持目标值为0
和1
。