如何在numpy中使用切片来模拟for循环

7z5jn7bk  于 2023-03-30  发布在  其他
关注(0)|答案(2)|浏览(148)

我尝试在python numpy中执行以下代码:

def log_loss(X, y, w, b=0): '''
    Input:
        X: data matrix of shape nxd
        y: n-dimensional vector of labels (+1 or -1)
        w: d-dimensional vector
        b: scalar (optional, default is 0)
    Output:
        scalar
   '''
   assert np.sum(np.abs(y)) == len(y) # check if all labels in y are either +1 or -1 wt = w.T
   n,d = X.shape
   y_pred = np.zeros(n)

   # I want to somehow not use this for loop here

   for i in range(n): 
      y_pred[i] = np.log( sigmoid( y[i]*( wt@X[i]+b )))
   return np.negative(np.sum(y_pred))

#########################################

def sigmoid(z): '''
    Calculates the sigmoid of z.
    Input:
        z: scalar or array of dimension n
    Output:
        scalar or array of dimension n
   '''
   sig = 1/(1+np.exp(-z)) 
   return sig

我的问题是我如何才能更有效地做到这一点,而不使用紧循环?或使用更有效的解决方案?我认为我的解决方案忽略了使用numpy的要点。请提供建议。

yqyhoc1h

yqyhoc1h1#

def log_loss(X, y, w, b=0):
    '''
    Input:
        X: data matrix of shape nxd
        y: n-dimensional vector of labels (+1 or -1)
        w: d-dimensional vector
        b: scalar (optional, default is 0)
    Output:
        scalar
    '''
    assert np.sum(np.abs(y)) == len(y)
    wt = w.T
    n,d = X.shape
    linear_pred = X.dot(wt) + b
    prob_pred = sigmoid(linear_pred)
    log_loss = np.mean(-y*np.log(prob_pred) - (1-y)*np.log(1-prob_pred))
    return log_loss
woobm2wo

woobm2wo2#

按照你的形状组织x & w,我假设:

  • x(n X d)
  • w(d X 1)
  • np.dot(x,w) -〉(n X 1)
y_pred = np.log( sigmoid( y*( np.dot(x,w)+b )))
return np.negative(np.sum(y_pred))

相关问题