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[] method

The 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. 

Output:
[[1 2 3] 
 [4 5 6] 
 [7 8 9]]

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]]]
Output:
Traceback [most recent call last]:
  File "c:/Users/DELL/Desktop/pycodes/__pycache__/strings.py", line 6, in    
    print[np.reshape[a, [2, 4]]]
  File "", line 5, in reshape
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\core\fromnumeric.py", line 299, in reshape
    return _wrapfunc[a, 'reshape', newshape, order=order]
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\core\fromnumeric.py", line 58, in _wrapfunc
    return bound[*args, **kwds]
ValueError: cannot reshape array of size 9 into shape [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[]]
Output:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
flattening a...
[1 2 3 4 5 6 7 8 9]

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

c = np.eye[3]         # Create a 3 x 3 identity matrix
print[c]              # Prints "[[ 1.  0.  0.]
                      #          [ 0.  1.  0.]
                      #          [ 0.  0.  1.]]"
2 có thể thay thế bằng các từ khác, tuy nhiên bạn nên đặt là
c = np.eye[3]         # Create a 3 x 3 identity matrix
print[c]              # Prints "[[ 1.  0.  0.]
                      #          [ 0.  1.  0.]
                      #          [ 0.  0.  1.]]"
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.

"NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects [such as masked arrays and matrices], and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more"
-//docs.scipy.org/doc/numpy-1.10.1/user/whatisnumpy.html.

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]

Chủ Đề