The difference between ravel() and flatten() in numpy

The operations frequently used in Numpy are flattened operations.Numpy provides two functions for this operation.Their functions are the same, but the memory is very different.

Let's first look at the use of these two functions:

from numpy import *
  
a = arange(12).reshape(3,4)
print(a)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print(a.ravel())
# [ 0  1  2  3  4  5  6  7  8  9 10 11]
print(a.flatten())
# [ 0  1  2  3  4  5  6  7  8  9 10 11]

It can be seen that these two functions achieve the same function, but flatten() is more suitable when we usually use it. Flatten() allocates new memory during use, but ravel() returns a view of an array The view is the reference of the array (it is not appropriate to say that the reference is because the address of the original array and the array returned by ravel() are not the same), and care should be taken to avoid affecting the original array when modifying the view. What is this Meaning, let's explain it specifically through code:

from numpy import *

a = arange(12).reshape(3,4)
print(a)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

# 创建一个和a相同内容的数组b
b = a.copy()
c = a.ravel()
d = b.flatten()
# 输出c和d数组
print(c)
# [ 0  1  2  3  4  5  6  7  8  9 10 11]
print(d)
# [ 0  1  2  3  4  5  6  7  8  9 10 11]
# 可以看到c和d数组都是扁平化后的数组,具有相同的内容

print(a is c)
# False
print(b is d)
# False
# 可以看到以上a,b,c,d是四个不同的对象

# 但因为c是a的一种展示方式,虽然他们是不同的对象,但在修改c的时候,a中相应的数也改变了
c[1] = 99
d[1] = 99
print(a)
# [[ 0 99  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print(b)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print(c)
# [ 0 99  2  3  4  5  6  7  8  9 10 11]
print(d)
# [ 0 99  2  3  4  5  6  7  8  9 10 11]

Through the above analysis, the flatten() function should be used as much as possible in practical applications to avoid unexpected errors.

 

Undertake programming in Matlab, Python and C++, machine learning, computer vision theory implementation and guidance, both undergraduate and master's degrees, salted fish trading, professional answers please go to know, please contact QQ number 757160542 for details, if you are the one.

 

 

Guess you like

Origin blog.csdn.net/weixin_36670529/article/details/114242603