numpy之矩阵

匿名 (未验证) 提交于 2019-12-02 23:47:01

---恢复内容开始---

一、矩阵的创建(三种方法)

'''     矩阵:其是numpy.matrix类型对象,该类继自ndarray,所以几乎所有针对ndarry数组的操作,对矩阵对象同样有效,         作为子类,矩阵又集合了自身的特点做了必要的扩充,如:矩阵的乘法运算、求逆等 ''' import numpy as np  # 创建矩阵 ary = np.arange(1, 10).reshape(3, 3) print(ary, type(ary)) # 方法1 m = np.matrix(ary, copy=True) print(m, type(m)) ary[0, 0] = 999 print(m, type(m)) print('-------------------') # 方法2 m = np.mat('1 2 3;4 5 6;7 8 9') print(m) # 方法3:等价于np.matrix(ary,copy=False)--->矩阵数据与数组数据共享 m = np.mat(ary) print(m)   输出结果:          [[1 2 3]  [4 5 6]  [7 8 9]] <class 'numpy.ndarray'> [[1 2 3]  [4 5 6]  [7 8 9]] <class 'numpy.matrix'> [[1 2 3]  [4 5 6]  [7 8 9]] <class 'numpy.matrix'> ------------------- [[1 2 3]  [4 5 6]  [7 8 9]] [[999   2   3]  [  4   5   6]  [  7   8   9]]     

二、矩阵的乘法运算----点积

  

'''     矩阵:其是numpy.matrix类型对象,该类继自ndarray,所以几乎所有针对ndarry数组的操作,对矩阵对象同样有效,         作为子类,矩阵又集合了自身的特点做了必要的扩充,如:矩阵的乘法运算、求逆等 ''' import numpy as np  # 创建矩阵 ary = np.arange(1, 10).reshape(3, 3) print(ary, type(ary)) # 方法1 m = np.matrix(ary, copy=True) print(m) print('==================') # 矩阵的乘法运算 print(m * m) a = np.arange(1, 4) # a = np.mat(a) b = np.arange(4, 7) # b = np.mat(b) print(a.dot(b), type(a.dot(b)))  输出结果:     [[1 2 3]  [4 5 6]  [7 8 9]] <class 'numpy.ndarray'> [[1 2 3]  [4 5 6]  [7 8 9]] ================== [[ 30  36  42]  [ 66  81  96]  [102 126 150]] 32 <class 'numpy.int32'>

三、矩阵的逆

  判断矩阵是否有逆矩阵方法:

      1>矩阵的行列式不等于零
      2>矩阵为满秩矩阵
      3>矩阵的合同标准型是单位矩阵

'''     矩阵求逆 ''' import numpy as np  # 创建矩阵 b = np.mat('4 6 7;2 3 7;8 4 2') # 求矩阵的逆 print(b) print(b.I) print(b * b.I) print(np.linalg.inv(b))  输出结果:  [[4 6 7]  [2 3 7]  [8 4 2]] [[-0.19642857  0.14285714  0.1875    ]  [ 0.46428571 -0.42857143 -0.125     ]  [-0.14285714  0.28571429  0.        ]] [[ 1.00000000e+00 -1.11022302e-16  0.00000000e+00]  [ 5.55111512e-17  1.00000000e+00  0.00000000e+00]  [-1.11022302e-16  0.00000000e+00  1.00000000e+00]] [[-0.19642857  0.14285714  0.1875    ]  [ 0.46428571 -0.42857143 -0.125     ]  [-0.14285714  0.28571429  0.        ]]

四、示例

  

'''     矩阵求解案例:假设学校旅游,去程小孩票价3元,家长3.2元,共花了118.4元;     回来时小孩票价3.5元,家长票价3.6元,共花了135.2元,求小孩和家长的人数 ''' import numpy as np  # 方法1 prices = np.mat('3 3.2;3.5 3.6') totals = np.mat('118.4;135.2') x = np.linalg.lstsq(prices, totals, rcond=-1)[0] print(x)  print('-----------')  # 方法2 persons = prices.I * totals print(persons)   输出结果: [[16.]  [22.]] ----------- [[16.]  [22.]]

  

---恢复内容结束---

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!