• Python之numpy


     

    1.查询矩阵的大小:.shape
    import numpy as np
    a = np.array([1, 2, 3, 4])
    b = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
    print (a.shape)
    print ('---')
    print (b.shape)
    type(a.shape) # 输出 (4,) --- (3, 4)
    tuple #这说明shape输出对象是一个元组类型,存储一个元素时表明对象是一个一维数组,有两个元素即为二维数组。

    如:(4, )shape有一个元素即为一维数组,数组中有4个元素 
           (3, 4)shape有两个元素即为二维数组,数组为3行4列

    1.1通过修改数组的shape属性,在保持数组元素个数不变的情况下,改变数组每个轴的长度。下面的例子将数组b的shape改为(4, 3),从(3, 4)改为(4, 3)并不是对数组进行转置,而只是改变每个轴的大小,数组元素在内存中的位置并没有改变:

    b.shape = 4, 3
    print (b)
    # 输出 [[ 1  2  3]
     [ 4  4  5]
     [ 6  7  7]
     [ 8  9 10]]

    1.2.当某个轴的元素为-1时,将根据数组元素的个数自动计算该轴的长度,下面程序将数组b的shape改为了(2, 6):

    b.shape = 2, -1
    print (b)
    # 输出 [[ 1  2  3  4  4  5]
     [ 6  7  7  8  9 10]]

    2.使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变

    a = np.array((1, 2, 3, 4))
    b = a.reshape((2, 2))
    b
    # 输出 array([[1, 2],
           [3, 4]])
    a = np.array([[1,2,3,4],[2,3,4,5]])
    c = a.reshape(a.shape[0],-1)

    #输出 array=
    [[1 2 3 4]
     [2 3 4 5]]

    3.创建数组: .array 
    首先需要创建数组才能对其进行其它操作,通过给array函数传递Python的序列对象创建数组,如果传递的是多层嵌套的序列,将创建多维数组(如c):

    import numpy as np
    a = np.array([1, 2, 3, 4])
    b = np.array((5, 6, 7, 8))
    c = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
    print (a)
    print ('---')
    print (b)
    print ('---')
    print (c)
    # 输出 [1 2 3 4]
    ---
    [5 6 7 8]
    ---
    [[ 1  2  3  4]
     [ 4  5  6  7]
     [ 7  8  9 10]]
    • 若导入numpy用的是import numpy命令,那么在创建数组的时候用a = numpy.array([1, 2, 3, 4])的形式
    • 若导入numpy用的是import numpy as np命令,那么用 a = np.array([1, 2, 3, 4])
    4.数组元素的类型可以通过dtype属性获得
    db.dtype == float# dtpye是data-type的缩写,专门用于获取对象的数据类型
    http://blog.csdn.net/lwplwf/article/details/55506896
    http://blog.csdn.net/sinat_34474705/article/details/74458605

    5.行列向量表示方法:
    Python中可以通过numpy进行矩阵的运算。 
    其中, 
    a = array([1, 2]) 是列向量 
    b = array([[1,2]]) 是行向量 
    c = array([[1,2],[1,2]])是一个2x2的矩阵 
    可以看出,行向量就是普通矩阵的特殊情况

    6.Python numpy函数:dot()

    dot()函数是矩阵乘,而*则表示逐个元素相乘

     
  • 相关阅读:
    APP 元素定位总结(未完待补充)
    vue-axios常见请求配置和全局设置
    vue-axios发送并发请求
    vue-axios基本使用
    vue-vuex-store目录结构
    vue-vuex-modules的基本使用
    vue-vuex-actions的基本使用
    vue-vuex-mutations的类型常量
    vue-vuex-state响应式
    vue-vuex-mutation的提交风格
  • 原文地址:https://www.cnblogs.com/ylHe/p/7739289.html
Copyright © 2020-2023  润新知