交叉熵误差损失函数

源码

"""
"""
# -*- coding: utf-8 -*-
# @Time    : 2023/3/6 11:15
# @Author  : 王摇摆
# @FileName: cross_entropy_error.py
# @Software: PyCharm
# @Blog    :https://blog.csdn.net/weixin_44943389?type=blog
"""
import numpy as np


# 在本实例中实现交叉熵误差函数
def cross_entropy_error(y, t):
    delta = 1e-7  # 保护性对策,防止数据溢出
    y = -np.sum(t * np.log((y + delta)))

    return y


# 测试数据
y1 = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]  # 表示神经网络的输出,结果值就是概率
y2 = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0]  # 表示神经网络的输出,结果值就是概率
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]  # 表示监督数据,将正确的解的标签打在这个数组上

new_y1 = np.array(y1)
new_y2 = np.array(y2)
new_t = np.array(t)

result1 = cross_entropy_error(new_y1, new_t)
result2 = cross_entropy_error(new_y2, new_t)

print(result1)
print(result2)

出现问题

D:\ANACONDA\envs\pytorch\python.exe C:/Users/Administrator/Desktop/Code/learn_pytorch/ch04/cross_entropy_error.py
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/Code/learn_pytorch/ch04/cross_entropy_error.py", line 24, in <module>
    y = cross_entropy_error(y=y, t=t)
  File "C:/Users/Administrator/Desktop/Code/learn_pytorch/ch04/cross_entropy_error.py", line 15, in cross_entropy_error
    y = -np.sum(t * np.log((y + delta)))
TypeError: can only concatenate list (not "float") to list

实参在传值的时候数据类型不匹配

  • 应该转化为np.array类型后再传值

结果展示

在这里插入图片描述

结果分析

损失函数的值越小,说明和监督数据的误差也越小

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王摇摆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值