当前位置:网站首页>Numpy library introductory tutorial: basic knowledge summary
Numpy library introductory tutorial: basic knowledge summary
2022-07-05 01:36:00 【Xiaobai learns vision】
numpy Can be said to be Python It is an important foundation for artificial intelligence and scientific computing , Recently, I just learned numpy,pandas,sklearn Wait a little Python Machine learning and scientific computing library , So here's a summary of common usage .
1 numpy Array creation
adopt array Way to create , towards array Pass in a list Realization
One dimensional array creation :
The creation of two-dimensional array : Pass in a nested list that will do , Here's an example :
adopt arange Create array : In the following example, create a 0~1 The interval is 0.1 The row vector , from 0 Start , barring 1, The second example generates a multi-dimensional array by aligning the broadcast .
adopt linspace Function to create an array : In the following example, create a 0~1 The interval is 1/9 The row vector ( Generate... In the form of an arithmetic sequence ), from 0 Start , Include 1.
adopt logspace Function to create an array : In the following example, create a 1~100, Yes 20 A row vector of elements ( Generate... In the form of an isometric sequence ), among 0 Express 10^0=1,2 Express 10^2=100, from 1 Start , Include 100
Generate a special form array :
Generate all 0 Array (zeros() function ), Generate all 1 Array (ones() function ), An array that allocates memory but does not initialize (empty() function ).
Pay attention to Specifies the size of the array ( Specify... With a tuple ), Also specify the type of element , Otherwise, an error will be reported
Generate random arrays
adopt frombuffer,fromstring,fromfile and fromfunction And so on Byte sequence 、 file And so on , In the following example, a 9*9 Multiplication table
2 Show 、 establish 、 Change the attributes of array elements 、 The size of the array, etc
3 Change the size of the array
reshape Method , The first example is to 43 The matrix is transformed into 34 matrix , The second example is to convert a row vector to a column vector . Pay attention to numpy in , When an axis is specified as -1 when , here numpy It will be automatically replaced according to the actual number of array elements -1 For specific size , As in the second case , We pointed out c There's only one column , and b Array has 12 Elements , therefore c Automatically designated as 12 That's ok 1 Columns of the matrix , That is, a 12 The column vector of dimension .
4 Element indexing and modification
Simple index form and slicing :
When using Boolean arrays b Access arrays as subscripts x When an element in , Will collect arrays x All in the array b The corresponding subscript in is True The elements of . Using Boolean arrays as subscripts does not share data space with the original array , Note that this approach only corresponds to Boolean array (array), Can't use Boolean list (list).( Note appended : When the length of the Boolean array is shorter than the length of the indexed array , The insufficient parts are regarded as False)
Index with conditions : Index using inequality, etc
Index and slice of multidimensional array ( The color in the right border corresponds to the color of the command on the left ):
alike , May adopt bool type Index and slice the array
In fact, the index of multidimensional array is still very easy to understand , For example, in the following example , We can see that for a tensor , That is to say b, The index is ,[i,j,k] Medium i Indicates the number of 2D arrays selected , then j Represents the vector of the first few rows in the two-dimensional array ,k Represents the number of elements in the row vector .
5 ufunc operation
ufunc yes universal function Abbreviation , It's a function that can operate on every element of an array .numPy Built in a lot of ufunc Functions are all in C Language level implementation , So they're very fast . Let's give a calculation sin function (sin Function calculates the of all elements in an array sin value ) Small example :
The four operators can be directly used in arrays ( One or more dimensions ) Calculation :
The comparison operation can also be carried out directly , as follows , Compare x1 and x2 The size of each corresponding element , Back to a bool Type of the array .
The available operators are ‘==’,‘!
=’,‘<’,‘>’,‘<=’,‘>=’ etc. . In addition, you can use the... Of the array any() or all() Method . As long as one of the values in the array is True, be any() return True; Only all elements of the array are True,all() To return to True.
Want to know more about numpy Self contained ufunc function , Check out this blog :
Customize ufunc function :frompyfunc(func,nin,nout) Function can convert a function that evaluates a single value into a function that evaluates each element in the array ufunc function . among nin It's input func The number of parameters ,nout yes func Number of returned values . Here's an example .
reduce Method ( And Python Of reduce Function similar to , Along the axis Shaft pair array To operate )
accumulate Method ( Its function and reduce The method is similar to , But the intermediate results will be saved )
outer Method ( Operate on the combination of every two pairs of elements of its two parameter arrays , Calculate the outer product ): If array a The dimension of is M, Array b The dimension of is N, be ufunc function op Of outer() Method pair a、b The array generated by array calculation c The dimension of is M+N,c The shape of is a、b A combination of shapes . for example a The shape of is (2,3),b The shape of is (4,5), be c The shape of is (2,3,4,5).
6 Broadcast operation
Broadcast is an operation taken for the operation of arrays with different shapes . When we use ufunc Function to evaluate two arrays ,ufunc The function evaluates the corresponding elements of the two arrays , Therefore, it requires that the two arrays have The same size (shape identical ). If two arrays of shape Different words ( The ranks vary in size ), The following broadcasts will be made (broadcasting) Handle :
1) Make all input arrays to among shape The longest array is the same ,shape The insufficient parts in the are all preceded by 1 A filling . Therefore, the output of the array shape Is the input array shape Maximum on each axis of ( Lean towards the maximum shaft length ).
2) If an axis of the input array is the same length as the corresponding axis of the output array, or its length is 1 when , This array can be used to calculate , Otherwise mistakes .
3) When you enter the value of an axis of the array The length is 1 when , All operations along this axis use the first set of values on this axis .
I don't feel very clear , So it's better to use examples .
7 Matrix operations
Matrix multiplication (dot Multiplication , Be careful to comply with the rules of matrix multiplication )
Inner product (inner, Calculate the vector / Matrix inner product ): and dot The product is the same , For two one-dimensional arrays , It calculates the product sum of the subscript elements of the two arrays ; For multidimensional arrays a and b, It calculates that each element in the result array is an array a and b The inner product of the last dimension of , So the array a and b The length of the last dimension of must be the same .
The formula is :
inner(a, b)[i,j,k,m] = sum(a[i,j,:]*b[k,m,:])
Exoproduct (outer, Calculate the outer product ): Calculate only according to one-dimensional array , If the passed in parameter is a multidimensional array , Then flatten the array into a one-dimensional array before operation .outer The matrix product of column vector and row vector calculated by product .
Solve a system of linear equations (solve):solve(a,b) There are two parameters a and b.a It's a N*N Two dimensional array of , and b Is a length of N One dimensional array of ,solve The function finds a length of N One dimensional array of x, bring a and x The matrix product of is exactly equal to b, Array x Is the solution of a system of multivariate first-order equations .
8 File access
a.tofile(file_name) , preservation a To file_name In file ,file_name Is a string type , Such as ‘a.txt’ etc. ; Read back from the file a Array needs to specify the type , Such as :b=np.fromfile(file_name,dtype=np.float)
When an error , The right way to use it is :
b=np.fromfile(file_name,dtype=np.int32)
save and load Method ( Neither writing to nor reading back from a file needs to specify the type , The storage file type is npy Format file ):
np.save(“a.npy”, a) # take array a Deposit in a.npy In file c = np.load( “a.npy” ) # from a.npy Read back... In the file array a
savetxt and loadtxt Method ( Save as txt Format file ):
np.savetxt(“a.txt”, a) # take array a Deposit in a.txt In file np.loadtxt(“a.txt”) # from a.txt Read back... In the file array a
- END -
边栏推荐
- Global and Chinese market of veterinary thermometers 2022-2028: Research Report on technology, participants, trends, market size and share
- Redis master-slave replication cluster and recovery ideas for abnormal data loss # yyds dry goods inventory #
- Using openpyxl module to write the binary list into excel file
- Research Report on the overall scale, major producers, major regions, products and application segmentation of agricultural automatic steering system in the global market in 2022
- Express routing, express middleware, using express write interface
- Arbitrum: two-dimensional cost
- Game 280 of leetcode week
- [wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
- Are you still writing the TS type code
- 实战模拟│JWT 登录认证
猜你喜欢
Express routing, express middleware, using express write interface
MySQL REGEXP:正则表达式查询
After reading the average code written by Microsoft God, I realized that I was still too young
Great God developed the new H5 version of arXiv, saying goodbye to formula typography errors in one step, and mobile phones can also easily read literature
[OpenGL learning notes 8] texture
小程序容器技术与物联网 IoT 可以碰撞出什么样的火花
Introduction to redis (1)
Remote control service
Basic operations of database and table ----- delete index
Phpstrom setting function annotation description
随机推荐
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
batchnorm.py这个文件单GPU运行报错解决
Logstash、Fluentd、Fluent Bit、Vector? How to choose the appropriate open source log collector
Database postragesql client connection default
MATLB | multi micro grid and distributed energy trading
PHP Joseph Ring problem
How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
微信小程序:全网独家小程序版本独立微信社群人脉
When the industrial Internet era is truly developed and improved, it will witness the birth of giants in every scene
Global and Chinese market of nutrient analyzer 2022-2028: Research Report on technology, participants, trends, market size and share
微信小程序:独立后台带分销功能月老办事处交友盲盒
Classification of performance tests (learning summary)
Redis(1)之Redis简介
phpstrom设置函数注释说明
Outlook:总是提示输入用户密码
Using openpyxl module to write the binary list into excel file
Win:使用组策略启用和禁用 USB 驱动器
【纯音听力测试】基于MATLAB的纯音听力测试系统
Interesting practice of robot programming 16 synchronous positioning and map building (SLAM)
無心劍英譯席慕容《無怨的青春》