Numpy“-=”运算符结果

ryhaxcpt  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(94)
def svm_loss(x, y):
"""
Computes the loss and gradient using for multiclass SVM classification.

Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth
  class for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
  0 <= y[i] < C

Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
loss, dx = None, None

###########################################################################
# TODO: Copy over your solution from A1.
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# 구현 (2023-09-01)
N = len(y)
x = x - x[np.arange(N),y][:,np.newaxis] + 1 # this part
x = np.maximum(0, x)
loss = (np.sum(x) - N) / N

我发现x = x - x[np.arange(N),y][:,np.newaxis] + 1x -= (x[np.arange(N),y][:,np.newaxis] - 1)给予不同的结果。
为什么会发生这种情况?

fumotvh3

fumotvh31#

对于一个简单的演示案例,我得到了同样的东西:

In [569]: x=np.arange(25).reshape(5,5); y=np.arange(5); N=5

In [570]: x
Out[570]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

In [571]: x - x[np.arange(N),y][:,np.newaxis] + 1
Out[571]: 
array([[ 1,  2,  3,  4,  5],
       [ 0,  1,  2,  3,  4],
       [-1,  0,  1,  2,  3],
       [-2, -1,  0,  1,  2],
       [-3, -2, -1,  0,  1]])

In [572]: x -= (x[np.arange(N),y][:,np.newaxis] - 1); x
Out[572]: 
array([[ 1,  2,  3,  4,  5],
       [ 0,  1,  2,  3,  4],
       [-1,  0,  1,  2,  3],
       [-2, -1,  0,  1,  2],
       [-3, -2, -1,  0,  1]])

这并没有什么区别,但您可以使用一个索引添加新维度:

In [573]: x=np.arange(25).reshape(5,5); y=np.arange(5); N=5

In [574]: x[np.arange(N),y][:,np.newaxis]
Out[574]: 
array([[ 0],
       [ 6],
       [12],
       [18],
       [24]])

In [575]: x[np.arange(N),y,None]
Out[575]: 
array([[ 0],
       [ 6],
       [12],
       [18],
       [24]])

相关问题