源码
"""
"""
# -*- 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类型
后再传值
结果展示
结果分析
损失函数的值越小,说明和监督数据的误差也越小