读书笔记:神经网络 Softmax-with-Loss 层的实现及应用 ← 斋藤康毅

神经网络中进行的处理有推理和学习两个阶段。
神经网络的推理通常不使用 Softmax 层
神经网络中未被正规化的输出结果有时被称为“
得分”。也就是说,当神经网络的推理只需要给出一个答案的情况下,因为此时只对得分最大值感兴趣,所以不需要 Softmax层。
不过,
神经网络的学习阶段则需要 Softmax 层

 【Softmax-with-Loss层的Python代码实现】

import numpy as np

def softmax(x):
    if x.ndim == 2:
        x = x.T
        x = x - np.max(x, axis=0)
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T 
    x = x - np.max(x)
    return np.exp(x) / np.sum(np.exp(x))

def cross_entropy_error(y,t):
    delta=1e-7
    return -np.sum(t*np.log(y+delta))

class SoftmaxWithLoss:
    def __init__(self):
        self.loss = None
        self.y = None # softmax的输出
        self.t = None # 监督数据

    def forward(self, x, t):
        self.t = t
        self.y = softmax(x)
        self.loss = cross_entropy_error(self.y, self.t)        
        return self.loss

    def backward(self, dout=1):
        batch_size = self.t.shape[0]
        if self.t.size == self.y.size: # 监督数据是one-hot-vector的情况
            dx = (self.y - self.t) / batch_size
        else:
            dx = self.y.copy()
            dx[np.arange(batch_size), self.t] -= 1
            dx = dx / batch_size
        
        return dx

x=np.array([0.01,0.99,0]) #Softmax层的输出
t=np.array([0,1,0]) #教师标签

SWL_layer=SoftmaxWithLoss()
qian_out=SWL_layer.forward(x,t)
hou_out=SWL_layer.backward()
print(qian_out)
print("\n")
print(hou_out)

运行后,此代码的输出为:

0.5578356242191105


[ 0.07161519 -0.1425178   0.07090261]
【参考文献】
https://blog.csdn.net/qq_19830591/article/details/125980910
https://blog.csdn.net/swjtu_pl/article/details/124528588

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值