当前位置:网站首页>Numpy basic operation

Numpy basic operation

2022-06-10 00:11:00 Stone to diamond?

This is a review of the basics , Cross reference table of contents , Review the relevant content , Students studying together can also try this method to build a foundation .

Import the package first

import numpy as np

Create a vector

vct_row = np.array([1, 2, 3])  #  Row vector 
vct_col = np.array([[4],
				[5],
				[6]])   #  Column vector 

Create a matrix

matrix = np.array([[1, 2, 3],
					[4, 5, 6],
					[7, 8, 9]])
mtx = np.mat([[1, 2, 3],
			  [4, 5, 6],
			  [7, 8, 9]])

Create sparse matrix

from scipy import sparse
mtx = np.array([[0, 2, 3],
				[4, 0, 0],
				[7, 8, 0]])
#  Compression matrix 
mtx_sparse = sparse.csr_matrix(mtx)

Show matrix properties

#  Line number 
mtx.shape  #  Note that there are no parentheses at the end 
vct.shape
#  Number 
mtx.size
#  dimension 
mtx.ndim

Multiple elements apply an operation

#  radio broadcast (radcasting)
mtx + 100
#  There is another way to view books 
add_100 = lambda i: 1 + 100
vct_add_100 = np.vectorize(add_100)
vct_add_100(mtx)

Maximum and minimum

#  Maximum 
mtx.max(axis = 1)  # axis, 0 is col,1 is row.
np.max(mtx, axis = 0)

#  minimum value 
mtx.min()
np.min(mtx)

mean value 、 variance 、 Standard deviation

#  mean value 
np.mean(mtx, axis = 0)
mtx.mean(axis = 1)
#  variance 
np.var(mtx)
mtx.var()
#  Standard deviation 
np.std(mtx)
mtx.var()

Matrix distortion

mtx.reshape(row, col)  # mtx.size = row*col
mtx.reshape(1, -1)

Transposition

mtx.T
vct.T

Expand the matrix

mtx.flatten()

Calculate the rank of the matrix

np.linalg.matrix_rank(mtx)

Calculate determinant

np.linalg.det(mtx)

Get the diagonal elements of the matrix

mtx.diagonal(offset = 1)

Calculate the trace of the matrix

mtx.trace()

Calculate the eigenvalues and eigenvectors

feature, vector = np.linalg.eig(mtx)

Calculate the dot product of the vector

np.dot(vector1, vector2)

Matrix addition or subtraction

np.add(matrix1, matrix2)
np.subtract(matrix1, matrix2)

Matrix multiplication ## Pay attention to distinguish between dot multiplication and corresponding element multiplication

np.dot(matrix1, matrix2)
matrix1 @ matrix2  # python3.5 Above version , It should be almost all now ?..
#  The corresponding elements are multiplied by 
matrix1 * matrix2

The matrix of the inverse

np.linalg.inv(mtx)
If inverse matrix exists , be
mtx @ np.linalg.inv(mtx) Should be an identity matrix , The computer is infinitely close 1 Value

The monkey is in a hurry

In practice , Some may not remember , It can be used dir(mtx), dir(vct) See what is included

Welcome to share and supplement

原网站

版权声明
本文为[Stone to diamond?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206092301327603.html