[Reprint] python3 numpy function _Python numpy summary (3)-common function usage

Reference link: numpy.empty_like in Python

For knowledge of Python Numpy matrix, please refer to the blog post: Python numpy learning (2)-matrix usage

 1 , np.ceil (x, y)

 Limit the range of elements, and round up.

 x represents the input data y float type represents the upper limit of each element.

 a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])

 np.ceil (a)

 # array([-1., -1., -0., 1., 2., 2., 2.])

 2,np.random.permutation(x)

 Randomly generate a permutation or return a range. If x is a multi-dimensional array, it will only be shuffled along its first index.

 import numpy as np

 shuffle_index = np.random.permutation(60000)

 X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]

 The difference between the usage of function np.random.permutation and np.random.shuffle

 The functions shuffle and permutation both reshuffle the original array (that is, randomly shuffle the original element order); the difference is that shuffle operates directly on the original array, changing the order of the original array, and has no return value. And permutation does not directly operate on the original array, but returns a new shuffled array without changing the original array.

 Example:

 a = np.arange(12)

 print('origin a ',a)

 np.random.shuffle(a)

 print('shuffle a ',a)

 print('\n')

 a = np.arange(12)

 print('origin a ',a)

 b = np.random.permutation(a)

 print('permutation b ',b)

 print('deal with a ',a)

 '''

 origin a [ 0 1 2 3 4 5 6 7 8 9 10 11]

 shuffle a [ 5 8 2 10 7 3 0 11 6 9 4 1]

 origin a [ 0 1 2 3 4 5 6 7 8 9 10 11]

 permutation b [ 1 10 2 11 3 7 4 0 8 9 5 6]

 deal with a [ 0 1 2 3 4 5 6 7 8 9 10 11]

 '''

 3 , e.g. armax ()

 Returns the index of the maximum value along the axis.

 a: array_like; input array

 axis: int, optional; By default, the index is placed in a flat array, otherwise along the specified axis.

 out: array, optional; If provided, the result will be inserted into this array. It should be of proper shape and dtype.

 # some_digit_scores content

 # array([[-311402.62954431, -363517.28355739, -446449.5306454 ,

 # -183226.61023518, -414337.15339485, 161855.74572176,

 # -452576.39616343, -471957.14962573, -518542.33997148,

 # -536774.63961222]])

 np.argmax(some_digit_scores)

 # Out

 # 5

 4. How to use np.dot()

 (This function reference: https://blog.csdn.net/skywalker1996/article/details/82462499)

 The np.dot() function has two main functions, vector dot product and matrix matrix multiplication. Here are the three most commonly used cases.

 4.1 np.dot(a, b), where a, b are one-dimensional vectors (a and b are np.ndarray types), and what is done at this time is vector dot product

 import numpy as np

 a = np.array([1, 2, 3, 4, 5])

 b = np.array([6, 7, 8, 9, 10])

 print(np.dot(a, b)) # 130

 # 1*6 + 2*7 + 3*8 + 4*9 + 5*10

 4.2 np.dot(a, b), where a is a two-dimensional matrix and b is a one-dimensional vector, where b will be calculated as a one-dimensional matrix

 the shape of a is (5, 5)

 the shape of b is (5,)

 [73 97 84 95 49]

 the shape of np.dot(a,b) is (5,)

 [[1 3 3 3 9]

 [1 4 8 6 8]

 [0 1 7 9 5]

 [9 8 4 7 6]

 [3 1 1 4 5]]

 What needs to be noted here is the difference between a one-dimensional matrix and a one-dimensional vector. The shape of a one-dimensional vector is (5, ), and the shape of a one-dimensional matrix is ​​(5, 1). If the two parameters a and b are both one The dimensional vector is the calculated dot product, but when one of them is a matrix (including one-dimensional matrix), dot will perform matrix multiplication, and if one of the parameters is a vector, it will automatically be converted to a one-dimensional matrix for calculation.

 4.3 np.dot(a, b), where a and b are two-dimensional matrices, at this time dot is the matrix multiplication operation

 import numpy as np

 a = np.random.randint(0, 10, size=(5, 5))

 b = np.random.randint(0, 10, size=(5, 3))

 print("the shape of a is " + str(a.shape))

 print("the shape of b is " + str(b.shape))

 print(np.dot(a, b))

 '''

 the shape of a is (5, 5)

 the shape of b is (5, 3)

 [[120 162 56]

 [ 85 106 80]

 [146 99 94]

 [ 88 90 70]

 [130 87 80]]

 '''

 5,np.linalg.inv()

 Calculate the inverse of the matrix

 a: (..., M, M) array_like; the matrix to be inverted

 X_b = np.c_[np.ones((100, 1)), X] # add x0 = 1 to each instance

 theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)

 6,np.ndarray.T()

 Calculate the transpose of the matrix, if self.ndim <2 then return itself.

 >>> x = np.array([[1.,2.],[3.,4.]])

 >>> x

 array([[ 1., 2.],

 [ 3., 4.]])

 >>> x.T

 array([[ 1., 3.],

 [ 2., 4.]])

 >>> x = np.array([1.,2.,3.,4.])

 >>> x

 array([ 1., 2., 3., 4.])

 >>> x.T

 array([ 1., 2., 3., 4.])

 7. Numpy adds and deletes a dimension with a value of 1

 (Reference address: https://www.jianshu.com/p/d1543cfaf737)

 7.1 Add a dimension of 1 to 2-d Array(H, W) called 3-d Array(H,W,1)

 Color images are stored as (H, W, C) shape (channel-last) 3-d Array in numpy; grayscale images are stored as (H, W) shape 2-d Array, which often needs to be added A dimension with a value of 1 becomes a 3-d Array(H, W, 1).

 import numpy as np

 in:

 a = np.ones((3,3))

 print(a.shape)

 b1 = np.expand_dims(a,2)

 print(b1.shape)

 out:

 (2, 2)

 (2, 2, 1)

 note:

 b2 = np.expand_dims(a, 0) # (1, 2, 2)

 b3 = np.expand_dims(a, 1) # (2, 2, 1)

 7.2 Delete the dimension with value 1 in dd Array

 When displaying and saving the image matrix, it is often necessary to delete the dimension with a value of 1:

 in:

 a = np.ones((2,2,1))

 print(a.shape)

 b = np.squeeze(a)

 print(b.shape)

 out:

 (2, 2, 1)

 (2, 2)

 8, np.random.normal() function

 np.random.normal() means a normal distribution, and normal here means normal. Here is an example:

 random.normal(loc=0.5, scale=1e-2, size=shape)

 explain:

 1. Parameter loc(float): the mean value of the normal distribution, corresponding to the center of this distribution. loc=0 indicates that this is a normal distribution with the Y axis as the axis of symmetry.

 2. Parameter scale (float): the standard deviation of the normal distribution, corresponding to the width of the distribution, the larger the scale, the shorter the curve of the normal distribution, the smaller the scale, the thinner the curve.

 3. Parameter size (int or integer tuple): The output value is assigned to shape, and the default is None.

 9. Basic usage of np.linspace function

 Return evenly spaced samples in the specified interval [start, stop]

 start: scalar; the starting value of the sequence

 stop: scalar; the end value of the sequence

 num: int, optional; the number of samples to be generated, the default is 50.

 endpoint: bool, optional; if it is True, the end value is included, otherwise the end value is not included, that is, the [start, stop) interval. The default is True.

 dtype: dtype, optional; the type of the output array, if not given, the type is inferred from the input data.

 X_new=np.linspace(-3, 3, 100).reshape(100, 1)

 X_new_poly = poly_features.transform(X_new)

 y_new = lin_reg.predict(X_new_poly)

 plt.plot(X, y, "b.")

 plt.plot(X_new, y_new, "r-", linewidth=2, label="Predictions")

 plt.xlabel("$x_1$", fontsize=18)

 plt.ylabel("$y$", rotation=0, fontsize=18)

 plt.legend(loc="upper left", fontsize=14)

 plt.axis ([- 3, 3, 0, 10])

 save_fig("quadratic_predictions_plot")

 plt.show()

 10. Basic usage of Meshgrid function

 Returns the coordinate matrix from the coordinate vector.

 Understanding: The meshgrid function uses points on two coordinate axes to draw a grid on a plane. Simply put, the function of meshgrid is suitable for generating grid data. It can accept two one-dimensional arrays to generate two two-dimensional matrices, corresponding to all (x, y) pairs in the two arrays

 Commonly used scenes of Meshgrid function include contour drawing and SVC hyperplane drawing in machine learning.

 x1, x2,..., xn: array_like; a one-dimensional array representing grid coordinates.

 indexing: {'xy','ij'}, optional; output Cartesian ('xy', default) or matrix ('ij') index.

 sparse: bool, optional; if True, return a sparse matrix to reduce memory, the default is False.

 >>> nx, ny = (3, 2)

 >>> x = np.linspace(0, 1, nx)

 >>> y = np.linspace(0, 1, ny)

 >>> xv, yv = np.meshgrid(x, y)

 >>> xv

 array([[ 0. , 0.5, 1. ],

 [ 0. , 0.5, 1. ]])

 >>> yv

 array([[ 0., 0., 0.],

 [ 1., 1., 1.]])

 >>> xv, yv = np.meshgrid(x, y, sparse=True) # make sparse output arrays

 >>> xv

 array([[ 0. , 0.5, 1. ]])

 >>> yv

 array([[ 0.],

 [ 1.]])

 11,norm()

 Matrix or vector norm

 x: array_like; the input array, if axis is None, x must be 1-D or 2-D.

 ord: {non-zero int, inf, -inf,'fro','nuc'}, optional; the order of the norm, inf represents the numpy inf object.

 axis : {int, 2-tuple of ints, None}, optional

 keepdims : bool, optional

 t1a, t1b, t2a, t2b = -1, 3, -1.5, 1.5

 # ignoring bias term

 t1s = e.g. linspace (t1a, t1b, 500)

 t2s = e.g. linspace (t2a, t2b, 500)

 t1, t2 = e.g. meshgrid (t1s, t2s)

 T = np.c_[t1.ravel(), t2.ravel()]

 Xr = np.array([[-1, 1], [-0.3, -1], [1, 0.1]])

 yr = 2 * Xr[:, :1] + 0.5 * Xr[:, 1:]

 J = (1/len(Xr) * np.sum((T.dot(Xr.T) - yr.T)**2, axis=1)).reshape(t1.shape)

 N1 = np.linalg.norm(T, ord=1, axis=1).reshape(t1.shape)

 N2 = np.linalg.norm(T, ord=2, axis=1).reshape(t1.shape)

 t_min_idx = np.unravel_index(np.argmin(J), J.shape)

 t1_min, t2_min = t1[t_min_idx], t2[t_min_idx]

 t_init = np.array([[0.25], [-1]])

 12,unravel_index()

 Convert plane index or plane index array to tuple of coordinate array

 indices: array_like; an integer array whose elements are indexed into a flat version of the dims array.

 dims: tuple of ints; the shape of the array used to decompose the index.

 order: {'C','F'}, optional; determines that the indicators should be in row-major (C-style) or column-major (Fortran-style) order.

 >>> np.unravel_index([22, 41, 37], (7,6))

 (array([3, 6, 6]), array([4, 5, 1]))

 >>> np.unravel_index([31, 41, 13], (7,6), order='F')

 (array([3, 6, 6]), array([4, 5, 1]))

 >>> np.unravel_index(1621, (6,7,8,9))

 (3, 1, 4, 1)

 13,mean()

 Calculate the arithmetic average along the specified axis

 a: array_like; contains the array that requires the average value, if it is not an array, try to convert.

 axis: None or int or tuple of ints, optional; the axis for calculating the average value, the flat array is calculated by default.

 dtype: data-type, optional; the type used to calculate the average value.

 out : ndarray, optional

 >>> a = np.array([[1, 2], [3, 4]])

 >>> np.mean(a)

 2.5

 >>> np.mean(a, axis=0)

 array([ 2., 3.])

 >>> np.mean(a, axis=1)

 array([ 1.5, 3.5])

 >>> a = np.zeros((2, 512*512), dtype=np.float32)

 >>> a[0, :] = 1.0

 >>> a[1, :] = 0.1

 >>> np.mean(a)

 0.54999924

 14. Basic usage of ravel() function

 def ravel(self, order=None): # real signature unknown; restored from __doc__

 """

 a.ravel([order])

 Return a flattened array.

 Refer to `numpy.ravel` for full documentation.

 See Also

 --------

 numpy.ravel : equivalent function

 ndarray.flat : a flat iterator on the array.

 """

 Convert a multi-array into a one-dimensional array

 import numpy as np

 x = np.array([[1, 2], [3,4]])

 # The ravel function defaults to row order first when reducing dimensionality

 res = x.ravel()

 print(x)

 print('**************')

 print(res)

 '''

 [[1 2]

 [3 4]]

 **************

 [1 2 3 4]

 '''

 15. Usage of np.c_ and np.r_ functions in numpy

 np.r_ connects two matrices according to rows, that is, adds the two matrices up and down, requiring the same number of columns, similar to the concat() function in pandas.

 np.c_ is to connect two matrices according to the columns, that is, to add the two matrices to the left and right, the number of rows is required to be equal, similar to the merge() function in pandas.

 for example:

 import numpy as np

 a = np.array([1, 2, 3])

 b = np.array([4, 5, 6])

 c = np.c_[a,b]

 print(np.r_[a,b])

 print('*********')

 print(np.c_[a,b])

 print('*********')

 print(np.c_[c,a])

 print('*********')

 '''

 [1 2 3 4 5 6]

 *********

 [[1 4]

 [2 5]

 [3 6]]

 *********

 [[1 4 1]

 [2 5 2]

 [3 6 3]]

 *********

 '''

 16, np.rollaxis and swapaxes functions

 (The understanding of this function comes from: https://blog.csdn.net/liaoyuecai/article/details/80193996)

 Before understanding these two functions, we must first understand the axis of the numpy array.

 The axis is the symbol of the dimensions in the array. It is too abstract to explain in terms of dimensions. We can illustrate it with an example.

 Suppose I have a student score sheet, the scores are arranged by seat, the score sheet is as follows:

 

 Then the horizontal axis of this table is the row, and the vertical axis is the column. We can calculate the average or highest score of that row or column, which is to specify the axis for calculation. We treat the table as a two-dimensional array and add the array The subscript becomes the following table: [78,34,87,25,83],[25,67,97,22,13],[78,43,87,45,89]]

 

 Run the code to find the maximum value:

 import numpy as np

 a = np.array([[78, 34, 87, 25, 83], [25, 67, 97, 22, 13], [78, 43, 87, 45, 89]])

 print(a.max(axis=0))

 print(a.max(axis=1))

 '''

 [78 67 97 45 89]

 [87 97 89]

 '''

 From here we can see that axis=1 is the data of the vertical axis, the first line prints the maximum value of each column, and axis=1 is the data of the horizontal axis.

 Let’s look at a 2*2 three-dimensional array: [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]

 

 Run the code to find the maximum value:

 import numpy as np

 a = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])

 print(a)

 print('**************************')

 print(a.max(axis=0))

 print('*************************')

 print(a.max(axis=1))

 print('**************************')

 print(a.max(axis=2))

 '''

 [[[0 1]

 [2 3]]

 [[4 5]

 [6 7]]]

 **************************

 [[4 5]

 [6 7]]

 *************************

 [[2 3]

 [6 7]]

 **************************

 [[1 3]

 [5 7]]

 '''

 The maximum value here is to treat a one-dimensional array as an element. When the axis is 0 and 1, it is the same as the two-dimensional array.

 Focus on axis=2. At this time, in order to match the third subscript of the array as a group, the contents of the one-dimensional array have changed:

 

 It can be seen that the axis of the multidimensional array is related to the array subscript. Now you can learn the rollaxis function, which has three parameters:

 numpy.rollaxis(arr, axis, start)

 arr: input array

 axis: the axis to be scrolled backward, the relative position of other axes will not change

 start: The default is zero, which means complete scrolling. Will scroll to a specific position

 code show as below:

 import numpy as np

 a = np.arange(8).reshape(2, 2, 2)

 print('Original array:')

 print(a)

 print('\n')

 # Scroll axis 2 to axis 0 (width to depth)

 print('Call the rollaxis function:')

 print(np.rollaxis(a, 2))

 # Scroll axis 0 to axis 1: (width to height)

 print('\n')

 print('Call the rollaxis function:')

 print(np.rollaxis(a, 2, 1))

 '''

 Original array:

 [[[0 1]

 [2 3]]

 [[4 5]

 [6 7]]]

 Call the rollaxis function:

 [[[0 2]

 [4 6]]

 [[1 3]

 [5 7]]]

 Call the rollaxis function:

 [[[0 2]

 [1 3]]

 '''

 When the program runs np.rollaxis(a, 2), the axis 2 is rolled to the front of axis 0, and the position of the other axes relative to axis 2 remains unchanged (start defaults to 0), and the array index order changes from 0, 1, 2 to 1, 2, 0

 At this time, the array is reorganized in the order of subscripts. For example, the subscript of [0, 1] in the first array is [000, 001], where the subscript of 0 does not affect the value, and the subscript of position 1 changes from 001 to 010. The first subscript is scrolled to the last subscript and the value is changed from 1 (001) to 2 (010):

 

 It can be concluded that the scrolling of the axis is the scrolling of the subscript. Similarly, when running np.rollaxis(a, 2, 1), the subscript 0,1,2 becomes 0,2.

 The numpy.swapaxes(arr, axis1, axis2) function is swap, which swaps axis1 and axis2.

 17, np.where() function

 The function is as follows:

 where(condition, x=None, y=None)

 Return element, which can be x or y. It depends on the condition. Simply put, if the condition is satisfied, the output x is not satisfied and the output y is not satisfied.

 If only conditions are given, return condition.nonzero()

 For different inputs, the value returned by where is different. We see example

 >>> aa = np.arange(10)

 >>> np.where(aa,1,-1)

 array([-1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # 0 is False, so the first output is -1

 >>> np.where(aa > 5,1,-1)

 array([-1, -1, -1, -1, -1, -1, 1, 1, 1, 1])

 >>> np.where([[True,False], [True,True]], # Examples on the official website

 [[1,2], [3,4]],

 [[9,8], [7,6]])

 array([[1, 8],

 [3, 4]])

 The condition of the above example is [[True, False], [True, False]], which correspond to the four values ​​of the final output result. The first value is selected from [1, 9]. Because the condition is True, it is selected 1. The second value is selected from [2, 8], because the condition is False, so select 8, and so on, you can see another example for similar problems:

 >>> a = 10

 >>> np.where([[a > 5,a < 5], [a == 10,a == 7]],

 [["chosen","not chosen"], ["chosen","not chosen"]],

 [["not chosen","chosen"], ["not chosen","chosen"]])

 array([['chosen', 'chosen'],

 ['chosen', 'chosen']], dtype='

 Only condition (condition), without x and y, output the coordinates (equivalent to numpy.nonzero) of the element that meets the condition (ie, non-zero). The coordinates here are given in the form of tuples. Usually, how many dimensions the original array has, the output tuple contains several arrays, which correspond to the coordinates of each dimension of the eligible elements.

 >>> a = np.array([2,4,6,8,10])

 >>> np.where(a> 5)# Return to index

 (array([2, 3, 4]),)

 >>> a[np.where(a> 5)] # equivalent to a[a>5]

 array([ 6, 8, 10])

 >>> np.where([[0, 1], [1, 0]])

 (array([0, 1]), array([1, 0]))

 In the above example condition, the truth values ​​of [[0, 1], [1, 0]] are two ones, each with the first dimension coordinates [0, 1] and the second dimension coordinates [1, 0].

 Let's look at a more complicated example:

 >>> a = np.arange(27).reshape(3,3,3)

 >>> a

 array([[[ 0, 1, 2],

 [ 3, 4, 5],

 [ 6, 7, 8]],

 [[ 9, 10, 11],

 [12, 13, 14],

 [15, 16, 17]],

 [[18, 19, 20],

 [21, 22, 23],

 [24, 25, 26]]])

 >>> np.where(a > 5)

 (array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2]),

 array([2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2]),

 array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]))

 # Eligible elements are

 [ 6, 7, 8]],

 [[ 9, 10, 11],

 [12, 13, 14],

 [15, 16, 17]],

 [[18, 19, 20],

 [21, 22, 23],

 [24, 25, 26]]]

 So np.where will output the corresponding coordinates of each element. Because the original array has three dimensions, there are three arrays in the tuple.

 18. np.diff() function

 The np.diff() function is the result of a[n]-a[n-1] in the array

 import numpy as np

 a = np.array([1, 3, 5, 7, 9])

 diff_a = np.diff(a)

 print(diff_a)

 # [2 2 2 2]

 This function is also suitable for high-dimensional arrays.

 19, np.empty() function

 The np.empty() function returns a matrix of random elements whose size is defined by the parameters. So be careful when using it, you need to redefine each value manually, otherwise the value is a random number, which is troublesome to debug.

 def empty(shape, dtype=None, order='C'): # real signature unknown; restored from __doc__

 """

 empty(shape, dtype=float, order='C')

 Return a new array of given shape and type, without initializing entries.

 Parameters

 ----------

 shape : int or tuple of int

 Shape of the empty array, e.g., ``(2, 3)`` or ``2``.

 dtype : data-type, optional

 Desired output data-type for the array, e.g, `numpy.int8`. Default is

 `numpy.float64`.

 order : {'C', 'F'}, optional, default: 'C'

 Whether to store multi-dimensional data in row-major

 (C-style) or column-major (Fortran-style) order in

 memory.

 Returns

 -------

 out : ndarray

 Array of uninitialized (arbitrary) data of the given shape, dtype, and

 order. Object arrays will be initialized to None.

 See Also

 --------

 empty_like : Return an empty array with shape and type of input.

 ones : Return a new array setting values to one.

 zeros : Return a new array setting values to zero.

 full : Return a new array of given shape filled with value.

 Notes

 -----

 `empty`, unlike `zeros`, does not set the array values to zero,

 and may therefore be marginally faster. On the other hand, it requires

 the user to manually set all the values in the array, and should be

 used with caution.

 Examples

 --------

 >>> np.empty([2, 2])

 array([[ -9.74499359e+001, 6.69583040e-309],

 [ 2.13182611e-314, 3.06959433e-309]]) #random

 >>> np.empty([2, 2], dtype=int)

 array([[-1073741821, -1067949133],

 [ 496041986, 19249760]]) #random

 """

 There are examples on the official website. Let’s translate it a little bit. It is based on a given shape and data type (order can be ignored). (shape, [dtype, order]) returns a new array (it can be empty or other, this is the data type to be given). The data type defaults to np.float64. When we do not specify any data type for the index, the data returned to i must be np.float64, which means it cannot be empty at this time. But when the data type refers to an object (such as a list), an empty array is created.

 a = np.empty((1, 4), dtype=dict)

 print(a) # [[None None None None]]

 b = np.empty((1, 4), dtype=list)

 print(b) # [[None None None None]]

 20,np.transpose()

 (Reference address: https://www.freesion.com/article/149821286/)

 First look at the source code:

 """

 Reverse or permute the axes of an array; returns the modified array.

 For an array a with two axes, transpose(a) gives the matrix transpose.

 Parameters

 ----------

 a : array_like

 Input array.

 axes : tuple or list of ints, optional

 If specified, it must be a tuple or list which contains a permutation of

 [0,1,..,N-1] where N is the number of axes of a. The i'th axis of the

 returned array will correspond to the axis numbered ``axes[i]`` of the

 input. If not specified, defaults to ``range(a.ndim)[::-1]``, which

 reverses the order of the axes.

 Returns

 -------

 p : ndarray

 `a` with its axes permuted. A view is returned whenever

 possible.

 See Also

 --------

 moveaxis

 argsort

 Notes

 -----

 Use `transpose(a, argsort(axes))` to invert the transposition of tensors

 when using the `axes` keyword argument.

 Transposing a 1-D array returns an unchanged view of the original array.

 Parameter a: input array

 axis: list of int type, this parameter is optional. By default, the dimension of the input array is reversed. When this parameter is given, the array transformation is performed according to the value given by this parameter

 Return value p: ndarray returns a view of the original array after transposition

 20.1 One-dimensional arrays

 For 1-dimensional arrays, np.transpose() doesn't work. The source code notes above also talked about it. Let's experiment here.

 import numpy as np

 t = np.arange(4)

 # array([0, 1, 2, 3])

 t.transpose()

 # array([0, 1, 2, 3])

 20.2 Two-dimensional array

 In the case of a two-dimensional array, the original array has two axes (x, y), and the corresponding subscript is (0, 1). The parameter passed in by np.transpose() is (1, 0), that is, the x, The y-axis is interchanged. So the transpose operation for a two-dimensional array is the transpose operation of the original array. The experiment is as follows:

 import numpy as np

 two_array = np.arange(16).reshape(4, 4)

 # print(two_array)

 '''

 [[ 0 1 2 3]

 [ 4 5 6 7]

 [ 8 9 10 11]

 [12 13 14 15]]

 '''

 print(two_array.transpose())

 '''

 [[ 0 4 8 12]

 [ 1 5 9 13]

 [ 2 6 10 14]

 [ 3 7 11 15]]

 '''

 print(two_array.transpose(1, 0))

 '''

 [[ 0 4 8 12]

 [ 1 5 9 13]

 [ 2 6 10 14]

 [ 3 7 11 15]]

 '''

 20.3 Three-dimensional array

 For a three-dimensional array, we can first look at an example:

 import numpy as np

 three_array = np.arange(18).reshape(2, 3, 3)

 # print(three_array)

 '''

 [[[ 0 1 2]

 [ 3 4 5]

 [ 6 7 8]]

 [[ 9 10 11]

 [12 13 14]

 [15 16 17]]]

 '''

 print(three_array.transpose())

 '''

 [[[ 0 9]

 [ 3 12]

 [ 6 15]]

 [[ 1 10]

 [ 4 13]

 [ 7 16]]

 [[ 2 11]

 [ 5 14]

 [ 8 17]]]

 '''

 This is the default operation of the np.transpose() function on the three_array array, that is, to reverse each axis of the original array, the original axis arrangement of the three_array is (0, 1, 2), and the default parameter of numpy.transpose() is (2 , 1, 0) Get the view of the transposed array, without affecting the content and size of the original array. Let’s analyze this process step by step: axis(0, 1, 2)——> axis(2, 1, 0), the array after transpose is equivalent to swapping the 0 axis and 2 axis of the original array .

 #Write the subscript of the original three array as follows:

 A=[

 [ [ (0,0,0) , (0,0,1) , (0,0,2)],

 [ (0,1,0) , (0,1,1) , (0,1,2)],

 [ (0,2,0) , (0,2,1) , (0,2,2)]],

 [[ (1,0,0) , (1,0,1) , (1,0,2)],

 [ (1,1,0) , (1,1,1) , (1,1,2)],

 [ (1,2,0) , (1,2,1) , (1,2,2)]]

 ]

 #Then exchange the first number and the third number of each of the above triples to get the following array

 B=[[[ (0,0,0) , (1,0,0) , (2,0,0)],

 [ (0,1,0) , (1,1,0) , (2,1,0)],

 [ (0,2,0) , (1,2,0) , (2,2,0)]],

 [[ (0,0,1) , (1,0,1) , (2,0,1)],

 [ (0,1,1) , (1,1,1) , (2,1,1)],

 [ (0,2,1) , (1,2,1) , (2,2,1)]]]

 #Finally write the element of the subscript corresponding to B in the original array to the corresponding position

 #Look at the comparison, this is the original array

 [[[ 0, 1, 2],

 [ 3, 4, 5],

 [ 6, 7, 8]],

 [[ 9, 10, 11],

 [12, 13, 14],

 [15, 16, 17]]]

 # Get the final array according to the mapping relationship of B.

 C=[[[ 0, 9],

 [ 3, 12],

 [ 6, 15]],

 [[ 1, 10],

 [4, 13],

 [7, 16]]

 [[ 2, 11],

 [5, 14],

 [8, 17]]

 ]

 # The final result is the array C

 We know the result of the rotated matrix, so why do we want to rotate the image in deep learning? And what is the point of doing this? We can continue to learn:

 import cv2 as cv

 import numpy as np

 img = cv.imread('my.jpg')

 cv.imshow('img',img)

 #Rotate 90 degrees counterclockwise

 img = np.transpose(img, (1, 0, 2))

 #Rotate 90 degrees clockwise

 # img = cv.flip(img, 1)

 #Rotate 270 degrees clockwise

 # img = cv.flip(img, 1)

 cv.namedWindow('img',cv.WINDOW_AUTOSIZE)

 cv.imshow('img2',img)

 cv.waitKey(0)

 cv.destroyAllWindows()

 Perform np.transpse(img, (1, 0, 2)) operation on the image, you can flip the image 90 degrees counterclockwise, and with cv2.fip(img, 0 or 1), you can flip 270 degrees or 90 degrees .

 The following function also flips the image, you can continue to look at it and use the one you like.

 21 , e.g. rot90 ()

 The function of this function is to rotate the matrix (the matrix is ​​rotated counterclockwise by 90 degrees or a multiple of 90 degrees), which can sometimes be used to rotate the image.

 The source code of the function is as follows (m is the matrix to be rotated, k is the rotation angle of 90 degrees*K (k defaults to 1)):

 def rot90(m, k=1, axes=(0, 1)):

 """

 Rotate an array by 90 degrees in the plane specified by axes.

 Rotation direction is from the first towards the second axis.

 Parameters

 ----------

 m : array_like

 Array of two or more dimensions.

 k : integer

 Number of times the array is rotated by 90 degrees.

 axes: (2,) array_like

 The array is rotated in the plane defined by the axes.

 Axes must be different.

 .. versionadded:: 1.12.0

 Returns

 -------

 y: ndarray

 A rotated view of `m`.

 See Also

 --------

 flip : Reverse the order of elements in an array along the given axis.

 fliplr : Flip an array horizontally.

 flipud : Flip an array vertically.

 Notes

 -----

 rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))

 rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))

 Example:

 >>> m = np.array([[1,2],[3,4]], int)

 >>> m

 array([[1, 2],

 [3, 4]])

 >>> np.rot90(m)

 array([[2, 4],

 [1, 3]])

 >>> np.rot90(m, 2)

 array([[4, 3],

 [2, 1]])

 >>> m = np.arange(8).reshape((2,2,2))

 >>> np.rot90(m, 1, (1,2))

 array([[[1, 3],

 [0, 2]],

 [[5, 7],

 [4, 6]]])

 There are two ways to rotate the image, using PIL, but it will change the image size. Need to pay attention to use. Rotation includes two methods: transpose() and rotate().

 from PIL import Image

 img = Image.open("logo1.jpg")

 # Rotation method one

 img1 = img.transpose(Image.ROTATE_90) # reference fixed constant value

 img1.save("r1.jpg")

 # Rotation method two

 img2 = img.rotate(90) # custom rotation degree

 img2.save("r2.jpg")

 # np Rotation method

 img3 = cv2.imread("logo1.jpg")

 img3 = np.rot90(img3, k=1)

 cv2.imwrite("r3.jpg", img3)

 Let's see the effect:

 

 So, use rotate carefully, and I stepped on the pit.

 Reference: https://github.com/wmpscc/DataMiningNotesAndPractice/blob/master/4.NumPy%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.md

Guess you like

Origin blog.csdn.net/u013946150/article/details/112976727