赞
踩
首先声明两者所要实现的功能是一致的(将多维数组降位一维),两者的区别在于返回拷贝(copy)还是返回视图(view),numpy.flatten()返回一份拷贝,对拷贝所做的修改不会影响(reflects)原始矩阵,而numpy.ravel()返回的是视图(view,也颇有几分C/C++引用reference的意味),会影响(reflects)原始矩阵。
1. 两者的功能
- >>> x = np.array([[1, 2], [3, 4]])
- >>> x
- array([[1, 2],
- [3, 4]])
- >>> x.flatten()
- array([1, 2, 3, 4])
- >>> x.ravel()
- array([1, 2, 3, 4])
- 两者默认均是行序优先
- >>> x.flatten('F')
- array([1, 3, 2, 4])
- >>> x.ravel('F')
- array([1, 3, 2, 4])
-
- >>> x.reshape(-1)
- array([1, 2, 3, 4])
- >>> x.T.reshape(-1)
- array([1, 3, 2, 4])
2. 两者的区别
- >>> x = np.array([[1, 2], [3, 4]])
- >>> x.flatten()[1] = 100
- >>> x
- array([[1, 2],
- [3, 4]]) # flatten:返回的是拷贝
- >>> x.ravel()[1] = 100
- >>> x
- array([[ 1, 100],
- [ 3, 4]])
References
[1] What is the difference between flatten and ravel functions in numpy?
---------------------
作者:Inside_Zhang
来源:CSDN
原文:https://blog.csdn.net/lanchunhui/article/details/50354978
版权声明:本文为博主原创文章,转载请附上博文链接!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。