numpy常用代码总结

1、矩阵特征值和特征向量

下面这段代码展示了用numpy求矩阵特征值和特征向量的方法:

import numpy as np
from numpy import linalg as LA

a = np.array([[-2, -36, 0], [-36, -23, 0], [0, 0, 3]])
w, v = LA.eig(a)

输出结果:

w
array([ 25., -50.,   3.])

v
array([[ 0.8,  0.6,  0. ],
       [-0.6,  0.8,  0. ],
       [ 0. ,  0. ,  1. ]])

 

2、点乘法和矩阵乘法

import numpy as np

'''
a = 1  2
    3  4
    5  6
    
b = 1
    2
'''
a = np.array([[1, 2], [3, 4], [5, 6]])
b = np.array([1, 2])

c = np.dot(a, b)
print('dot product of a and b is ', c)
d = np.matmul(a, b)
print('matrix multiplicity is ', d)


x1 = np.random.randint(1, 10, size=(1, 2))
'''
change the statement like this:
x1 = np.random.randint(1, 10, size=(1, 2))
you will get the same result.
'''

x2 = np.random.randint(1, 10, size=(2))
x3 = np.dot(x1, x2)
print("x1 is ", x1, "its shape is ", x1.shape)
print("x2 is ", x2, "its shape is ", x2.shape)
print("x1 * x2 = ", x3)

 3、洗牌

import numpy as np

a = np.random.randint(1, 10, 10)
print(a)
np.random.shuffle(a)
print(a)

输出:

[6 4 6 8 4 4 5 6 8 2]
[6 6 5 6 8 2 4 8 4 4]

 

posted @ 2018-09-17 11:48  lichongbin  阅读(1400)  评论(0编辑  收藏  举报