神经网络中进行的处理有推理和学习两个阶段。
神经网络的推理通常不使用 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