NumPy shape 与 reshape 区别

一. 基本使用

In [438]: x = np.arange(12)
In [439]: y = x                # same object
In [440]: y.shape = (2,6)      # inplace shape change
In [441]: y
Out[441]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])
In [442]: x
Out[442]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])
In [443]: y = y.reshape(3,4)   # y is a new view
In [444]: y
Out[444]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [445]: x                    # buffer data is not change
Out[445]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])

二. 具体介绍

可以使用 numpy array 的 shape 属性值, 或者 reshape 方法来修改 numpy 对象的 shape.

  • 直接 shape 赋值, 修改了 numpy array 的 data buffer
  • 使用 reshape 方法, 仅仅返回了一个视图

三. Data Buffer 与 View

numpy array 变量有一个对应的内存实体 (data buffers), 同时可以有多个视图 (view).

  • shape 直接改变 data buffer; reshape 则是返回一个新的 view.
  • 不同索引/切片 (index) 方法对应于不同的返回结果 (view 或者是 copy) 待总结
  • Arrays can also have views, which are new array objects, but with shared data buffers.

  • A copy has its own data buffer.

References

原文地址:https://www.cnblogs.com/crayonsea/p/14058393.html