当前位置:网站首页>*Code understanding *numpy basic (plus code) that must be understood
*Code understanding *numpy basic (plus code) that must be understood
2022-07-24 07:50:00 【Summer 여름이다】
2022 4 18 5:38
Ignoring small details may change the perception of the whole .
--insanena
Pycharm Next
import numpy as np # introduce numpy The basic library is abbreviated as np.
Definition to understand :
Scalar (scalar): Generally refers to a number ,-100,0.05,8, etc. ( Only in size , A quantity without direction )
Sequence (sequence): yes python The most basic data structure in , A sequence is used to hold an ordered set of data , All data has a unique place in the sequence , And the data in the sequence will be added in the order to allocate the index . The sequence contains a list of variable sequences (list) And the dictionary (dict), It also includes immutable sequence strings (str) And a tuple (tuple).
( vector (Vector) And list (List) Are two typical Sequence (Sequence).)
list (list): Based on linked list , It is the abstraction and extension of the linked list structure . Lists are used to store ordered , The object of the object . grammar : list [ start : end : step ].eg:x=[1,2,3,4,5,6]print(a[0:5:2])# Printing starts with the first element , Until the fifth element , In steps of 2 A list of . The result is [1,3,5]
vector (vector): Based on the array implementation , Therefore, it is also called array list (ArrayList)[1,2] [3,3,3] etc.
Array (array):np.array() The output is an array . Array is a concept of storing information in computer , The elements in the array can be numbers , It can also be numerical . For multiplication 、 Operations such as power and division , The operators and meanings of matrix operation and array operation are different , Array operation is defined by corresponding element operation , Use the dot operator , Operate on the corresponding elements .
matrix (matrix):[[1,2],[3,4]]2*2 Matrix etc. ( There is one more bracket than the vector ). Matrix is a concept in Computational Science , Elements in a matrix can only be numeric . Matrix operation is defined by linear transformation , Use the usual symbols .
tensor (tensor):[[[1,2],[3,4]],[[1,2],[3,4]]]( More than vectors 2 Two brackets , More than matrix 1 Two brackets )
torch.tensor() The output is tensor . among ,0 The tensor of a dimension is a scalar ,1 The tensor of a dimension is a vector ,2 The tensor of a dimension is a matrix , Greater than or equal to 3 The tensor unity of dimensions is called tensor .
1.np.array()
grammar :arr = np.array(data, dtype=dtype, copy=copy)# stay numpy Create a matrix in
# The connection and change of arrays
import numpy as np
#1:np.array() And np.asarray() The difference between
a=[[1,2,3],[4,5,6],[7,8,9]]# hold a Assign values to three vectors
b=np.array(a)#b Equal to array a
c=np.asarray(a)#c be equal to
a[2]=1# Definition a The third element of is equal to 1
print(a)
print(b)
print(c)
'''
The output is :
[[1, 2, 3], [4, 5, 6], 1]
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 2 3]
[4 5 6]
[7 8 9]]
'''
#2 When input is array
a=np.random.random((3,3))# Enter a 3*3 Is a set of random Numbers
print(a.dtype)
b=np.array(a,dtype='float32')
c=np.asarray(a,dtype='float32')
a[2]=2# The third number of each definition is 2
print(a)
print(b)
print(c)
'''
The output is :
float64
[[0.197422 0.79698091 0.47039659]
[0.04872883 0.77691557 0.42768748]
[2. 2. 2. ]]
[[0.197422 0.79698091 0.47039659]
[0.04872883 0.77691557 0.42768748]
[0.4383789 0.25756943 0.21566227]] #np.array Output is not 2
[[0.197422 0.79698091 0.47039659]
[0.04872883 0.77691557 0.42768748]
[2. 2. 2. ]] #np.asarray The output is 2, When float32 when , The output will not change
'''
#3: Input array Type to list type
a=np.random.random((3,3))
print(a.dtype)
b=a.tolist()
a[1]=2
print(a)
print(b)
'''
The output is :
float64
[[0.16345856 0.97967348 0.36779687]
[2. 2. 2. ]
[0.79421058 0.53767031 0.16113611]]
[[0.16345855721891467, 0.9796734821736771, 0.36779687339507416], [0.21354288752427475, 0.17388485497498962, 0.45500183183428156], [0.7942105804174061, 0.5376703139612654, 0.16113610637379305]]
When one 3*3 When the matrix of becomes a list , The defined elements will change
And the original element has also become longer
'''2.np.mat()mat And matrix identical
# About numpy.mat() Code practice
import numpy as np
from mpmath import matrix
from numpy import mat
#1: understand np.mat() The grammar of
m=np.mat([[1,2,3]])# Two square brackets indicate that only matrix format is accepted
x=np.matrix([[1,2,],[3,4]])
print('m:',m)#m yes 1*3 Matrix
print('x:',x)#x yes 2*2 Matrix
print('x Your first act :',m[0])# take m The first line of
#print('x Your first act :',m[0][1])# error , Unable to read the first line 2 It's worth
'''
The running result is :
m: [[1 2 3]]
x: [[1 2]
[3 4]]
x Your first act : [[1 2 3]]
'''
#2: take Python The list of is converted to NumPy Matrix
list=[1,2,3]# Define a sequence
print('list Convert to matrix :',mat(list))# The print sequence is converted to the value of the matrix
'''
The running result is :
list Convert to matrix : [[1 2 3]]
'''
#3: take Numpy dnarray convert to Numpy matrix
n = np.array([1,2,3])
print('n yes :',n)
print('np.mat(n) yes :',np.mat(n))# Matrix format , More brackets
'''
The running result is :
n yes : [1 2 3]
np.mat(n) yes : [[1 2 3]]
'''
#4: Sort and index values
m=np.mat([[2,5,1],[4,6,2]]) # establish 2 That's ok 3 Column matrices
print('m yes :',m)
m.sort() # Sort each row
print('m yes :',m)
print('m Of size:',m.shape)
print('m The number of lines is :',m.shape[0])
print('m The number of columns in is :',m.shape[1])
print(' All elements in the first line are :',m[1,:])# Get all the elements in the first row
print(m[1,0:1])# Print the first line 1 Elements , Pay attention to left closing and right opening
print(m[1,0:3])# Print the first three elements of the first line
print(m[1,0:2])# Print the first two elements of the first line
'''
The running result is :
m yes : [[2 5 1]
[4 6 2]]
m yes : [[1 2 5]
[2 4 6]]
m Of size: (2, 3)
m The number of lines is : 2
m The number of columns in is : 3
All elements in the first line are : [[2 4 6]]
[[2]]
[[2 4 6]]
[[2 4]]
'''
3.flatten() Flattening
import numpy as np
#1 Used in arrays
from numpy import array, mat, shape
a=[[1,3],[2,4],[3,5]]
a=array(a)
print(a.flatten())
'''
The output is :
[1 3 2 4 3 5]# Flatten the original into a 1*n Sequence
'''
#2 Used in list
#a = [[1, 3], [2, 4], [3, 5]]
#a.flatten()# Using it directly will make mistakes
a = [[1,3],[2,4],[3,5],["abc","def"]]
a1 = [y for x in a for y in x]
print(a1)
# In another way
a = [[1,3],[2,4],[3,5],["abc","def"]]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
print(flatten(a))
'''
The output is :
[1, 3, 2, 4, 3, 5, 'abc', 'def']
[1, 3, 2, 4, 3, 5, 'abc', 'def']
'''
#3 Used in matrix
a = [[1,3],[2,4],[3,5]]# Definition a It's a 2*3 Array of
a = mat(a)# Personal understanding : stay numpy Create an array instead of a tiled array
y = a.flatten()#y Equal to the value of expanding the array , Two brackets ( Array )
print('a Flattened y yes :',y)
y = a.flatten().A
print(y.dtype)
print(shape(y))# Print y Size
print(shape(y[0]))
y = a.flatten().A[0]
print(' Print y:',y)
'''
The output is :
a Flattened y yes : [[1 3 2 4 3 5]]
int32
(1, 6)
(6,)
Print y: [1 3 2 4 3 5]
'''边栏推荐
- Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 1. robots and mobile robots
- HCIP第十天笔记
- MS SQL Server 2019 learning
- requests-爬取页面源码数据
- C language advanced part VII. Program compilation and preprocessing
- Arduino在不同主频下稳定支持的TTL串口速率
- Hcip day 10 notes
- MySQL 啥时候用表锁,啥时候用行锁?
- Example of dictionary
- Generate API documents using swagger2markup
猜你喜欢

