python - 在python中实现softmax方法
问题描述
我试图从 lightaime 的 Github 页面中理解这段代码。它是一种向量化的 softmax 方法。让我困惑的是“softmax_output[range(num_train), list(y)]”
这个表达是什么意思?
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorize implementation
Inputs have dimension D, there are C classes, and we operate on minibatches of N examples.
Inputs:
W: A numpy array of shape (D, C) containing weights.
X: A numpy array of shape (N, D) containing a minibatch of data.
y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C.
reg: (float) regularization strength
Returns a tuple of:
loss as single float
gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_classes = W.shape[1]
num_train = X.shape[0]
scores = X.dot(W)
shift_scores = scores - np.max(scores, axis = 1).reshape(-1,1)
softmax_output = np.exp(shift_scores)/np.sum(np.exp(shift_scores), axis = 1).reshape(-1,1)
loss = -np.sum(np.log(softmax_output[range(num_train), list(y)]))
loss /= num_train
loss += 0.5* reg * np.sum(W * W)
dS = softmax_output.copy()
dS[range(num_train), list(y)] += -1
dW = (X.T).dot(dS)
dW = dW/num_train + reg* W
return loss, dW
解决方案
softmax_output
这个表达式的意思是:对一个形状数组进行切片(N, C)
,只从中提取与训练标签相关的值y
。
二维numpy.array
可以用包含适当值的两个列表进行切片(即它们不应导致索引错误)
range(num_train)
为第一个轴创建一个索引,允许在第二个索引的每一行中选择特定值 - list(y)
。你可以在numpy 的 indexing 文档中找到它。
第一个索引 range_num 的长度等于softmax_output
(= N
) 的第一个维度。它指向矩阵的每一行;然后对于每一行,它通过索引第二部分中的相应值选择目标值 - list(y)
。
例子:
softmax_output = np.array( # dummy values, not softmax
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]]
)
num_train = 4 # length of the array
y = [2, 1, 0, 2] # a labels; values for indexing along the second axis
softmax_output[range(num_train), list(y)]
Out:
[3, 5, 7, 12]
因此,它从第一行中选择第三个元素,从第二行中选择第二个元素,等等。这就是它的工作原理。
(ps我是否误解了您和您对“为什么”而不是“如何”感兴趣?)
推荐阅读
- html - 在我的表格中有一个图片上传部分。如果用户没有上传任何文件,那么它会给出 MultiValueDictKeyError。如何摆脱它?
- dataframe - 如何从 Spark 中的列中提取 JSON 字符串
- javascript - 在 html 的另一个页面上显示下拉列表中的选定值以及其他表单值
- java - 如何通过从文件中读取文本来拆分字符串
- reactjs - Recharts 每周每月按钮
- powershell - Powershell:创建一个自动添加键并计算值的哈希表
- c# - C# 是否可以在 ASP.Net 中运行 nunit 测试?
- kubernetes - 使用 docker-compose 设置 Prometheus 以获取现有 Kubernetes pod 的指标
- javascript - Redux 状态条目哈希
- authorization - 身份验证和精细授权