首页 > 其他 > 详细

numpy之矩阵

时间:2019-07-11 11:06:08      阅读:106      评论:0      收藏:0      [点我收藏+]

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

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

‘‘‘
    矩阵:其是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.]]

 

 

  

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

numpy之矩阵

原文:https://www.cnblogs.com/yuxiangyang/p/11168436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!