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

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
    herosunly 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")
    
    点赞 评论
  • herosunly
    herosunly 2021-03-19 13:07

    根据经验,如果训练数据不是很多的话,那就过拟合了,建议把模型结构设计的再简单点。

    点赞 1 评论

相关推荐