您的位置:首页 > 其它

tensorflow 分类损失函数使用小记

2020-03-11 16:08 471 查看

多分类损失函数

label.shape:[batch_size]; pred.shape: [batch_size, num_classes]

使用 tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1)

- y_true 真实值, y_pred 预测值
- from_logits,我的理解是,如果预测结果经过了softmax(单次预测结果满足和为1)就使用设为`False`,  
如果预测结果未经过softmax就设为`True`.

pred = tf.convert_to_tensor([[0.9, 0.05, 0.05], [0.5, 0.89, 0.6], [2.05, 0.01, 0.94]])
label = tf.convert_to_tensor([0, 1, 2])
loss = tf.keras.losses.sparse_categorical_crossentropy(label, pred)
print(loss.numpy())
# 包含 reduction 参数, 用于对一个批次的损失函数求平均值,求和等
# loss = tf.keras.losses.SparseCategoricalCrossentropy()(label, pred)
label.shape:[batch_size, num_classes](one_hot);pred.shape:[batch_size, num_classes]

使用 tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1)

- y_true 真实值, y_pred 预测值
- from_logits 同上

pred = tf.convert_to_tensor([[0.9, 0.05, 0.05], [0.5, 0.89, 0.6], [0.05, 0.01, 0.94]])
label = tf.convert_to_tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = tf.keras.losses.categorical_crossentropy(label, pred)
print(loss.numpy())

二分类损失损失函数

label = tf.convert_to_tensor([0, 0, 1, 1], dtype=tf.float32)
pred = tf.convert_to_tensor([1, 1, 1, 0], dtype=tf.float32)
loss = tf.keras.losses.BinaryCrossentropy()(label, pred)
print(loss.numpy())

多分类与二分类

通常 categorical_crossentropy与 softmax激活函数搭配使用; binary_crossentropy 与 sigmoid搭配使用;

参考

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息