【问题标题】:Numpy array indexing with complete vector具有完整向量的 Numpy 数组索引
【发布时间】:2021-11-26 13:07:53
【问题描述】:

以下代码有什么作用? (grad[range(m),y] -= 1)

def delta_cross_entropy(X,y):
    """
    X is the output from fully connected layer (num_examples x num_classes)
    y is labels (num_examples x 1)
        Note that y is not one-hot encoded vector. 
        It can be computed as y.argmax(axis=1) from one-hot encoded vectors of labels if required.
    """
    m = y.shape[0]
    grad = softmax(X)
# What does this do? Does it subtract y from grad? (As that is what is supposed to happen)
    grad[range(m),y] -= 1
    grad = grad/m
    return grad

编辑:这不是关于切片如何从原地更新它们的数组,因为y 不是grad 的切片,这个问题是关于 NumPy 的语法。

【问题讨论】:

  • 这能回答你的问题吗? - vs -= operators with numpy
  • 随意编辑标题,或告诉我正确的搜索词是什么,因为我不确定我的标题是否完全符合要求
  • @alex 有点像,但我还是不明白它的作用...... sry
  • 它从grad 的元素子集中减去 1。索引决定了哪个。

标签: python arrays numpy softmax cross-entropy


【解决方案1】:
grad[range(m),y] -= 1 # It is the same as subtracting X[i,j] when j==y[i].

【讨论】:

  • 我刚刚意识到,X 是一个矩阵,在我的例子中,x 始终只是一个向量。如果有错误请纠正我,但这是否意味着在grad 中,每列都会减去y
  • 是的,正如你所说。
猜你喜欢
  • 2018-12-02
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多