• python在数据处理中常用的模块之numpy


    一 numpy模块

    NumPy系统是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix))。

    import numpy as np

    (1).np.linalg.norm(x)    

      顾名思义:linalg = linear + algebra,norm则表示范数,首先需要注意的是范数是对向量(或者矩阵)的度量,是一个标量(scalar)

      首先help(np.linalg.norm查看文档

    norm(x, ord=None, axis=None, keepdims=False)

     x表示要度量的向量,ord表示范数的种类

    参数 说明 计算方法
    默认 二范数 np.sqrt(x1**2+x2**2+....+xn**2)
    ord=2 二范数 同上
    ord=1 一范数 |x1|+|x2|+...+|xn|
    ord=np.inf 无穷范数 max(|xi|)

      用于计算向量x的2范数

    x = np.array([3,4])
    y = np.linalg.norm(x)
    print(y)
    

       输出结果为5.0

       计算矩阵x的2范数  对矩阵每一个元素求平方和然后开根号

    x = np.array([3,4,5],[3,4,5])
    y = np.linalg.norm(x)
    print(x)

       输出结果为10.0

    (2).np.log10(x)              #计算以10为底的对数

        np.log(x)                       #log下什么都不写默认是自然对数 e为底

    x1 = 10
    y1 = np.log10(x1)
    x2 = np.e
    y2 = np.log(x2)
    print(y1,y2)
    

       输出结果为1.0 1.0

     (3).np.nan_to_num:Replace nan with zero and inf with finite numbers.
          把np.nan(非常小的数字,接近0)用0取代
           np.inf,或者-np.inf(正负无穷大的数字)用有限数替代

    np.set_printoptions(precision=8)
    x = np.array([np.inf, -np.inf, np.nan, -128, 128])
    print(np.nan_to_num(x))
    

         输出结果为[  1.79769313e+308  -1.79769313e+308   0.00000000e+000  -1.28000000e+002
         1.28000000e+002]

    (4).numpy.random.randn(d0, d1, …, dn)是从标准正态分布中返回一个或多个样本值。
          numpy.random.rand(d0, d1, …, dn)的随机样本位于[0, 1)中。

    x1 = np.random.randn(2,4)
    print(x1)
    x2 = np.random.rand(2,4)
    print(x2)

        输出结果 

      [[-1.47942602  0.10728309 -1.49062996  1.32908036]
       [ 0.37065869 -0.04594328  0.72822393  0.74898655]]
      [[ 0.54672608  0.0216933   0.04434537  0.65831692]
       [ 0.06332446  0.75230353  0.12993006  0.75911764]]

    (5). numpy.random.normal(loc=0.0, scale=1.0, size=None)   正太分布

          参数的意义为:

      loc:float 概率分布的均值,对应着整个分布的中心center

      scale:float 概率分布的标准差,对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高

      size:int or tuple of ints  维数

    (6).numpy.random.random(size)

    random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0

    (7).numpy.random.uniform(a,b)
           用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= a

    print random.uniform(10, 20)
    print random.uniform(20, 10)
    # 18.7356606526
    # 12.5798298022  

    (8).random.randint(a, b)

    用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

    print random.randint(12, 20)  # 生成的随机数 n: 12 <= n <= 20
    print random.randint(20, 20)  # 结果永远是20     
    # print random.randint(20, 10)  # 该语句是错误的。下限必须小于上限

    (9).random.randrange([start], stop[, step])

    从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效.

    (10).andom.choice(sequence)

    从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。下面是使用choice的一些例子:

    print random.choice("学习Python")
    print random.choice(["JGood", "is", "a", "handsome", "boy"])
    print random.choice(("Tuple", "List", "Dict"))  

    (11).random.shuffle(x[, random])

    用于将一个列表中的元素打乱。如:

    p = ["Python", "is", "powerful", "simple", "and so on..."]
    random.shuffle(p)
    print p
    # ['powerful', 'simple', 'is', 'Python', 'and so on...']  

    (12)对ndarray类型使用len函数

    len用于获取一个数组的长度,如果是多维数组,则获取数组的行数。

        temp = np.zeros(shape=[10,20])
        print(len(temp))  #10

    (13)np.squeeze(a, axis=None):

    从数组的形状中删除单维度条目,即把shape中为1的维度去掉。

        x = np.array([[[0], [1], [2]]])
        print(x.shape)  #(1, 3, 1)
        print(np.squeeze(x).shape)     #(3,)
        print(np.squeeze(x, axis=(2,)).shape) #    (1, 3)

    (14).  np.expand_dims(a, axis):

    该函数和np.squeeze()正好相反,数组形状扩充一个维度的。

        x = np.array([1,2])
        print(x.shape)   #(2,)
        y = np.expand_dims(x, axis=0)
        print(y.shape) #(1, 2)

     (15)列向量和行向量,以及秩为1的数组的区别

    # -*- coding: utf-8 -*-
    """
    Created on Sun Mar 25 20:17:21 2018
        x = np.array([[[0], [1], [2]]])
        print(x.shape)  #(1, 3, 1)
        print(np.squeeze(x).shape)     #(3,)
        print(np.squeeze(x, axis=(2,)).shape) #    (1, 3)
    
    
    
    
    @author: Administrator
    """
    
    import numpy as np
    
    '''
    下面显示了秩为1的数组以及列向量和行向量的使用,以及区别.我们在使用的时候最好不要使用秩为1的数组
    并且当我们不确定矩阵或者向量的维数维数时,我们可以使用.reshape(m,n)指定
    '''
    
    #a为秩为1的数组,我们可以看到转置和本身一致,shape都是(5,)
    a = np.random.randn(5)
    print(a,a.shape)       #[ 0.58371745  0.62467384  0.72225761 -0.32777546 -1.06321595] (5,)
    print(a.T,a.T.shape)   #[ 0.58371745  0.62467384  0.72225761 -0.32777546 -1.06321595] (5,)
    
    r = np.dot(a,a)
    print(r,r.shape)   #2.49046445333 ()
    
    
    r = np.dot(a,a.T)
    print(r,r.shape)   #2.49046445333 ()
    
    
    #a1为5x1的列向量
    a1 = np.random.randn(5,1)
    print(a1,a1.shape)   #[[-0.20126605]
                         # [-0.08183096]
                         # [ 0.12709234]
                         # [ 1.88915869]
                         # [1.18566033]] (5, 1)   
    
    #r1 = np.dot(a1,a1)   #会报错   shapes (5,1) and (5,1) not aligned: 1 (dim 1) != 5 (dim 0)
    #print(r1,r1.shape)
    
    
    r1 = np.dot(a1,a1.T)
    print(r1,r1.shape)   #[[ 0.04050802  0.01646979 -0.02557937 -0.3802235  -0.23863317]
                         # [ 0.01646979  0.00669631 -0.01040009 -0.15459166 -0.09702372]
                         # [-0.02557937 -0.01040009  0.01615246  0.24009759  0.15068834]
                         # [-0.3802235  -0.15459166  0.24009759  3.56892057  2.23990052]
                         # [-0.23863317 -0.09702372  0.15068834  2.23990052  1.40579042]] (5, 5) 
    
    #a2为1x5的行向量
    a2 = np.random.randn(1,5)
    print(a2,a2.shape)   #[ 0.48272148  0.4743339  -0.31309436  2.01153588 -0.58482391] (5,) 
    
    #r2 = np.dot(a2,a2)   #会报错   shapes (1,5) and (,5) not aligned: 5 (dim 5) != 1 (dim 0)
    #print(r2,r2.shape)
    
    
    r2= np.dot(a2,a2.T)
    print(r2,r2.shape)    #[[ 3.81502768]] (1, 1)


    #由list或者touple转换为的秩为数组,我们最好指定其shape
    c = np.array([1,2,3,4])
    print(c.shape)      #(4,)

    c = np.array([1,2,3,4]).reshape(4,1)
    print(c.shape)      #(4,1)

    d = np.array([[1,2,3],[4,5,6]])
    print(d.shape)     #(2,3)

    参考文献

    [1]Python3.1-标准库之Numpy

  • 相关阅读:
    使用正则表达式实现(加减乘除)计算器(C#实现)
    asp.net core中间件工作原理
    WPF
    WPF
    WPF
    WPF
    WPF 3D Cube及点击交互
    WPF 3D足球导览
    WPF 3D 球面导览
    WPF 3D球及进阶玩法
  • 原文地址:https://www.cnblogs.com/zyly/p/8560475.html
Copyright © 2020-2023  润新知