当前位置:网站首页>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 nutrient analyzer 2022-2028: Research Report on technology, participants, trends, market size and share
- Change the background color of a pop-up dialog
- 微信小程序:微群人脉微信小程序源码下载全新社群系统优化版支持代理会员系统功能超高收益
- Take you ten days to easily complete the go micro service series (IX. link tracking)
- Lsblk command - check the disk of the system. I don't often use this command, but it's still very easy to use. Onion duck, like, collect, pay attention, wait for your arrival!
- Interesting practice of robot programming 14 robot 3D simulation (gazebo+turtlebot3)
- 增量备份 ?db full
- Five ways to query MySQL field comments!
- Exploration and practice of integration of streaming and wholesale in jd.com
- PHP Joseph Ring problem
猜你喜欢

MySQL regexp: Regular Expression Query

How to safely eat apples on the edge of a cliff? Deepmind & openai gives the answer of 3D security reinforcement learning
![[pure tone hearing test] pure tone hearing test system based on MATLAB](/img/1c/62ed6b3eb27a4dff976c4a2700a850.png)
[pure tone hearing test] pure tone hearing test system based on MATLAB

Basic operations of database and table ----- create index

phpstrom设置函数注释说明

流批一体在京东的探索与实践

MATLB | multi micro grid and distributed energy trading
![[swagger]-swagger learning](/img/60/1dbe074b3c66687867192b0817b553.jpg)
[swagger]-swagger learning

Interesting practice of robot programming 15- autoavoidobstacles

Lsblk command - check the disk of the system. I don't often use this command, but it's still very easy to use. Onion duck, like, collect, pay attention, wait for your arrival!
随机推荐
Redis master-slave replication cluster and recovery ideas for abnormal data loss # yyds dry goods inventory #
Yyds dry inventory jetpack hit dependency injection framework Getting Started Guide
微信小程序:全新独立后台月老办事处一元交友盲盒
Remote control service
微信小程序:星宿UI V1.5 wordpress系统资讯资源博客下载小程序微信QQ双端源码支持wordpress二级分类 加载动画优化
What sparks can applet container technology collide with IOT
batchnorm.py这个文件单GPU运行报错解决
Database postragesql lock management
Yyds dry goods inventory kubernetes management business configuration methods? (08)
[pure tone hearing test] pure tone hearing test system based on MATLAB
Roads and routes -- dfs+topsort+dijkstra+ mapping
Heartless sword English translation of Xi Murong's youth without complaint
Outlook: always prompt for user password
How to safely eat apples on the edge of a cliff? Deepmind & openai gives the answer of 3D security reinforcement learning
Kibana installation and configuration
Actual combat simulation │ JWT login authentication
PHP 基础篇 - PHP 中 DES 加解密详解
Outlook:总是提示输入用户密码
流批一體在京東的探索與實踐
phpstrom设置函数注释说明