【numpy学习笔记】矩阵操作

转置

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])
发布了255 篇原创文章 · 获赞 362 · 访问量 32万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览