为了账号安全,请及时绑定邮箱和手机立即绑定

在python中实现softmax方法

在python中实现softmax方法

元芳怎么了 2021-10-19 14:59:05
我试图从 lightaime 的 Github 页面理解这段代码。它是一种 vetorized 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
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

这个表达式的意思是:对一个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 我误解了你,你对“为什么”感兴趣,而不是“如何”?)


查看完整回答
反对 回复 2021-10-19
?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

这里的损失由以下等式定义

//img1.sycdn.imooc.com//616e6cf80001e80303160057.jpg

这里,对于数据点所属的类,y 为 1,对于所有其他类,y 为 0。因此,我们只对数据点类的 softmax 输出感兴趣。因此上面的方程可以改写为

//img1.sycdn.imooc.com//616e6d010001fbab03710054.jpg

因此,下面的代码表示上述等式。

loss = -np.sum(np.log(softmax_output[range(num_train), list(y)]))

该代码softmax_output[range(num_train), list(y)]用于为各个类选择 softmax 输出。range(num_train)代表所有训练样本并list(y)代表各自的类别。

Mikhail 在他的回答中很好地解释了这种索引。


查看完整回答
反对 回复 2021-10-19
  • 2 回答
  • 0 关注
  • 235 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号