第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

像在 Keras 中一樣在 pytorch 中獲取交叉熵?fù)p失

像在 Keras 中一樣在 pytorch 中獲取交叉熵?fù)p失

Cats萌萌 2022-12-27 10:16:06
我正在努力將分類(lèi)模型從 keras 移植到 pytorch。特別是交叉熵?fù)p失似乎返回完全不同的數(shù)字。import numpy as npimport torch as timport torch.nn as nnimport tensorflow.keras.backend as Ky_true = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]])y_pred = np.array([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 1, 0.41, 0.31, 0.21, 0.11]])print("Keras", K.categorical_crossentropy(K.constant(y_true), K.constant(y_pred)))print("PyTorch", nn.CrossEntropyLoss()(t.tensor(y_pred).argsort(dim=-1).float(), t.tensor(y_true).argmax(dim=-1)))```印刷:Keras tf.Tensor([2.3369865], shape=(1,), dtype=float32)PyTorch 張量 (1.4587)由于我有一個(gè)自定義損失函數(shù),其中交叉熵是其中的一部分,因此我需要獲得相似(如果不是相同)的數(shù)字。
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊

問(wèn)題是它們有不同的實(shí)現(xiàn)。


正如 pytorch文檔所說(shuō),nn.CrossEntropyLoss將nn.LogSoftmax()和組合nn.NLLLoss()在一個(gè)類(lèi)中。但是,tensorflow文檔指定keras.backend.categorical_crossentropy默認(rèn)情況下不應(yīng)用 Softmax,除非您設(shè)置from_logits為 True。出于這個(gè)原因,keras.backend.categorical_crossentropy除非您使用from_logits=True.


如果你不想事先應(yīng)用 softmax,你應(yīng)該使用:


import numpy as np

import torch as t

import torch.nn as nn

import tensorflow.keras.backend as K


y_true = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]])

y_pred = np.array([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 1, 0.41, 0.31, 0.21, 0.11]])



print("Keras", K.categorical_crossentropy(K.constant(y_true), K.constant(y_pred), from_logits=True))

# output: Keras tf.Tensor([2.408051], shape=(1,), dtype=float32)

print("PyTorch", nn.CrossEntropyLoss()(t.tensor(y_pred).float(), t.tensor(y_true).argmax(dim=-1)))

# output: PyTorch tensor(2.4081)

否則,您可以在計(jì)算 categorical_crossentropy 之前手動(dòng)應(yīng)用 Softmax


import numpy as np

import torch as t

import torch.nn as nn

import tensorflow.keras.backend as K


y_true = np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]])

y_pred = np.array([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 1, 0.41, 0.31, 0.21, 0.11]])



print("Keras", K.categorical_crossentropy(K.constant(y_true), K.softmax(K.constant(y_pred))))

# output: Keras tf.Tensor([2.408051], shape=(1,), dtype=float32)

print("PyTorch", nn.CrossEntropyLoss()(t.tensor(y_pred).float(), t.tensor(y_true).argmax(dim=-1)))

# output: PyTorch tensor(2.4081)

因此,您不應(yīng)像在示例中那樣使用keras.backend.categorical_crossentropywith 。from_logits=False


tf.keras.backend.categorical_crossentropy


target:與輸出形狀相同的張量。


output:由 softmax 產(chǎn)生的張量(除非 from_logits 為 True,在這種情況下輸出預(yù)計(jì)為 logits)。


from_logits:布爾值,輸出是 softmax 的結(jié)果,還是 logits 的張量。


查看完整回答
反對(duì) 回復(fù) 2022-12-27
  • 1 回答
  • 0 關(guān)注
  • 146 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)