Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the numpy module of python and how to use it

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you what the numpy module of python is and how to use the relevant knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.

Numpy is the abbreviation of Numerical Python extensions, which literally means the extension of Python numerical calculation. Numpy is the dependence of many machine learning libraries in python, which realize the basic matrix calculation through Numpy.

Numpy not only supports high-order, massive matrix and vector computation, but also provides a wealth of functions. In addition, Numpy is based on a more modern programming language-python,python, which is popular in the technical circle because of its open source, free, flexible, easy to learn and good engineering characteristics, and has become the mainstream programming language in the fields of machine learning and data analysis.

I. array type

The array type of numpy is a basic data type of the library. This data type literally means array, which means that its most critical attributes are elements and dimensions. We can use this data type to implement multidimensional arrays.

Therefore, with this data type, we can use one-dimensional arrays to represent vectors, two-dimensional arrays to represent matrices, and so on to represent tensors of higher dimensions.

The basics of 1.1array types use import numpy as np# to create an array type named array through the np.array () method The parameter is a listarray = np.array ([1,2,3,4]) print (array) # the result is: [1234] # get the maximum value of the element in array print (array.max ()) # the result is: "get the minimum value of the element in array print (array.min ()) # result: get the average value of the element in array print (array.mean ()) # result: 2." directly multiply array by 2 Python multiplies each element by 2print (array*2) # the result is: [2468] print (array+1) # the result is: [2345] print (array/2) # the result is: [0.51.1.52.] # divide each element by 2 The result of floating-point representation print (array% 2) # is: [1 0] array_1 = np.array ([1, 0, 2, 0]) # get the first index of the data with the largest element value in this set of data, and the subscript starts with 0 and print (array_1.argmax ()) # results: 2

From the above code, we can learn the basic usage of the array type in Numpy.

We can see that array is actually a class, which is instantiated as an object by passing in a list parameter, thus realizing the encapsulation of the data.

Import numpy as np# creates a two-dimensional array representing a matrix of 3 rows and 2 columns array = np.array ([[1, 2], [3, 4], [5, 6]]) print (array) # View the dimensional properties of the data, and output the result (3) 2) represents 3 rows and 2 columns of print (array.shape) # the result is: (3) 2) # View the number of elements print (array.size) # the result is: "check the index print (array.argmax ()) of the maximum value of the element. The result is:" convert the array with shape to (3p2) into one line to represent print (array.flatten ()) # the result is: [1 2 3 4 5 6] # We can see The flatten () method is the process of "flattening" multidimensional data into an one-dimensional array # changing the array data from the form of shape to (3) to the form of (2) print (array.reshape (2)). The result is: [[1 23] [4 56]]'# change the array data from the form of shape to (3) to (1) 6) the form print (array.reshape (1,6)) # results as follows: [[1 2 3 4 5 6]]

The more advanced functions are flatten () and reshape (). It is important to note that the result returned by reshape () is of type array.

1.3Numpy creates a special type of array type 1.3.1 generates all zeros or all 1s arrayimport numpy as np# generates all elements array_zeros = np.zeros ((2,3,3)) print (array_zeros)'', the result is: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]''array_ones = np.ones ((2, 3, 3) print (array_ones)' 'result is: [1. 1. 1.] [1. 1. 1.] [1. 1.] [1. 1.] [1. 1.] [1. 1.]' 'print (array_ones.shape) # result is: (2, 3, 3)

Note: if you change (2, 3, 3) to (3, 3)

Array_zeros = np.zeros ((3,3)) print (array_zeros)''result is: [0. 0. 0.] [0. 0. 0.] [0. 0. 0.]''

It generates three rows and three columns of array

1.3.2np.arrange () and np.linspace ()

Arange ([start,] stop [, step,], dtype=None, like=None)

