您的位置:首页 > 编程语言 > Python开发

NumPy 数组矩阵运算

2016-05-29 13:16 363 查看
原文地址:http://blog.csdn.net/lsjseu/article/details/20359201

在原文基础上适当精简并更正少量原作者的笔误:

 

线性代数

1.  简单数组运算

>>> from numpy import *
>>> from numpy.linalg import *

>>> a = array([[1.0, 2.0], [3.0, 4.0]])
>>> print a
[[ 1.  2.]
[ 3.  4.]]

>>> a.transpose()
array([[ 1.,  3.],
[ 2.,  4.]])

>>> inv(a)
array([[-2. ,  1. ],
[ 1.5, -0.5]])

>>> u = eye(2) # unit 2x2 matrix; "eye" represents "I"
>>> u
array([[ 1.,  0.],
[ 0.,  1.]])
>>> j = array([[0.0, -1.0], [1.0, 0.0]])

>>> dot (j, j) # matrix product
array([[-1.,  0.],
[ 0., -1.]])

>>> trace(u)  # trace
2.0

>>> y = array([[5.], [7.]])
>>> solve(a, y)
array([[-3.],
[ 4.]])

>>> eig(j)
(array([ 0.+1.j,  0.-1.j]),
array([[ 0.70710678+0.j,  0.70710678+0.j],
[ 0.00000000-0.70710678j,  0.00000000+0.70710678j]]))
Parameters:
square matrix

Returns
The eigenvalues, each repeated according to its multiplicity.

The normalized (unit "length") eigenvectors, such that the
column ``v[:,i]`` is the eigenvector corresponding to the
eigenvalue ``w[i]`` .


2.  矩阵类运算

>>> A = matrix('1.0 2.0; 3.0 4.0')
>>> A
[[ 1.  2.]
[ 3.  4.]]
>>> type(A)  # file where class is defined

>>> A.T  # transpose
[[ 1.  3.]
[ 2.  4.]]

>>> X = matrix('5.0 7.0')
>>> Y = X.T
>>> Y
[[5.]
[7.]]

>>> print A*Y  # matrix multiplication
[[19.]
[43.]]

>>> print A.I  # inverse
[[-2.   1. ]
[ 1.5 -0.5]]

>>> solve(A, Y)  # solving linear equation
matrix([[-3.],
[ 4.]])


3.  要注意很重要的一点就是NumPy切片数组不创建数据的副本;切片提供统一数据的视图:

>>> A = arange(12)
>>> A
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> A.shape = (3,4)
>>> M = mat(A.copy())
>>> print type(A),"  ",type(M)

>>> print A
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]
>>> print M
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]

>>> print A[:]; print A[:].shape
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]
(3, 4)
>>> print M[:]; print M[:].shape
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]
(3, 4)

>>> print A[:,1]; print A[:,1].shape
[1 5 9]
(3,)
>>> print M[:,1]; print M[:,1].shape
[[1]
[5]
[9]]
(3, 1)


注意最后两个结果的不同。对二维数组使用一个冒号产生一个一维数组,然而矩阵产生了一个二维矩阵。

例如,一个 M[2,:] 切片产生了一个形状为(1,4)的矩阵,相比之下,一个数组的切片总是产生一个尽可能低维度的数组。

例如,如果C是一个3维数组, C[...,1] 产生一个二维的数组而 C[1,:,1] 产生一个一维数组。

从这时开始,如果相应的矩阵切片结果是相同的话,我们将只展示数组切片的结果。

假如我们想要一个数组的第一列和第三列,一种方法是使用列表切片:

>>> A[:,[1,3]]
array([[ 1,  3],
[ 5,  7],
[ 9, 11]])
如果我们想跳过第一行:

>>> A[1:,].take([1,3],axis=1)
array([[ 5,  7],
[ 9, 11]])
or
<pre name="code" class="python">>>> A[1:,[1,3]]



现在让我们做些更复杂的。比如说我们想要保留第一行大于1的列。方法是创建布尔索引:

>>> A[0,:]>1
array([False, False, True, True], dtype=bool)
>>> A[:,A[0,:]>1]
array([[ 2,  3],
[ 6,  7],
[10, 11]])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  numpy python