numpy中的matrix类
numpy提供了一个专门的矩阵处理模块:numpy.matlib。
1、矩阵创建函数。
2、矩阵的特殊属性。
3、矩阵的特殊函数。
备注:
( 1 ) 矩阵创建函数在numpy.matlib模块下,不过函数也有numpy命名空间,可以在numpy模块名下使用。
( 2 ) 矩阵类是:numpy.matrices
一、矩阵创建函数
numpy命名空间中的函数
创建函数 | 函数说明 |
---|---|
mat(data[, dtype]) | Interpret the input as a matrix. |
matrix(data[, dtype, copy]) | Returns a matrix from an array-like object, or from a string of data. |
asmatrix(data[, dtype]) | Interpret the input as a matrix. |
bmat(obj[, ldict, gdict]) | Build a matrix object from a string, nested sequence, or array. |
matlib命名空间中的函数
创建函数 | 函数说明 |
---|---|
empty(shape[, dtype, order]) | Return a new matrix of given shape and type, without initializing entries. |
zeros(shape[, dtype, order]) | Return a matrix of given shape and type, filled with zeros. |
ones(shape[, dtype, order]) | Matrix of ones. |
eye(n[, M, k, dtype, order]) | Return a matrix with ones on the diagonal and zeros elsewhere. |
identity(n[, dtype]) | Returns the square identity matrix of given size. |
repmat(a, m, n) | Repeat a 0-D to 2-D array or matrix MxN times. |
rand(*args) | Return a matrix of random values with given shape. |
randn(*args) | Return a random matrix with data from the “standard normal” distribution. |
注意:上述函数在新的版本中,为了方便,在numpy于numpy.matlib都有定义。如果在numpy中无效,则说明版本是老板,可以使用numpy.matlib
1. 创建矩阵函数的模块matlib
import numpy as np
m=np.mat ( [
[ 1, 2, 3],
[ 4, 5, 6]
] )
print ( m )
[[1 2 3]
[4 5 6]]
import numpy.matlib as mb
m=mb.empty( (2, 3 ) )
print ( m )
import numpy as np
m=mb.empty( (2, 3 ) )
print ( m )
#mat在numpy也定义。
m=mb.mat ( [
[ 1, 2, 3],
[ 4, 5, 6]
] )
print ( m )
[[4.9e-324 9.9e-324 1.5e-323]
[2.0e-323 2.5e-323 3.0e-323]]
[[4.9e-324 9.9e-324 1.5e-323]
[2.0e-323 2.5e-323 3.0e-323]]
[[1 2 3]
[4 5 6]]
2. matrix类
矩阵创建函数中matrix实际是类,定义如下:
class numpy.matrix(data, dtype=None, copy=True)[source]
其中data可是是字符串。
#下面输出的矩阵类型是matrix
mb.matrix ( [
[ 1, 2, 3],
[ 4, 5, 6]
] )
matrix([[1, 2, 3],
[4, 5, 6]])
# data可以是字符串:逗号表示列,分号表示行
data = '[ [ 1, 2, 3 ]; [ 4, 5, 6] ]'
mb.matrix ( data )
matrix([[1, 2, 3],
[4, 5, 6]])
# mat返回的都是矩阵类型
mb.mat ( [
[ 1, 2, 3],
[ 4, 5, 6]
] )
matrix([[1, 2, 3],
[4, 5, 6]])
二、matrix的特殊属性
下面是matrxi新增属性属性
矩阵的属性 | 属性说明 |
---|---|
A | Return self as an ndarray object. |
A1 | Return self as a flattened ndarray. |
H | Returns the (complex) conjugate transpose of self. |
I | Returns the (multiplicative) inverse of invertible self. |
下面是从nadarray继承的属性
矩阵的属性 | 属性说明 |
---|---|
T | Returns the transpose of the matrix. |
base | Base object if memory is from some other object. |
ctypes | An object to simplify the interaction of the array with the ctypes module. |
data | Python buffer object pointing to the start of the array’s data. |
dtype | Data-type of the array’s elements. |
flags | Information about the memory layout of the array. |
flat | A 1-D iterator over the array. |
imag | The imaginary part of the array. |
itemsize | Length of one array element in bytes. |
nbytes | Total bytes consumed by the elements of the array. |
ndim | Number of array dimensions. |
real | The real part of the array. |
shape | Tuple of array dimensions. |
size | Number of elements in the array. |
strides | Tuple of bytes to step in each dimension when traversing an array. |
1. matrix独有属性的使用与理解
m= mb.matrix ( [
[ 1, 2, 3 ],
[ 4, 5, 6 ]
] )
#A属性m.A
print ( m.A ) #返回自己,只是类型是ndarray。
#A1属性
print ( m.A1 ) #返回自己,作为1-D数组。
m= mb.matrix ( [
[ 1+3j, 2-5j, 4+7j ],
[ 2+6j, 4+8j, 8-9j ]
] )
#H属性
print ( m.H ) #返回复数的共轭矩阵
[[1 2 3]
[4 5 6]]
[1 2 3 4 5 6]
[[1.-3.j 2.-6.j]
[2.+5.j 4.-8.j]
[4.-7.j 8.+9.j]]
2. 矩阵的可逆矩阵
矩阵为阶方阵,若存在阶矩阵,使得矩阵、的乘积为单位阵,则称为可逆阵,为的逆矩阵。若方阵的逆阵存在,则称为可逆矩阵或非奇异矩阵,且其逆矩阵唯一。不可逆的矩阵也称奇异矩阵(Singular matrix)。
计算矩阵的逆矩阵有两种方法:
(1) ,其中为矩阵的伴随矩阵 ( 伴随矩阵就是使用代数余子式构成 )。
(2) 对作初等变换,将A化为单位阵E,单位矩阵E就化为可逆矩阵A 。
# I 属性
m= mb.matrix ( [
[ 2, 0, 0 ],
[ 0, 2, 0 ],
[ 0, 0, 2 ]
] )
print ( m.I ) #返回逆矩阵
#如果矩阵不可逆,要计算其可逆矩阵则返回如下错误:LinAlgError: Singular matrix。
#可逆矩阵必须是方阵。
#对非方阵,也能求逆矩阵
m= mb.matrix ( [
[ 1, 2, 3 ],
[ 4, 5, 6 ]
] )
print ( m.I )
print ( m.dot ( m.I ) ) # 接近单位矩阵E。
print ( (m.I).dot ( m ) ) #这个矩阵不是单位矩阵E。
[[0.5 0. 0. ]
[0. 0.5 0. ]
[0. 0. 0.5]]
[[-0.94444444 0.44444444]
[-0.11111111 0.11111111]
[ 0.72222222 -0.22222222]]
[[ 1.00000000e+00 3.60822483e-16]
[-1.11022302e-15 1.00000000e+00]]
[[ 0.83333333 0.33333333 -0.16666667]
[ 0.33333333 0.33333333 0.33333333]
[-0.16666667 0.33333333 0.83333333]]
三、 matrix的特殊函数
matrix独有的函数
继承函数 | 函数说明 |
---|---|
getA() | Return self as an ndarray object. |
getA1() | Return self as a flattened ndarray. |
getH() | Returns the (complex) conjugate transpose of self. |
getI() | Returns the (multiplicative) inverse of invertible self. |
从nadarray继承的函数
继承函数 | 函数说明 |
---|---|
getT() | Returns the transpose of the matrix. |
all([axis, out, keepdims]) | Returns True if all elements evaluate to True. |
any([axis, out, keepdims]) | Returns True if any of the elements of a evaluate to True. |
argmax([axis, out]) | Return indices of the maximum values along the given axis. |
argmin([axis, out]) | Return indices of the minimum values along the given axis of a. |
argpartition(kth[, axis, kind, order]) | Returns the indices that would partition this array. |
argsort([axis, kind, order]) | Returns the indices that would sort this array. |
astype(dtype[, order, casting, subok, copy]) | Copy of the array, cast to a specified type. |
byteswap([inplace]) | Swap the bytes of the array elements |
choose(choices[, out, mode]) | Use an index array to construct a new array from a set of choices. |
clip([min, max, out]) | Return an array whose values are limited to [min, max]. |
compress(condition[, axis, out]) | Return selected slices of this array along given axis. |
conj() | Complex-conjugate all elements. |
conjugate() | Return the complex conjugate, element-wise. |
copy([order]) | Return a copy of the array. |
cumprod([axis, dtype, out]) | Return the cumulative product of the elements along the given axis. |
cumsum([axis, dtype, out]) | Return the cumulative sum of the elements along the given axis. |
diagonal([offset, axis1, axis2]) | Return specified diagonals. |
dot(b[, out]) | Dot product of two arrays. |
dump(file) | Dump a pickle of the array to the specified file. |
dumps() | Returns the pickle of the array as a string. |
fill(value) | Fill the array with a scalar value. |
flatten([order]) | Return a copy of the array collapsed into one dimension. |
getfield(dtype[, offset]) | Returns a field of the given array as a certain type. |
item(*args) | Copy an element of an array to a standard Python scalar and return it. |
itemset(*args) | Insert scalar into an array (scalar is cast to array’s dtype, if possible) |
max([axis, out, keepdims]) | Return the maximum along a given axis. |
mean([axis, dtype, out, keepdims]) | Returns the average of the array elements along given axis. |
min([axis, out, keepdims]) | Return the minimum along a given axis. |
newbyteorder([new_order]) | Return the array with the same data viewed with a different byte order. |
nonzero() | Return the indices of the elements that are non-zero. |
partition(kth[, axis, kind, order]) | Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array. |
prod([axis, dtype, out, keepdims]) | Return the product of the array elements over the given axis |
ptp([axis, out]) | Peak to peak (maximum - minimum) value along a given axis. |
put(indices, values[, mode]) | Set a.flat[n] = values[n] for all n in indices. |
ravel([order]) | Return a flattened array. |
repeat(repeats[, axis]) | Repeat elements of an array. |
reshape(shape[, order]) | Returns an array containing the same data with a new shape. |
resize(new_shape[, refcheck]) | Change shape and size of array in-place. |
round([decimals, out]) | Return a with each element rounded to the given number of decimals. |
searchsorted(v[, side, sorter]) | Find indices where elements of v should be inserted in a to maintain order. |
setfield(val, dtype[, offset]) | Put a value into a specified place in a field defined by a data-type. |
setflags([write, align, uic]) | Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. |
sort([axis, kind, order]) | Sort an array, in-place. |
squeeze([axis]) | Remove single-dimensional entries from the shape of a. |
std([axis, dtype, out, ddof, keepdims]) | Returns the standard deviation of the array elements along given axis. |
sum([axis, dtype, out, keepdims]) | Return the sum of the array elements over the given axis. |
swapaxes(axis1, axis2) | Return a view of the array with axis1 and axis2 interchanged. |
take(indices[, axis, out, mode]) | Return an array formed from the elements of a at the given indices. |
tobytes([order]) | Construct Python bytes containing the raw data bytes in the array. |
tofile(fid[, sep, format]) | Write array to a file as text or binary (default). |
tolist() | Return the array as a (possibly nested) list. |
tostring([order]) | Construct Python bytes containing the raw data bytes in the array. |
trace([offset, axis1, axis2, dtype, out]) | Return the sum along diagonals of the array. |
transpose(*axes) | Returns a view of the array with axes transposed. |
var([axis, dtype, out, ddof, keepdims]) | Returns the variance of the array elements, along given axis. |
view([dtype, type]) | New view of array with the same data. |
1. matrix 独有方法的使用
#matrix都有的几个函数都对应着属性。
m= mb.matrix ( [
[ 1, 2, 3 ],
[ 4, 5, 6 ]
] )
print ( m.getI ( ) )
[[-0.94444444 0.44444444]
[-0.11111111 0.11111111]
[ 0.72222222 -0.22222222]]
2. ndarray几个函数使用的补充
clip函数
ndarray.clip(min=None, max=None, out=None)
返回一个数组,数组的值限制在 [min, max]. 比min下的都设置为min,比max大的都设置为max。
m= mb.matrix ( [
[ 7, 4, 3, 6, 5, 1 ],
[ 2, 5, 9, 7, 1, 8 ]
] )
print ( m.clip ( min = 3, max = 6 ) )
[[6 4 3 6 5 3]
[3 5 6 6 3 6]]
conj函数与conjugate函数
ndarray.conj()
ndarray.conjugate()
都是返回复数共轭矩阵
m= mb.matrix ( [
[ 1+3j, 2-5j, 4+7j ],
[ 2+6j, 4+8j, 8-9j ]
] )
print ( m.conj ( ) )
print ( m.conjugate ( ) )
print ( m.H )
print ( m.getH ( ) )
[[1.-3.j 2.+5.j 4.-7.j]
[2.-6.j 4.-8.j 8.+9.j]]
[[1.-3.j 2.+5.j 4.-7.j]
[2.-6.j 4.-8.j 8.+9.j]]
[[1.-3.j 2.-6.j]
[2.+5.j 4.-8.j]
[4.-7.j 8.+9.j]]
[[1.-3.j 2.-6.j]
[2.+5.j 4.-8.j]
[4.-7.j 8.+9.j]]
dot函数
ndarray.dot(b, out=None)
计算内积(内积必须满足条件:mxn nxk,返回mxk的矩阵)
A = mb.matrix ( [
[ 1, 2, 3 ],
[ 4, 5, 6 ]
] )
B = mb.matrix ( [
[ 1, 2],
[ 4, 5],
[ 7, 8]
] )
print ( A.dot( B ) )
print ( A @ B )
print ( B.dot( A ) )
print ( B @ A )
[[30 36]
[66 81]]
[[30 36]
[66 81]]
[[ 9 12 15]
[24 33 42]
[39 54 69]]
[[ 9 12 15]
[24 33 42]
[39 54 69]]
ptp函数
ndarray.ptp(axis=None, out=None)
最大值与最小值只差(maximum - minimum)
ptp是peak to peak缩写(峰到峰)
A = mb.matrix ( [
[ 1, 2, 3 ],
[ 4, 5, 6 ]
] )
print ( A.ptp ( ) )
print ( A.ptp ( axis=0 ) )
print ( A.ptp ( axis=1 ) )
5
[[3 3 3]]
[[2]
[2]]
round函数
ndarray.round(decimals=0, out=None)
返回四舍五入矩阵
decimals=0 设置精度(小数点位数)
A = mb.matrix ( [
[ 1.4, 2.9, 3.5 ],
[ 4.49, 5.51, 6.3 ]
] )
print ( A.round ( ) )
print ( A.round ( decimals =1 ) )
[[1. 3. 4.]
[4. 6. 6.]]
[[1.4 2.9 3.5]
[4.5 5.5 6.3]]
swapaxes函数
ndarray.swapaxes(axis1, axis2)
交换坐标轴
A = mb.matrix ( [
[ 1.4, 2.9, 3.5 ],
[ 4.49, 5.51, 6.3 ]
] )
print ( A.swapaxes ( 0, 1 ) ) #对2-D矩阵来说就是转置。
[[1.4 4.49]
[2.9 5.51]
[3.5 6.3 ]]
【资源】
本文使用ipython notebook格式编辑,文件下载:
【ndarray_matrix.ipynb】