NLP(5)-softmax和交叉熵

发布于:2024-04-27 ⋅ 阅读:(32) ⋅ 点赞:(0)

前言

仅记录学习过程,有问题欢迎讨论

感觉全连接层就像一个中间层转换数据的形态的,或者说预处理数据?

代码

softmax就是把输出的y 归一化,把结果转化为概率值!,在分类问题中很常见。
而交叉熵是一种损失函数,也是在分类问题中使用,通常搭配着softmax使用;可以计算分布概率之间的差异;期望是两个概率分布的更相似。

# softMAX --概率归一化
# 主要把输出的y 的可能性 sum = 1
# 比如 判断是否为 猫狗 y = 【猫,狗,都不是】

# 【123====[ e^1/(e^1+e^2+e^3) ,e^2/(e^1+e^2+e^3) ,e^3/(e^1+e^2+e^3) ]

# 损失函数:
# 均方差 (y-y_pre)**2/n
# 交叉熵:y_true=[1,0,0] y_pred=[0.5,0.4,0.1] =loss==>| 1*log0.5+0*log0.4+0 | = 0.3

import torch
import torch.nn as nn
import numpy as np

##使用torch计算交叉熵
ce_loss = nn.CrossEntropyLoss()
# 假设有3个样本,每个都在做3分类
pred = torch.FloatTensor([[0.3, 0.1, 0.3],
                          [0.9, 0.2, 0.9],
                          [0.5, 0.4, 0.2]])  # n*class_num
# 正确的类别 == [0,1,0][0,0,1][1,0,0]
target = torch.LongTensor([1, 2, 0])
print(target)
loss = ce_loss(pred, target)
print(loss, "torch输出交叉熵")


# 实现softMax函数 x为矩阵格式!!
def softmax(x):
    return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims=True)


# 验证softmax函数
# print(torch.softmax(pred, dim=1))
# print(softmax(pred.numpy()))

# 将输入转化为onehot矩阵 == [0,1,0][0,0,1][1,0,0]
def to_one_hot(target, shape):
    one_hot_target = np.zeros(shape)
    # enumerate 也是一种循环 格式为【index,value】
    for i, t in enumerate(target):
        one_hot_target[i][t] = 1
    return one_hot_target


# target_matrix =  to_one_hot(target,pred.shape)
# print(target_matrix)

# 实现交叉熵
def cross_entropy(pred, target):
    batch_size, class_num = pred.shape
    # 先归一化
    pred = softmax(pred)
    # 变为矩阵格式
    target = to_one_hot(target,pred.shape)
    # 每一列求
    entropy = -np.sum(target * np.log(pred), axis=1)
    return sum(entropy) / batch_size

print(cross_entropy(pred.numpy(), target.numpy()), "手动实现交叉熵")




网站公告

今日签到

点亮在社区的每一天
去签到