如何在 Keras 中使用 fit_generator() 对类进行加权? [英] How to weight classes using fit_generator() in Keras?

查看:32
本文介绍了如何在 Keras 中使用 fit_generator() 对类进行加权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 keras 来拟合 CNN 模型来对图像进行分类.数据集具有更多来自某些类别的图像,因此不平衡.

I am trying to use keras to fit a CNN model to classify images. The data set has much more images form certain classes, so its unbalanced.

我阅读了不同的关于如何在 Keras 中对损失进行权重来解释这一点的不同内容,例如:https://datascience.stackexchange.com/问题/13490/how-to-set-class-weights-for-imbalanced-classes-in-keras,这很好解释.但是,它总是解释 fit() 函数,而不是 fit_generator() 函数.

I read different thing on how to weight the loss to account for this in Keras, e.g.: https://datascience.stackexchange.com/questions/13490/how-to-set-class-weights-for-imbalanced-classes-in-keras, which is nicely explained. But, its always explaining for the fit() function, not the fit_generator() one.

确实,在 fit_generator() 函数中我们没有class_weights"参数,而是有weighted_metrics",我不明白它的描述:"weighted_metrics:在训练和测试期间要通过 sample_weight 或 class_weight 进行评估和加权的指标列表."

Indeed, in the fit_generator() function we dont have the 'class_weights' parameter, but instead we have 'weighted_metrics', which I dont understand its description: "weighted_metrics: List of metrics to be evaluated and weighted by sample_weight or class_weight during training and testing."

如何将class_weights"传递给weighted_metrics"?有人能举个简单的例子吗?

How can I pass from 'class_weights' to 'weighted_metrics'? Would any one have a simple example?

推荐答案

我们在 fit_generator 中有 class_weight (Keras v.2.2.2) 根据文档:

We have class_weight in fit_generator (Keras v.2.2.2) According to docs:

Class_weight:可选字典将类索引(整数)映射到一个权重(浮点数)值,用于对损失函数进行加权(在仅培训).这对于告诉模型支付更多注意"来自代表性不足的类的样本.

Class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class.

假设您有两个类 [positivenegative],您可以将 class_weight 传递给 fit_generator:

Assume you have two classes [positive and negative], you can pass class_weight to fit_generator with:

model.fit_generator(gen,class_weight=[0.7,1.3])

这篇关于如何在 Keras 中使用 fit_generator() 对类进行加权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