Returns the value of a uniform distribution over a given interval. The value is generated within the half-open interval ``[start, stop) `(in other words, the interval that includes `start` but not `stop`). For integer parameters, this function is equivalent to the Python built-in `range` function, but returns ndarray instead of a list. When a non-integer step is used (for example, 0.1), the results are usually inconsistent. For these cases, it is best to use `numpy.linspace`.

Linspace (start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Returns evenly distributed numbers within the specified time interval. Return "num" a uniformly distributed sample and calculate it on the interval [`start`, `stop`].

Start: the starting value of the sequence.

Stop: the end value of the sequence, unless `endpoint` is set to False. In this case, the sequence consists of all samples except the last "num + 1" uniformly distributed sample, so "stop" is excluded. Note that when `endpoint` is False, the step size will change.

Num=50: the number of samples to generate. The default value is 50. Must be a nonnegative number.

Endpoint=True: if true, `stop` is the last sample. Otherwise, it is not included. The default is true.

Retstep=False: if True, (`samples`, `step`) is returned, where `step` is the spacing between samples.

Dtype=None: the type of output array. If `dtype` is not given, the data type is inferred from `start` and `stop`. The inferred dtype will never be an integer; `float` is selected even if the parameter produces an array of integers.

So the following code is easy to understand

# generate an array, incrementing from 0 to 10, step size 1array_arange = np.arange (10) print (array_arange) # result: [0 1 2 3 4 5 6 7 8 9] # generate an array, increase from 0 to 10, step size 2array_arange_1 = np.arange (0,10,2) print (array_arange_1) # result: [0 24 68] # generate an array 0-10 is divided into five parts: array_linspace = np.linspace (0,10,5) print (array_linspace) # the result is: [0. 2.55. 7.5 10.] 1.4Numpy basic calculation demonstrates that import numpy as np# takes the absolute value print (np.abs ([1,-2, 3) ) # [1 234] # find the sine print (np.sin (np.pi/2)) # 1. Find the inverse tangent print (np.arctan (1)) # 0.785398163397448 find e to the second power of print (np.exp (2)) # 7.3890560989306) to the cubic print (np.power (2,3)) # find the vector [1m 2] and the dot product print (np.dot ([1m 2)], [3] Print (np.sqrt (4)) # 2.Sum print (np.sum ([1,2,3,4])) # 1 calculate the average print (np.mean ([1,2,3,4])) # 2.5 # calculate the standard deviation print (np.std ([1,2,3,4])) # 1.118033988749895, Linear Algebra correlation

Earlier, we learned about array types and their basic operations, and that array types can represent vectors, matrices, and multidimensional tensors.

Linear algebraic computing is very important in the field of scientific computing, so let's learn about the linear algebraic operations provided by Numpy below.

Import numpy as npvector_a = np.array ([1,2,3]) vector_b = np.array ([2,3,4]) # define two input vectors vector_a and vector_bm = np.dot (vector_a, vector_b) # multiply the two vectors, that is, dot multiplication, the result is 20print (m) n = vector_a.dot (vector_b) print (n) # multiplies vector_a and vector_b The result is 20o = np.dot (vector_a, vector_b.T) print (o)''. The result of multiplying a row vector by a column vector is equivalent to the dot product of two row vectors. Here the dot () method is tested. Where the T () method of type array represents transpose. The test results show that the dot () method calculates the dot product of the two vectors by default. For matrices that conform to the cross-multiplication format, multiply and multiply automatically.'' # Let's take a look at the following example: matrix_a = np.array ([[1,2], [3,4]]) # define a square matrix matrix_b = np.dot (matrix_a, matrix_a.T) with two rows and two columns. Here we multiply the square matrix with its transpose, and assign the result to the matrix_b variable print (matrix_b)''. The result is: array ([[5j11], [11]). 25]])''p = np.linalg.norm ([1,2]) print (p) # finds the value of the norm of a vector, and the result is 2.236067977499789. If the norm () method does not specify the second parameter, then the default is to find 2 norm np.linalg.norm ([1,-2], 1) # specify the second parameter value as 1, that is, 1 norm. As we mentioned earlier, the result of 1 norm is the sum of the absolute values of each element in the vector, and the result is 3.0Q = np.linalg.norm ([1,2,3,4], np. Inf) print (Q) # find the infinite norm of the vector, where np.inf represents positive infinity, that is, the one with the largest element value in the vector. The result is 4.0r = np.linalg. Norm ([1,2,3,4],-np.inf) print (r) # similarly, the result of finding the negative infinite norm is 1, that is, the minimum value of the element in the vector, s = np.linalg.det (matrix_a) print (s) #-2.00000000000004t = np.trace (matrix_a) print (t) # find the trace of the matrix matrix_a The result is 5u = np.linalg.matrix_rank (matrix_a) # to find the rank of the matrix, and the result is that 2print (u) v = vector_a * vector_b# uses the sign * to multiply the two vectors Is to multiply the elements in the two vectors separately, that is, the Hadamard product print (v) # [2612] w = vector_a * * vector_bprint (w) # uses the binary operator * * to operate on the two vectors, and the result is array ([1,8,81], dtype = int32) # indicates that the vector vector. The elements in a correspond to vector. The element values in b are exponentiated. For example, the final result can be expressed as [1, 1, 2, 2, 3, 3, 3] # finding the inverse matrix z = np.linalg.inv (matrix_a) print (z)'[- 2. 1.] [1.5-0.5] 3. The high-level function of the matrix-random number matrix

In addition to providing us with conventional mathematical calculation functions and matrix-related operations, Numpy also provides many functional modules, of which the random number module is one of them.

The random number module can be used to generate random number matrix, which is more powerful than the random number module of python.

Import numpy as np# sets the random number seed np.random.seed () # to generate an integer random number from [1p3), and to generate 10 a = np.random.randint (1mem3,10) print (a) # [1 1 1 2 1 1 1 12 2] # if you want to continuously generate floating point numbers between [1p3}. You can use the following method: # ① b = 2*np.random.random (10) + 1print (b)''[2.88458839 2.07004167 2.80814156 1.83247535 2.33649809 2.62763357 2.0549351 2.33464915 1.70562208 2.66257726]'# ② c = np.random.uniform (1,3) 10) print (c)'[1.76967412 1.37703868 2.48838004 1.45986254 2.04487418 2.51107658 1.25673115 1.31416097 2.56218317 2.90575438] generates a matrix that satisfies normal distribution (Gaussian distribution) and its dimension is 4x 4d = np. Random.normal (size= (4,4)) print (d)''[[0.76164366 0.11588368 0.49221559-0.28222691] [0.47638143-0.21197541-1.0776362 0.49241666] [0.26038756-0.20406522 1.11210954-1.191425] [0.58255677 1.84047863-0.21366512-0.85425828]]''# randomly produces 10 binomial distribution data: e = np.random.binomial (nasty 5, pendant 0.5) Size=10) print (e) # [1 1 5 2 1 2 1 1 2 12] # produces a sequence from 0 to 9 data = np.arange (10) print (data) # [0 1 2 3 4 5 6 7 8 9] # five samples are randomly collected from data data In the process of collection, f = np.random.choice (data, 5) print (f) # [17334] # randomly collected 5 samples from data data, and g = np.random.choice (data, 5, replace=False) print (g) # [8 9 150] # disordered data h = np.random.permutation (data) print (h) # [8 53 9 20 0 6 17] # disordered data And replace it with the new datanp.random.shuffle (data) print (data) # [9 7 03 8 5 2 1 46] above is all the content of this article "what is the numpy module of python and how to use it". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 229

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report