赞
踩
l o s s ( x , c l a s s ) = − l o g ( e x p ( x [ c l a s s ] ) ∑ j e x p ( x [ j ] ) ) = − x [ c l a s s ] + l o g ( ∑ j e x p ( x [ j ] ) ) loss(x,class)=-log(\frac{exp(x[class])}{\sum_jexp(x[j])})=-x[class]+log(\sum_jexp(x[j])) loss(x,class)=−log(∑jexp(x[j])exp(x[class]))=−x[class]+log(j∑exp(x[j]))
import torch
import torch.nn as nn
import math
entroy=nn.CrossEntropyLoss()
input=torch.Tensor([[-0.7715, -0.6205,-0.2562]])
target = torch.tensor([0])
output = entroy(input, target)
print(output)
#根据公式计算
tensor(1.3447)
−
x
[
0
]
+
l
o
g
(
e
x
p
(
x
[
0
]
)
+
e
x
p
(
x
[
1
]
)
+
e
x
p
(
x
[
2
]
)
)
-x[0]+log(exp(x[0])+exp(x[1])+exp(x[2]))
−x[0]+log(exp(x[0])+exp(x[1])+exp(x[2]))
=
0.7715
+
l
o
g
(
e
x
p
(
−
0.7715
)
+
e
x
p
(
−
0.6205
)
+
e
x
p
(
−
0.2562
)
=
1.3447266007601868
=0.7715+log(exp(-0.7715)+exp(-0.6205)+exp(-0.2562)=1.3447266007601868
=0.7715+log(exp(−0.7715)+exp(−0.6205)+exp(−0.2562)=1.3447266007601868
。
m = nn.LogSoftmax()
loss = nn.NLLLoss()
input=m(input)
output = loss(input, target)
print('output:',output)
input: tensor([[-1.3447, -1.1937, -0.8294]])
output: tensor(1.3447)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。