Hướng dẫn dùng numpy flatten python
A vital property of NumPy arrays is their shape. The shape of an array can be determined by using the numpy reshape and numpy flatten attribute. But what about if you want to change the shape of an array? The numpy.reshape() and numpy.flatten() functions are used to change the shape of an array. In this tutorial, we will discuss how to implement them in your code. Using the reshape() methodThe reshape method is used to convert an array from one shape, to another. For instance, an array of shape (1, 9) can be reshaped to an array of shape (3, 3). Below is the syntax of the reshape() method. np.reshape(a, newshape) Parameters: a: This is the array you wish to be reshaped. newshape: This is the new shape of the array to be returned. Let’s see an example. import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) #reshaping the array. print(np.reshape(a, (3, 3))) In the example above, the 1-dimensional array of length 9 was converted to a 2-dimensional array of shape, 3 by 3. Let’s see the result for the above code.
As seen, the shape has been changed. There’s one thing to note about the reshape method, however. The new shape must be able to contain all the elements of the old shape. For example, the array in the last example has 9 elements. A 3 by 3 array can contain 9 elements, so it is compatible. An attempt to reshape that array to say (2, 4), which can contain only 8 elements and not 9, returns an error. See the example below. import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) #reshaping the array. print(np.reshape(a, (2, 4)))
The reshape() method is especially useful when building convolutional neural networks as most times, you will need to reshape the image shape from 2-dimensional to a 3-dimensional array. Using the numpy.flatten() method.As the name applies, the flatten() method in Numpy is used to convert an array into a 1-dimensional array. So it basically flattens the array irrespective of its shape. Using the flatten() method does not have a required parameter. See an example below. import numpy as np a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(a) #flatten the array print('flattening a...') print(a.flatten())
If you have any questions, feel free to leave them in the comment section and I’d do my best to answer them. Vì numpy là thư viện được sử dụng thường xuyên nên nó thường được khai báo gọn lại như trên 2 có thể thay thế bằng các từ khác, tuy nhiên bạn nên đặt là 2 vì các tài liệu hướng dẫn đều ngầm quy ước như thế.NumPy là gì ?Theo định nghĩa trên trang chủ của Numpy.
Bạn có thể hiểu đơn giản: NumPy (Numeric Python) là là thư viện cốt lõi cho tính toán khoa học trong Python. Nó cung cấp một đối tượng mảng đa chiều hiệu suất cao và các công cụ để làm việc với các mảng này. Hãy xem qua một ví dụ cho thấy NumPy mạnh như thế nào. Giả sử chúng ta có hai list a và b, bao gồm 100.000 số không âm đầu tiên và chúng tôi muốn tạo một list mới c có phần tử thứ i là a[i] + 2 * b[i] |