【numpy學習筆記】矩陣操作

Datawhale發表於2018-07-11

轉置

a = np.array([[1,2,3],[3,4,5]],dtype='float')
# array([[ 1.,  2.,  3.],
         [ 3.,  4.,  5.]])
a.T  
# array([[ 1.,  3.],
         [ 2.,  4.],
         [ 3.,  5.]])
a = np.array([[[1,2,3,0],[3,4,5,2]]])
# array([[[1, 2, 3, 0],
          [3, 4, 5, 2]]])

#   array([[[1, 3],
            [2, 4],
            [3, 5],
            [0, 2]]])
# a.transpose可以指定到底要怎麼變換:比如原來是 [1,2,4],可以指定轉變的方式 [0,2,1]
# 這個 [0,2,1] 的意思是 第一個維度不變,後兩個維度交換,那麼形狀就變成了 [1,4,2]

求逆矩陣

# 求逆矩陣
# This calculates the inverse of a matrix
>>>from numpy.linalg import inv
>>>a = np.array([[1., 2.], [3., 4.]])
>>>inv(a)
array([[-2. ,  1. ],
       [ 1.5, -0.5]])
>>>ainv = inv(a)
# here is to check if np.dot(a, ainv) equals to I matrix A * A逆 = 
>>>np.allclose(np.dot(a, ainv), np.eye(2))
True

求特徵值

#求特徵值
>>>from numpy.linalg import *
>>>a = np.array([[1,2,3],[3,4,5]],dtype='float')
>>>np.linalg.eig(np.dot(a.T,a)) 
(array([6.36227766e+01, 3.77223398e-01, 1.16614561e-15]),
 array([[-0.39133557, -0.8247362 ,  0.40824829],
        [-0.5605708 , -0.13817999, -0.81649658],
        [-0.72980603,  0.54837623,  0.40824829]]))

求對角和

# Return the sum along diagonals of the array.求對角和
>>>a = np.array([[1., 2.], [3., 4.]])
>>>np.trace(a)
5.0

交換行列

# Return a view of the array with `axis1` and `axis2` interchanged.
>>>a = np.array([[1., 2.], [3., 4.]])
>>>a.swapaxes(1,0)
array([[ 1.,  3.],
       [ 2.,  4.]])

計算陣列中非負數出現的次數

# Count number of occurrences of each value in array of non-negative ints.
>>>np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) 
array([1, 3, 1, 1, 0, 0, 0, 1], dtype=int64)

Universal Functions

>>>a = np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>np.exp(a)
array([1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01,
       5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03,
       2.98095799e+03, 8.10308393e+03])
>>>np.sqrt(a)
array([ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ,
        2.23606798,  2.44948974,  2.64575131,  2.82842712,  3.        ])

>>>b = np.random.randn(10)
array([-0.16569888,  0.59625817, -0.79988162,  2.21359273, -0.69462344,
        0.61648668,  0.09869501, -0.22239437, -1.155591  , -0.5204446 ])
>>>c = np.random.randn(10).reshape(2,5)
array([[ 0.57416664, -0.0885477 , -0.53258925,  0.64967919, -2.6187962 ],
       [ 0.74204145,  0.13735184,  0.4516909 ,  0.66379306, -0.08035595]])
>>>np.add(b,c)
array([-0.44751905,  0.02907221,  2.2269195 , -1.54937333,  1.60076085,
        2.03151324, -1.4535573 , -1.37325156, -1.45352241, -2.76061538])

相關文章