Starting from scratch C language intensive Part 3: Functions

生成模型与判别模型

Using bidirectional linked list to realize stack (c)

Anaconda install pytorch
![[cloud native] MySQL index analysis and query optimization](/img/ca/79783721637641cb8225bc26a8c4a9.png)
[cloud native] MySQL index analysis and query optimization

Facing Tencent (actual combat) - Test Development - detailed explanation of interns (face experience)

Debug No1 summarizes common solutions to bugs

C language file operation
![[hiflow] Tencent cloud hiflow scene connector realizes intelligent campus information management](/img/a9/7cdab9264902b1e2947a43463f6b32.png)
[hiflow] Tencent cloud hiflow scene connector realizes intelligent campus information management

About the solution of thinking that you download torch as a GPU version, but the result is really a CPU version
随机推荐
MySQL update uses case when to update the value of another field according to the value of one field
Anaconda install pytorch
Introduction to C language v First understanding pointer VI. first understanding structure
The difference between session and cookie
requests-爬虫实现一个简易网页采集器
Hcip 13th day notes
C language to achieve mine sweeping game
Error when using PIP: pip is configured with locations that requires tls/ssl
Li Kou, niuke.com - > linked list related topics (Article 1) (C language)
Use JMeter to analyze and test the lottery probability of the lottery interface
Starting from scratch C language intensive Part 3: Functions
Digital twin demonstration project -- Talking about simple pendulum (2) vision exploration and application scenarios
Advanced part of C language VI. file operation
Hcip day 10 notes
Digital twin demonstration project -- Talking about simple pendulum (4) IOT exploration
requests-爬虫多页爬取肯德基餐厅位置
Arduino 超级省电之休眠模式用1节18650电池工作17年
Using bidirectional linked list to realize stack (c)
Tools for data visualization
Flinksql UDF custom data source