赞
踩
初学python试图通过矩阵简化运算,感谢网友智慧,做个摘抄给自己留恋。
本文记录了Numpy 数组和矩阵应用的区别 。
# 创建矩阵2 X 2的矩阵 A_mat 和 二维数组 A_array
import numpy as np
A_mat = np.mat([[1, 2],[3, 4]], int)
A_array = np.array([[1, 2],[3, 4]])
print(A_mat, type(A_mat))
print(A_array, type(A_array))
#结果
[[1 2]
[3 4]] <class 'numpy.matrix'>
[[1 2]
[3 4]] <class 'numpy.ndarray'>
b1=np.array([[1],[2]])
b2=np.array([[1,2]])
#结果
print('b1:',b1)
print('b2:',b2)
b1: [[1]
[2]]
b2: [[1 2]]
A_array = np.array([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4],[5,5,5,5,5]]) B_array = np.array([0.1,0.01,0.001,0.0001,0.00001]) X1 = A_array * X + B_array X2 = A_array .dot(X) + B_array #结果 print('X1:',X1) print('X2:',X2) X1: [[1.1000000e+00 1.0010000e+01 1.0000100e+02 1.0000001e+03 1.0000000e+04] [2.1000000e+00 2.0010000e+01 2.0000100e+02 2.0000001e+03 2.0000000e+04] [3.1000000e+00 3.0010000e+01 3.0000100e+02 3.0000001e+03 3.0000000e+04] [4.1000000e+00 4.0010000e+01 4.0000100e+02 4.0000001e+03 4.0000000e+04] [5.1000000e+00 5.0010000e+01 5.0000100e+02 5.0000001e+03 5.0000000e+04]] X2: [11111.1 22222.01 33333.001 44444.0001 55555.00001]
A=np.array([[1,2,3],[4,5,6],[7,8,9]]) B1=np.zeros((3,1)) B1[0,0] = 10 B1[1,0] = 100 B1[2,0] = 1000 B2=np.array([10,100,1000]) C1=A@B1 C2=A@B2 D1=C1+B1 D2=C2+B1 D3=C1+B2 D4=C2+B2 print("A=",A,A.shape) print("B1=",B1,B1.shape) print("B2=",B2,B2.shape) print("C1=",C1,C1.shape) print("C2=",C2,C2.shape) print("D1=",D1,D1.shape) print("D2=",D2,D2.shape) print("D3=",D3,D3.shape) print("D4=",D4,D4.shape) #结果 A= [[1 2 3] [4 5 6] [7 8 9]] (3, 3) B1= [[ 10.] [ 100.] [1000.]] (3, 1) B2= [ 10 100 1000] (3,) C1= [[3210.] [6540.] [9870.]] (3, 1) C2= [3210 6540 9870] (3,) D1= [[ 3220.] [ 6640.] [10870.]] (3, 1) D2= [[ 3220. 6550. 9880.] [ 3310. 6640. 9970.] [ 4210. 7540. 10870.]] (3, 3) D3= [[ 3220. 3310. 4210.] [ 6550. 6640. 7540.] [ 9880. 9970. 10870.]] (3, 3) D4= [ 3220 6640 10870] (3,)
虽然B1和B2形式相同,但是从shape函数的输出结果可以看到,B1是维数确定的数组,B2是位数不确定的数组。用B1和B2和A进行点乘运算时,结果维数和B1和B2相同。然而,当进行加法运算时,维数不同的加法会把扩大矩阵维数,如D2和D3的结果。
2. 查资料也发现,取矩阵的某一行会出现维度消失的问题。
B3=A[:,1]
print(B3.shape)
#结果
(3,)
B4=A[:,1,None]
print("B4",B4,B4.shape)
#结果
B4 [[2]
[5]
[8]] (3, 1)
b)用reshape改造
B5=(A[:,1]).reshape(A.shape[0],1)
print("B5",B5,B5.shape)
#结果
B5 [[2]
[5]
[8]] (3, 1)
[1]https://zhuanlan.zhihu.com/p/163281949
[2] https://blog.csdn.net/u011851421/article/details/83783826
[3] https://blog.csdn.net/sinat_24259567/article/details/98317504
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。