摘要
本文使用纯 Python 和 PyTorch 对比实现softmax函数及其反向传播.
相关
原理和详细解释, 请参考文章 :
softmax函数详解及反向传播中的梯度求导
系列文章索引 :
https://blog.csdn.net/oBrightLamp/article/details/85067981
正文
import numpy as np
import torch
class Solfmax:
def __init__(self):
self.softmax = None
self.grad = None
self.dnx = None
def __call__(self, nx):
shifted_x = nx - np.max(nx)
ex = np.exp(shifted_x)
sum_ex = np.sum(ex)
self.solfmax