python numpy矩阵操作
文章目录
1. ones() 生成全1矩阵
>>> np.ones(5)
array([1., 1., 1., 1., 1.])
>>> np.ones((5,), dtype=int)
array([1, 1, 1, 1, 1])
>>> np.ones((2, 1))
array([[1.],
[1.]])
>>> s = (2,2)
>>> np.ones(s)
array([[1., 1.],
[1., 1.]])
2. zeros() 零矩阵
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])
>>> np.zeros((2, 1))
array([[ 0.],
[ 0.]])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
dtype=[('x', '<i4'), ('y', '<i4')])
3. arange() 在给定的间隔内返回均匀间隔的值。
值是在半开间隔[start, stop)内生成的(换句话说,包括start但不包括stop的间隔)。
对于整型参数,该函数相当于Python内置的range函数,但返回的是ndarray而不是list。
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
4. reshape() 改变矩阵形状
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
5. transpose() 或 T 转置矩阵
>>> np.transpose(x)
array([[0, 2],
[1, 3]])
>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)
>>> x = np.ones((2, 3, 4, 5))
>>> np.transpose(x).shape
(5, 4, 3, 2)
x=np.arange(9).reshape(3,3)
x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
x.T
array([[0, 3, 6],
[1, 4, 7],
[2, 5, 8]])
6. I 求逆矩阵(ndarray不行,要先转化为matrix)
>>> l=[[1,2],[2,1]]
>>> x=np.matrix(l)
>>> x.I
matrix([[-0.33333333, 0.66666667],
[ 0.66666667, -0.33333333]])
7. random.rand() 生成随机数
>>> np.random.rand(5)
array([0.98780692, 0.91722709, 0.65190955, 0.69180064, 0.02656584])
>>> np.random.rand(3,2)*10+10
array([[13.5878008 , 14.68702715],
[17.32597083, 16.86564768],
[12.04615693, 11.53085938]])
8. hstack() 任意水平排列(按列排列)的堆栈数组。
>>> a = np.array((1,2,3))
>>> b = np.array((4,5,6))
>>> np.hstack((a,b))
array([1, 2, 3, 4, 5, 6])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[4],[5],[6]])
>>> np.hstack((a,b))
array([[1, 4],
[2, 5],
[3, 6]])
9. dot() 点乘
>>> np.dot(3, 4)
12
Neither argument is complex-conjugated:
>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
For 2-D arrays it is the matrix product:
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
[2, 2]])
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128
10. mat() 把list或者array变成矩阵
>>> x = np.array([[1, 2], [3, 4]])
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])