--- 恢复内容开始 ---
一, 矩阵的创建 (三种方法)
- '''
- 矩阵: 其是 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.]]
--- 恢复内容结束 ---
来源: http://www.bubuko.com/infodetail-3120065.html