numpy库函数补充

1, np.argsort : Returns the indices that would sort an array. 在 KNN 中取前 K 个最小值时就可以使用这个函数

>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])

2, np.bincount:Count number of occurrences of each value in array of non-negative ints. 可以用于ensemble model中记下每个类别被预测的次数:

>>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])

3, nditer : 多维数组的高效遍历,如 cs231n 中求导函数的写法:

def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
  """ 
  a naive implementation of numerical gradient of f at x 
  - f should be a function that takes a single argument
  - x is the point (numpy array) to evaluate the gradient at
  """ 

  fx = f(x) # evaluate function value at original point
  grad = np.zeros_like(x)
  # iterate over all indexes in x
  it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
  while not it.finished:

    # evaluate function at x+h
    ix = it.multi_index
    oldval = x[ix]
    x[ix] = oldval + h # increment by h
    fxph = f(x) # evalute f(x + h)
    x[ix] = oldval - h
    fxmh = f(x) # evaluate f(x - h)
    x[ix] = oldval # restore

    # compute the partial derivative with centered formula
    grad[ix] = (fxph - fxmh) / (2 * h) # the slope
    if verbose:
      print(ix, grad[ix])
    it.iternext() # step to next dimension

  return grad

3,np.random.choice 用于抽样

>>> np.random.choice(5, 3)
array([0, 3, 4])
>>> #This is equivalent to np.random.randint(0,5,3)

猜你喜欢

转载自blog.csdn.net/baidu_33939056/article/details/78619347