qq_39716743 2021-03-18 16:11 采纳率: 100%
浏览 1848
已采纳

keras训练二分类模型acc一直0.5 loss一直是0.69怎么办?

import os
import tensorflow as tf
from tensorflow.keras import Sequential, regularizers
from tensorflow.keras.layers import MaxPooling2D, Conv2D, Flatten, Dense, Dropout, Activation, \
    BatchNormalization
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow_core.python.keras import Model




if __name__ == '__main__':
    os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
    image_generator = ImageDataGenerator(rescale=1. / 255)
    image_generator2 = ImageDataGenerator(rescale=1. / 255)

    train_data = image_generator.flow_from_directory("/Users/kongbai/temp/data/train", batch_size=20,
                                                     color_mode='grayscale',
                                                     shuffle=False,

                                                     #
                                                     save_to_dir="/Users/kongbai/temp/data/gen/t",

                                                     save_prefix='train_',

                                                     target_size=(100, 100), class_mode="categorical")
    test_data = image_generator.flow_from_directory("/Users/kongbai/temp/data/test", batch_size=1,
                                                    color_mode='grayscale',
                                                    shuffle=False,

                                                    # save_to_dir=SAVE_PATH,
                                                    #
                                                    # save_prefix='gen',

                                                    target_size=(100, 100), class_mode='categorical')
    vailted_data = image_generator.flow_from_directory("/Users/kongbai/temp/data/vailted", batch_size=20,
                                                       color_mode='grayscale',
                                                       shuffle=True,

                                                       save_to_dir="/Users/kongbai/temp/data/gen/v",

                                                       save_prefix='vailted_',

                                                       target_size=(100, 100), class_mode='categorical')

    model = Sequential()
    model.add(Conv2D(32, 3, 1, input_shape=(100, 100, 1), activation='relu'))

    model.add(MaxPooling2D(3))
    model.add(Conv2D(128, 1, padding='same'))
    model.add(Conv2D(64, 1))

    model.add(Dropout(0.1))

    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(0.4))
    model.add(Dense(2, activation='softmax', ))

    model.compile(loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False),
                  optimizer=tf.keras.optimizers.SGD(1e-4),
                  metrics=['accuracy'])
    model.summary()
    model.fit_generator(train_data, shuffle=True, steps_per_epoch=20, epochs=20, workers=16,
                        validation_data=vailted_data,
                        validation_steps=20)



    model.save("demo.h5")

训练的acc一直在0.5,loss直接固定在0.69了...............这就是个识别一张照片上的两个人是否是同一个人的网络呀,也没什么东西了呀  损失函数也改过Adam 也是一样的  有大佬帮忙看看吗?

  • 写回答

2条回答 默认 最新

  • herosunly Python领域优质创作者 2021-03-19 22:08
    关注

    帮你改了下代码,路径你自己再改改,验证集acc能跑到0.8以上了。

    import os
    import tensorflow as tf
    from tensorflow.keras import Sequential, regularizers
    from tensorflow.keras.layers import MaxPooling2D, Conv2D, Flatten, Dense, Dropout, Activation, \
        BatchNormalization
    from tensorflow.keras.optimizers import Adam, SGD
    from tensorflow.keras.preprocessing.image import ImageDataGenerator
    from tensorflow.keras.applications.resnet50 import ResNet50
    
    
    if __name__ == '__main__':
        os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
        image_generator = ImageDataGenerator(rescale=1. / 255)
        image_generator2 = ImageDataGenerator(rescale=1. / 255)
    
        train_data = image_generator.flow_from_directory("mg", batch_size=32,
                                                         color_mode='grayscale',
                                                         shuffle=True,
    
                                                         # #
                                                         # save_to_dir="/Users/kongbai/temp/data/gen/t",
                                                         #
                                                         # save_prefix='train_',
                                                         target_size=(256, 256), class_mode="categorical")
        test_data = image_generator.flow_from_directory("mg_test", batch_size=32,
                                                        color_mode='grayscale',
                                                        shuffle=True,
    
                                                        # save_to_dir=SAVE_PATH,
                                                        #
                                                        # save_prefix='gen',
    
                                                        target_size=(256, 256), class_mode='categorical')
        vailted_data = image_generator.flow_from_directory("mg_test", batch_size=32,
                                                           color_mode='grayscale',
                                                           shuffle=True,
                                                           target_size=(256, 256), class_mode='categorical')
    
        model = Sequential()
        model.add(Conv2D(filters=32, kernel_size=(5, 5), strides=(2, 2), \
                  input_shape=(256, 256, 1)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
    
        model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
    
        # model.add(Conv2D(32, (3, 3)))
        # model.add(Activation('relu'))
        # model.add(MaxPooling2D(pool_size=(2, 2)))
        #
        # model.add(Conv2D(64, (3, 3)))
        # model.add(Activation('relu'))
        # model.add(MaxPooling2D(pool_size=(2, 2)))
    
        model.add(Flatten())
        model.add(Dropout(0.8))
        model.add(Dense(128))
        model.add(Activation('relu'))
        model.add(Dropout(0.8))  # Dropout防止过拟合
        model.add(Dense(2))
        model.add(Activation('sigmoid'))
    
        # model = tf.keras.applications.ResNet50(input_shape=(224,224, 1), classes=2, weights=None)
    
        model.compile(optimizer=tf.keras.optimizers.Adam(), loss="categorical_crossentropy", metrics=["acc"], )
    
        # model.compile(loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False),
        #               optimizer=tf.keras.optimizers.SGD(1e-4),
        #               metrics=['accuracy'])
        model.summary()
        model.fit_generator(train_data, shuffle=True, epochs=10, workers=16,
                            validation_data=vailted_data)
    
        model.save("demo.h5")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器