CNN 模型训练问题(%16 准确率)

时间:2021-01-16 13:55:58

标签: python tensorflow keras neural-network conv-neural-network

我有一个关于神经网络的作业。我需要开发一个花卉识别应用程序。

首先,我尝试学习如何对 that link 中的猫狗照片进行分类并应用自己。之后,我开始将该模型应用于带有 5 个标签的花卉识别。

虽然模型运行正常,但训练不成功,准确率为 %16。

这里是准确度图。

Classification Accuracy Plot

def define_model_one_block():
 model = Sequential()
 model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))
 model.add(MaxPooling2D((2,2)))
 model.add(Flatten())
 model.add(Dense(128,activation='relu',kernel_initializer='he_uniform'))
 model.add(Dense(1,activation='sigmoid'))
 opt = SGD(lr=0.001,momentum=0.9)
 model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['accuracy'])
 return model
def run_model_one_block():
    model = define_model_one_block()
    datagen = ImageDataGenerator(rescale=1.0/255.0)
    #prepare train and test iterators
    train_it = datagen.flow_from_directory('flowers/train/',
                class_mode='binary',batch_size=64,target_size=(200,200))
    test_it = datagen.flow_from_directory('flowers/test/',
            class_mode='binary', batch_size=64, target_size=(200, 200))
    #fit model
    history = model.fit_generator(train_it,steps_per_epoch=len(train_it),
            validation_data=test_it,validation_steps=len(test_it),epochs=20,verbose=0)
    #evaluate model
    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)
    print('>%.3f' % (acc*100.0))
    #plot of learning curves
    summarize_diagnostics(history)

1 个答案:

答案 0 :(得分:1)

您有 5 个课程。因此,您不再进行二元分类。以下是您需要更改的内容

In train_it and test_it  change class_mode to 'categorical'
code model.add(Dense(1,activation='sigmoid')) should be changed to
model.add(Dense(5,activation='softmax'))
code  model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['accuracy'])
should be changed to
model.compile(optimizer=opt, loss='categorical_crossentropy',metrics=['accuracy'])

此外,我认为您的模型不够复杂,无法达到高准确度。试试看,如果效果不好,请按以下方式修改

IMG_HEIGHT=200
IMG_WIDTH=200
model = tf.keras.Sequential([
    Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 3)),
    MaxPooling2D(),
    Conv2D(32, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 3)),
    MaxPooling2D(),
    Conv2D(64, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 3)),
    MaxPooling2D(),
    Conv2D(128, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 3)),
    MaxPooling2D(),
    Conv2D(256, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 3)),
    MaxPooling2D(),
    Flatten(),
    Dense(128, activation='relu'),
    Dropout(.3),
    Dense(64, activation='relu'),
    Dropout(.3),
    Dense(5, activation='softmax')
])