首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python中循环的向量化

python中循环的向量化
EN

Stack Overflow用户
提问于 2018-05-04 21:39:10
回答 1查看 301关注 0票数 2

下面有一个循环,在这个循环中,我正在计算不同大小的批的softmax转换,如下所示

代码语言:javascript
复制
import numpy as np 
def softmax(Z,arr):
    """
    :param Z:  numpy array of any shape (output from hidden layer)
    :param arr: numpy array of any shape (start, end)
    :return A: output of multinum_logit(Z,arr), same shape as Z
    :return cache: returns Z as well, useful during back propagation
    """
    A = np.zeros(Z.shape)
    for i in prange(len(arr)):
        shiftx = Z[:,arr[i,1]:arr[i,2]+1] - np.max(Z[:,int(arr[i,1]):int(arr[i,2])+1])
        A[:,arr[i,1]:arr[i,2]+1] = np.exp(shiftx)/np.exp(shiftx).sum()
    cache = Z
    return A,cache

因为这个for循环不是矢量化的,所以它是我代码中的瓶颈。什么是可能的解决办法使它更快。我尝试过使用@jit of numba,这使它稍微快了一点,但还不够。我想知道是否还有其他方法使其更快,或者将其向量化/并行化。

函数的输入数据示例

代码语言:javascript
复制
Z = np.random.random([1,10000])
arr = np.zeros([100,3])
arr[:,0] = 1
temp = int(Z.shape[1]/arr.shape[0])
for i in range(arr.shape[0]):
    arr[i,1] = i*temp
    arr[i,2] = (i+1)*temp-1
arr = arr.astype(int)

编辑:

我忘了在这里强调,我的班级人数是不同的。例如,批处理1有10个类,批2可能有15个类。因此,我正在传递一个数组arr,它跟踪哪些行属于batch1,等等。这些批次与传统神经网络框架中的批次不同。

在上面的示例中,arr跟踪行的起始索引和结束索引。因此,softmax函数中的分母将仅是指数介于起始指标和结束指标之间的观测值之和。

EN

回答 1

Stack Overflow用户

发布于 2018-05-04 21:53:26

这是一个矢量化的softmax函数。这是斯坦福大学cs231n课程关于conv网的作业的实现。

该函数接受可优化的参数、输入数据、目标和正则化器。(您可以忽略正则化器,因为它引用了另一个类,仅限于某些cs231n赋值)。

它返回参数的损失和梯度。

代码语言:javascript
复制
def softmax_loss_vectorized(W, X, y, reg):
  """
  Softmax loss function, vectorized version.
  Inputs and outputs are the same as softmax_loss_naive.
  """
  # Initialize the loss and gradient to zero.

  loss = 0.0
  dW = np.zeros_like(W)

  num_train = X.shape[0]

  scores = X.dot(W)

  shift_scores = scores - np.amax(scores,axis=1).reshape(-1,1)

  softmax = np.exp(shift_scores)/np.sum(np.exp(shift_scores), axis=1).reshape(-1,1)

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

  loss /= num_train

  loss += 0.5* reg * np.sum(W * W)

  dSoftmax = softmax.copy()

  dSoftmax[range(num_train), list(y)] += -1

  dW = (X.T).dot(dSoftmax)
  dW = dW/num_train + reg * W

  return loss, dW

为了比较起见,这里是相同方法的天真(非向量化)实现。

代码语言:javascript
复制
def softmax_loss_naive(W, X, y, reg):
  """
  Softmax loss function, naive implementation (with loops)
  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
  """

  loss = 0.0
  dW = np.zeros_like(W)

  num_train = X.shape[0]
  num_classes = W.shape[1]

  for i in xrange(num_train):
      scores = X[i].dot(W)

      shift_scores = scores - max(scores)

      loss_i = -shift_scores[y[i]] + np.log(sum(np.exp(shift_scores)))
      loss += loss_i
      for j in xrange(num_classes):
          softmax = np.exp(shift_scores[j])/sum(np.exp(shift_scores))
          if j==y[i]:

              dW[:,j] += (-1 + softmax) * X[i]
          else:
              dW[:,j] += softmax *X[i]

  loss /= num_train

  loss += 0.5 * reg * np.sum(W * W)

  dW /= num_train + reg * W

  return loss, dW

来源

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50183377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档