zoukankan      html  css  js  c++  java
  • 『Numpy』常用方法记录

    numpy教程

    防止输出省略号

    import numpy as np  
    np.set_printoptions(threshold=np.inf)
    

    广播机制

    numpy计算函数返回默认是一维行向量:

    import numpy as np
    
    a = [[1,1,1],
        [2,2,2],
        [3,3,3]]
    b = (np.sum(a,axis=1))
    c = (np.sum(a,axis=0))
    print(b,'
    ',c)
    
    # [3 6 9] 
    # [6 6 6]
    

     所以广播之实际是高维对一维行向量的广播:

    除法广播:

    b = a/(np.sum(a,axis=1))
    c = a/(np.sum(a,axis=0))
    print(b,'
    ',c)
    
    # [[ 0.33333333  0.16666667  0.11111111]
    #  [ 0.66666667  0.33333333  0.22222222]
    #  [ 1.          0.5         0.33333333]] 
    # [[ 0.16666667  0.16666667  0.16666667]
    #  [ 0.33333333  0.33333333  0.33333333]
    #  [ 0.5         0.5         0.5       ]]
    

     向量乘法,加法可以类比:

    np.array([1,2,3])*np.array([1,1,1])
    # [1 2 3]
    
    np.array([1,2,3])*np.array([1])
    # [1 2 3]
    
    np.array([1,2,3])*np.array([1,1])
    # 报错
    
    np.array([[1],[1],[1]])*np.array([1,2,3])
    # [[1 2 3]
    #  [1 2 3]
    #  [1 2 3]]
    

    线性代数相关

    np.diag():对角阵生成

    np.linalg.det():求行列式

    np.linalg.inv():矩阵求逆

    np.linalg.eig():对称阵特征值分解

    np.linalg.svd():任意阵SVD分解

    通用函数

    使单输入单输出的函数具备广播功能,frompyfunc(fun, in_num, out_num),常用f = frompyfunc(fun, 1, 1)

    >>> oct_array = np.frompyfunc(oct, 1, 1)
    
    >>> oct_array(np.array((10, 30, 100)))
    array([012, 036, 0144], dtype=object)
    
    >>> np.array((oct(10), oct(30), oct(100))) # for comparison
    array(['012', '036', '0144'],
          dtype='|S4')
    

    np.sum(array1 == array2,dtype=float)

    bool转换为数组默认是整形,需要手动修改为浮点型,比较值得注意的tip,或者说由于python本身不做区分,所以在numpy中必须特别注意数字类型的问题

    取整

    np.rint(result) # 四舍五入
    np.ceil(result) # 向上取整
    np.floor(result) # 向下取整

    np.unique()

    保留数组中不同的值

    >>> a=np.random.randint(0,5,8) 
    >>> a 
    array([2, 3, 3, 0, 1, 4, 2, 4]) 
    
    >>> np.unique(a) 
    array([0, 1, 2, 3, 4]) 
    
    >>> c,s=np.unique(b,return_index=True) 
    >>> c 
    array([0, 1, 2, 3, 4]) 
    >>> s 
    array([3, 4, 0, 1, 5])(元素出现的起始位置)  
    

    np.full((shape), value, type)

    numpy数组初始化函数

    np.split(array, num)

    把数组顺序等分

    np.fun.at(array, index_array, [array2])

    fun需要一个参数时等价np.fun(array[index_array]),多参数用法如下:

    Examples

    Increment items 0 and 1, and increment item 2 twice:

    >>> a = np.array([1, 2, 3, 4])
    >>> np.add.at(a, [0, 1, 2, 2], 1)
    >>> print(a)
    array([2, 3, 5, 4])
    

    Add items 0 and 1 in first array to second array, and store results in first array:

    >>> a = np.array([1, 2, 3, 4])
    >>> b = np.array([1, 2])
    >>> np.add.at(a, [0, 1], b)
    >>> print(a)
    array([2, 4, 3, 4])
    

    特色,

    #np.add.at(dW, x, dout)
    #dW[x] += dout # this will not work, see the doc of np.add.at
    a = np.array([1,2,3,4,5,6,7])
    i = np.array([0,1,2,0,1])
    b = np.array([1,2,3,4,5])
    np.add.at(a, i, b)
    print(a)
    a = np.array([1,2,3,4,5,6,7])
    i = np.array([0,1,2,0,1])
    b = np.array([1,2,3,4,5])
    a[i] += b
    print(a)
    

     输出如下,即索引重复的时候,只有np.add.at会累积前面的结果,单纯的索引会取最后一次的结果覆盖,

    [6 9 6 4 5 6 7]

    [5 7 6 4 5 6 7]

    np.save() & np.load()

    np.save('./bottleneck/{1}/{0}'.format(img.split('/')[-1].split('.')[0], file_name),bottleneck_values)

    bottleneck_string = np.load(os.path.join(base_path,
    'bottleneck',
    train_or_test,
    label_name,
    bottlenecks_tensor_name))

    np.loadtxt()

    # 本函数读取数据后自动转化为ndarray数组,可以自行设定分隔符delimiter=","
    np.loadtxt('housing.data')     # 读取数据
    

    np.insert()

    np.insert(scale_data, 0, 1, axis=1)      # 数组插入函数
    

      在数组中插入指定的行列,numpy.insert(arr, obj, values, axis=None),和其他数组一样,axis不设定的话会把数组定为一维后插入,axis=0的话行扩展,axis=1的话列扩展

    np.matrix()

    『科学计算_理论』优化算法:梯度下降法&牛顿法

    学习了numpy中的矩阵类型:np.matrix(),在牛顿法中我用的是matrix,在梯度下降法中我用的是array:

    matrix是array的子类,特点是有且必须只是2维,matrix.I()可以求逆,和线代的求逆方法一致,所以绘图时我不得不才用np.sequeeze(np.asarray())操作来降维,而由于x[:, -1]这种操作对array会自动降维(由两行变为一行),所以要么使用matrix,要么切片后reshape(2,1),总之不消停。

    np.concatenate()

    『科学计算_理论』优化算法:梯度下降法&牛顿法

    注意到数组拼接方法都是不破坏原数组,单纯返回新数组的,且axis=0是行拼接(行数增加),axis=1是列拼接(列数增加),

    x_n = np.concatenate((x_n, x_n[:,-1] - np.linalg.inv(H).dot(dx_n)),axis=1)

    np.nxis

    np.exped_dim

    用于扩展维度,numpy不仅有expend_dim这样的函数,也可以使用np.newaxis标记来实现扩维:

    a = np.array([1,2,3,4,5])
    a = a[:,np.newaxis]
    a
    Out[44]: 
    array([[1],
           [2],
           [3],
           [4],
           [5]])
    a = np.array([1,2,3,4,5])
    a = a[np.newaxis,:]
    a
    Out[47]: 
    array([[1, 2, 3, 4, 5]])
    

    array.transpose(1,0,2)

    转置,1维没效果(并不能行列互化),高维后面参数维转置顺序,假如(T,N,H)经过上面的命令会变为(N,T,H)

    np.bincount()

    计数&投票函数

    numpy.bincount详解

    np.maximum(X, Y, out=None):

      • X 与 Y 逐位比较取其大者;
      • 最少接收两个参数

    np.squeeze():剔除长度为一的轴

    np.squeeze(np.array([[1,2,3]]))
    # Out[17]: 
    # array([1, 2, 3])
    np.squeeze(np.array([[1],[2],[3]]))
    # Out[18]: 
    # array([1, 2, 3])
    

    numpy.roll():平移数组行列

    >>> x = np.arange(10) 
    >>> np.roll(x, 2)
    array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
    >>> x2 = np.reshape(x, (2,5)) >>> x2 array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> np.roll(x2, 1) array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]) >>> np.roll(x2, 1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1) array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])


    计算机视觉中人为建立图像抖动会使用这个函数:

    『cs231n』作业3问题4选讲_图像梯度应用强化

    ox, oy = np.random.randint(-max_jitter, max_jitter+1, 2)                    # 随机抖动生成
    X = np.roll(np.roll(X, ox, -1), oy, -2)                                     # 抖动,注意抖动不是随机噪声
    
    pass
    
    X = np.roll(np.roll(X, -ox, -1), -oy, -2)                                  # 还原抖动
    
  • 相关阅读:
    jq的stop
    mouseover,mouseout与mouseenter,mouseleave
    jq的load
    KeyUp 和KeyDown 、KeyPress之间的区别
    jq的error
    $(function() {....}) ,(function($){...})(jQuery)
    delegate事件委托
    将项目提交到git
    linux下安装jenkins
    手写简单的linkedlist
  • 原文地址:https://www.cnblogs.com/hellcat/p/7422005.html
Copyright © 2011-2022 走看看