Keras CNN模型始终返回[0.5 0.5]

Keras CNN模型始终返回[0.5 0.5],keras,deep-learning,computer-vision,cnn,Keras,Deep Learning,Computer Vision,Cnn,有人能帮我解决这个问题吗?我的模型总是返回1类。源代码如下: 我想对图像进行分类(二进制)。该模型具有良好的精度。现在,我需要测试新图像的模型,我加载模型并尝试预测类,但它总是返回0 batch_size = 30 epochs = 50 IMG_HEIGHT = 224 IMG_WIDTH = 224 image_gen_train = ImageDataGenerator( rotation_range=15,

有人能帮我解决这个问题吗?我的模型总是返回1类。源代码如下: 我想对图像进行分类(二进制)。该模型具有良好的精度。现在,我需要测试新图像的模型,我加载模型并尝试预测类,但它总是返回0

    batch_size = 30
    epochs = 50
    IMG_HEIGHT = 224
    IMG_WIDTH = 224
    image_gen_train = ImageDataGenerator(
            rotation_range=15,
            width_shift_range=0.01,
            height_shift_range=0.01,
            rescale=1./255,
            shear_range=0.1,
            fill_mode='nearest',
            validation_split=0.2)
    
    train_data_gen = image_gen_train.flow_from_directory(batch_size=batch_size,
                                                         directory=dataset_dir,
                                                         shuffle=True,
                                                         target_size=(IMG_HEIGHT, IMG_WIDTH),
                                                         subset='training',
                                                         class_mode='binary') # set as training data
    
    val_data_gen = image_gen_train.flow_from_directory(batch_size=batch_size,
                                                         directory=dataset_dir,
                                                         shuffle=False,
                                                         target_size=(IMG_HEIGHT, IMG_WIDTH),
                                                         subset='validation',
                                                         class_mode='binary') # set as validation data
    
    sample_training_images, _ = next(train_data_gen)
    # This function will plot images in the form of a grid with 1 row and 5 columns where images are placed in each column.
    def plotImages(images_arr):
        fig, axes = plt.subplots(1, 4, figsize=(20,20))
        axes = axes.flatten()
        for img, ax in zip( images_arr, axes):
            ax.imshow(img)
            ax.axis('off')
        plt.tight_layout()
        plt.savefig('xray_new.png')
        plt.clf()
    plotImages(sample_training_images[:4])
    
    #the model
    model = Sequential()
    model.add(Conv2D(64, kernel_size= (3,3), input_shape=(IMG_HEIGHT, IMG_WIDTH, 3),padding='same'))
    
    model.add(BatchNormalization(momentum=0.5, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    model.add(Conv2D(64, kernel_size=(3,3), padding='same'))
    model.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.35))
    
    model.add(Conv2D(128, kernel_size =(3,3),padding='same'))
    model.add(BatchNormalization(momentum=0.2, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    model.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    model.add(Conv2D(128,(3,3), padding='same' ))
    model.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.35))
    
    model.add(Conv2D(256, kernel_size = (3,3), padding='same'))
    model.add(BatchNormalization(momentum=0.2, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    model.add(Conv2D(256, kernel_size= (3,3) ,padding='same'))
    model.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
    model.add(LeakyReLU(alpha=0.1))
    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.35))
    
    model.add(Flatten())
    model.add(Dense(256))
    model.add(LeakyReLU(alpha=0.1))
    model.add(BatchNormalization())
    model.add(Dense(1, activation='sigmoid'))
    
    model.compile(optimizer='adam',
                  loss='binary_crossentropy',
                  metrics=['accuracy'])
    #model.summary()
    model.save("model.h5")
    history = model.fit_generator(
        train_data_gen,
        steps_per_epoch= train_data_gen.samples // batch_size,
        epochs=epochs,
        validation_data=val_data_gen,
        validation_steps= val_data_gen.samples // batch_size,verbose=1)
但是当我测试模型时,它总是输出一个类:

    filepath = 'model.h5'
    model = load_model(filepath,compile=True)
    def test(model,image_path):
      
      test_image = image.load_img(image_path, target_size=(IMG_HEIGHT, IMG_WIDTH))
      test_image = image.img_to_array(test_image)
      test_image = np.expand_dims(test_image, axis=0)
    
      # predict the result
      prediction = model.predict(test_image)
    
      print(prediction)
      if prediction[0][0] == 1:
          my = 'Normal'
      else:
          my = 'Asthma'
      print(my)
      prediction = np.argmax(prediction)
      labels = (train_data_gen.class_indices)
      labels = dict((v,k) for k,v in labels.items())
      return labels[prediction]

我真的很感谢你的帮助

我想你忘了将输入图像除以
255。
在测试部分。

我添加了test\u image=test\u image/255,但它仍然只能预测一个类。[0.5]概率在训练模型之前保存模型,然后加载它,但它是未训练的版本,这很奇怪。您应该在
model.fit\u生成器之后放置
model.save