python - 如何创建加权交叉熵损失?
问题描述
我必须处理高度不平衡的数据。据我了解,我需要使用加权交叉熵损失。
我试过这个:
import tensorflow as tf
weights = np.array([<values>])
def loss(y_true, y_pred):
# weights.shape = (63,)
# y_true.shape = (64, 63)
# y_pred.shape = (64, 63)
return tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(y_true, y_pred, weights))
model.compile('adam', loss=loss, metrics=['acc'])
但是有一个错误:
ValueError: Creating variables on a non-first call to a function decorated with tf.function
我怎样才能创造这种损失?
解决方案
我建议首先使用class_weight
Keras。
class_weight
是一本字典{label:weight}
例如,如果标签 1 中的示例比标签 0 中的示例多 20 倍,那么您可以编写
# Assign 20 times more weight to label 0
model.fit(..., class_weight = {0:20, 1:0})
通过这种方式,您无需担心自己实施加权 CCE。
附加说明:在您的使用中model.compile()
不要忘记使用weighted_metrics=['accuracy']
,以便有相关反映您的准确性。
model.fit(..., class_weight = {0:20, 1:0}, weighted_metrics = ['accuracy'])
推荐阅读
- java - 如何在片段中插入共享首选项
- python - 切换路由时有时会注销 - Heroku Flask_SQLAlchemy
- c++ - 头文件和源文件错误
- docker - 为什么`docker-compose.yml`中指定的ARGS在`Dockerfile`中可用于`docker compose run`而不是`docker compose build`?
- c# - 为什么 webapi 的 post 方法在从邮递员调用时接收类型接口为 null 的参数?
- python - 有没有办法在不同的单元测试中运行单元测试?
- python - Kivy 应用程序在尝试播放视频时显示空白屏幕
- dataframe - 使用 groupby() 方法后如何迭代数据帧
- javascript - 如何正确同步解析打字稿/javascript中的承诺列表
- javascript - IndexError: 元组索引超出范围。奥多 14