pytorch和tensorlfow的交叉熵对比

pytorch交叉熵

import torch

# CrossEntropyLoss由LogSoftmax和Nllloss组成。

# 输入和输出
input_x = torch.tensor([[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
target_y = torch.tensor([1, 2])
logsoftmax = torch.nn.LogSoftmax(dim = 1)
logsoftmax_output = logsoftmax(input_x)
nllloss = torch.nn.NLLLoss()
nllloss_output = nllloss(logsoftmax_output, target_y)
#
crossentropy = torch.nn.CrossEntropyLoss()
crossentropy_output = crossentropy(input_x, target_y)
print("logsoftmax_nllloss: ", nllloss_output)

keras交叉熵:

import tensorflow as tf
import numpy as np


y_true_np = np.array([1, 2])

flag = 1
if flag == 1:
    y_true = tf.constant([1, 2])
    y_pred = tf.constant([[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
    # sparse_categorical_crossentropy等价于pytorch中的torch.nn.Nllloss()(torch.log(input_x), target)
    loss_total = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
    loss = tf.reduce_mean(loss_total)
    
    y_true_np = np.array([1, 2])
    y_pred_np = np.array([[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
    np_crossentropy = -(np.log(y_pred_np[0][y_true_np[0]]) + np.log(np.log(y_pred_np[1][y_true_np[1]])))
    
    print(loss.numpy())
    print(np_crossentropy)

总结:

在keras中使用了sparse_categorical_crossentropy,则输出需要使用softmax(x);

在pytorch中达到相同的数值,使用CrossEntropyLoss时,网络输出不需要softmax(x)/log_softmax();或者使用Nllloss(),网络输出则为torch.nn.log_softmax()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值