tensorflow 分類損失函數(shù)使用小記
多分類損失函數(shù)
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 真實(shí)值, y_pred 預(yù)測值
- from_logits,我的理解是,如果預(yù)測結(jié)果經(jīng)過了softmax(單次預(yù)測結(jié)果滿足和為1)就使用設(shè)為`False`,
如果預(yù)測結(jié)果未經(jīng)過softmax就設(shè)為`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 參數(shù), 用于對一個批次的損失函數(shù)求平均值,求和等 # 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 真實(shí)值, y_pred 預(yù)測值
- 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())
二分類損失損失函數(shù)
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激活函數(shù)搭配使用; binary_crossentropy 與 sigmoid搭配使用;
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python根據(jù)Excel表進(jìn)行文件重命名的實(shí)現(xiàn)示例
在日常辦公過程中,批量重命名是經(jīng)常使用的操作,本文主要介紹了Python根據(jù)Excel表進(jìn)行文件重命名,具有一定的參考價值,感興趣的可以了解一下2024-01-01
修改 CentOS 6.x 上默認(rèn)Python的方法
這篇文章主要介紹了修改 CentOS 6.x 上默認(rèn)Python的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
wx.CheckBox創(chuàng)建復(fù)選框控件并響應(yīng)鼠標(biāo)點(diǎn)擊事件
這篇文章主要為大家詳細(xì)介紹了wx.CheckBox創(chuàng)建復(fù)選框控件并響應(yīng)鼠標(biāo)點(diǎn)擊事件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04
Python將json文件寫入ES數(shù)據(jù)庫的方法
這篇文章主要介紹了Python將json文件寫入ES數(shù)據(jù)庫的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-04-04
Python Collections強(qiáng)大的數(shù)據(jù)結(jié)構(gòu)工具使用實(shí)例探索
這篇文章主要介紹了Python Collections強(qiáng)大的數(shù)據(jù)結(jié)構(gòu)工具的使用實(shí)例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
python連接MySQL數(shù)據(jù)庫實(shí)例分析
這篇文章主要介紹了python連接MySQL數(shù)據(jù)庫,實(shí)例分析了Python操作MySQL的相關(guān)技巧,需要的朋友可以參考下2015-05-05

