python - 在 keras 中计算微 F-1 分数
问题描述
我有一个包含 15 个不平衡类的数据集,并尝试使用 keras 进行多标签分类。
我正在尝试使用微 F-1 分数作为衡量标准。
我的模型:
# Create a VGG instance
model_vgg = tf.keras.applications.VGG19(weights = 'imagenet', pooling = 'max', include_top = False,
input_shape = (512, 512, 3))
# Freeze the layers which you don't want to train.
for layer in model_vgg.layers[:-5]:
layer.trainable = False
# Adding custom Layers
x = model_vgg.output
x = Flatten()(x)
x = Dense(1024, activation = "relu")(x)
x = Dropout(0.5)(x)
x = Dense(1024, activation = "relu")(x)
predictions = Dense(15, activation = "sigmoid")(x)
# creating the final model
model_vgg_final = Model(model_vgg.input, predictions)
# Print the summary
model_vgg_final.summary()
对于 F1 分数,我使用此问题中的自定义指标
from keras import backend as K
def f1(y_true, y_pred):
def recall(y_true, y_pred):
"""Recall metric.
Only computes a batch-wise average of recall.
Computes the recall, a metric for multi-label classification of
how many relevant items are selected.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
precision = precision(y_true, y_pred)
recall = recall(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
我在编译模型时使用二元交叉熵和自定义 F-1
# Compile a model
model_vgg_final.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = [f1])
我监视 F-1 是否提前停止
# Early stopping
early_stopping = EarlyStopping(monitor = 'f1', patience = 5)
# Training the model
history_vgg = model_vgg_final.fit(train_generator, steps_per_epoch = 10, epochs = 30, verbose = 1,
callbacks = [early_stopping], validation_data = valid_generator)
如何更新此自定义函数并将 micro F-1 作为指标?也感谢有关我的方法的提示。
scikit-learn 文档中有信息,但不确定如何将其合并到 keras
解决方案
好问题。
您在此处提供的链接指向如何在旧版本的 Keras 中计算指标(请耐心等待,简短说明)。问题是,在较旧的 Keras (1.X) 中,指标是分批计算的,这当然会导致不正确的全局结果。在 Keras 2.X 中,删除了内置指标。
但是,有解决您的问题的方法。
- 您可以实现自己的自定义回调。你可以在这里查看我的答案,它保证可以在 TensorFlow 中工作
2.x
:如何在 Tensorflow 2.0 中获取其他指标(不仅是准确度)? - 您可以使用
tensorflow-addons
-->pip install tensorflow-addons
。TensorFlow 插件是一个非常好的包,它包含了基础 TensorFlow 包中不具备的多种功能和特性。这里,F1Score
是一个内置的指标,所以你可以直接使用它。
例子:
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.00001),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tfa.metrics.F1Score(num_classes=number_of_classes, average='micro',threshold=0.5),
请注意 ' micro
' 参数的用法,它实际上代表了您想要的,即 micro f1-score
。
推荐阅读
- docker - 为什么有些 Docker 镜像没有定义 VOLUME?
- c++ - 使用指向类的指针时 RAM 使用错误
- python - 我正在使用 ubuntu、django 3.0.5、sqlte3 ...帮助!!!谢谢!在命令行中运行“python manage.py shell”,它会给出错误:
- c - 如何计算在c中的字符串中找到的单词数
- c - 我可以在 do-while 语句的主体中声明 C 中的变量吗?
- django - 配置文件表更新时如何更新用户表?
- libgdx - 相机 Libgdx 的旋转
- c++ - 如何在 MPI 中将矩阵从一个进程转移到另一个进程?
- database-design - 在本地存储分析以供 Google 处理或存储?
- mysql - MySQL获取字符串中的X字节