微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获得固定精度:使用 Google Colab 在 Keras 模型中为 0.5000,有时为 0.0000e+00

如何解决获得固定精度:使用 Google Colab 在 Keras 模型中为 0.5000,有时为 0.0000e+00

我正在使用 Google Colab 上的 Keras 训练一个 CNN 模型进行二进制图像分类,问题是当我使用 Sigmoid 函数时,我的准确度固定在 0.5000,当我将指标更改为“acc”时,我得到 0.000e+00 作为准确性。此外,当我将激活函数更改为“softmax”时,我的模型开始学习。

Ps:我正在使用 google colab,其中 Tensorflow 版本为 2.5.0

我的代码

def define_model(input_shape,num_classes):
    model=resnet50(include_top = False,weights = 'imagenet',input_shape = input_shape)
    x = model.output
    x = GlobalAveragePooling2D()(x)
    preds = Dense(num_classes,activation='sigmoid')(x) 
    model = Model(inputs=model.input,outputs=preds)
    return model

def train(epochs):   

    train_generator = ImageDataGenerator(rescale=1.0/255.0,vertical_flip=True,horizontal_flip=True)                                                                                                                           
    test_generator = ImageDataGenerator(rescale=1.0/255.0)

    train_generator = train_generator.flow_from_directory(
        'trainset/',target_size=(image_size,image_size),batch_size=BATCH_SIZE_TRAINING,seed = 7)

    validation_generator = test_generator.flow_from_directory(
        'testset/',batch_size=BATCH_SIZE_VALIDATION,seed = 7)

    input_shape = (CHANNELS,image_size,image_size) if K.image_data_format() == 'channels_first' \
            else (image_size,CHANNELS) 
            
    model = define_model(input_shape,NUM_CLASSES)

    opt = optimizers.Adam(learning_rate=1e-6,beta_1=0.9,beta_2=0.99,amsgrad=False)

    model.summary()
    model.compile(loss='binary_crossentropy',optimizer=opt,metrics=['acc'])
               
    filepath=path+"weights-improvement-{epoch:02d}-vacc:{val_accuracy:.2f}-tacc:{accuracy:.2f}.hdf5"
    '''cb_early_stopper = EarlyStopping(monitor = 'val_accuracy',mode='min',verbose=1,patience = EARLY_STOP_PATIENCE)
    cb_checkpointer = ModelCheckpoint(filepath = filepath,monitor = 'val_accuracy',save_best_only = True,mode = 'auto')
    reduce_lr = ReduceLROnPlateau(monitor='val_accuracy',factor=0.25,patience=5,min_lr=1e-7)'''
    fit_history = model.fit(train_generator,epochs = NUM_EPOCHS,validation_data=validation_generator,class_weight=class_weights)
#            callbacks = [cb_checkpointer,cb_early_stopper,reduce_lr],return model,fit_history
        
def main():
    
    start_time = time()
    model,fit_history = train(epochs=NUM_EPOCHS)    
    end_time = time()
    seconds_elapsed = end_time - start_time
    print('token time: ',seconds_elapsed)
    hours,rest = divmod(seconds_elapsed,3600)
    minutes,seconds = divmod(rest,60)
    
if __name__ == "__main__":
    main()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。