将Numpy(n,)向量重塑为(n,1)向量 [英] Reshape numpy (n,) vector to (n,1) vector

查看:287
本文介绍了将Numpy(n,)向量重塑为(n,1)向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我需要进行线性代数运算时,我更容易将向量视为列向量.因此,我更喜欢像(n,1)这样的形状.

So it is easier for me to think about vectors as column vectors when I need to do some linear algebra. Thus I prefer shapes like (n,1).

形状(n,)和(n,1)之间是否存在显着的内存使用差异?

Is there significant memory usage difference between shapes (n,) and (n,1)?

首选方式是什么?

以及如何将(n,)向量重塑为(n,1)向量.不知何故b.reshape((n,1))不能解决问题.

And how to reshape (n,) vector into (n,1) vector. Somehow b.reshape((n,1)) doesn't do the trick.

a = np.random.random((10,1))
b = np.ones((10,))
b.reshape((10,1))
print(a)
print(b)

[[ 0.76336295]
 [ 0.71643237]
 [ 0.37312894]
 [ 0.33668241]
 [ 0.55551975]
 [ 0.20055153]
 [ 0.01636735]
 [ 0.5724694 ]
 [ 0.96887004]
 [ 0.58609882]]
[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

推荐答案

ndarray.reshape() 返回一个新视图或一个副本(取决于新形状).它不会修改数组.

ndarray.reshape() returns a new view, or a copy (depends on the new shape). It does not modify the array in place.

b.reshape((10, 1))

这样

实际上是无效的操作,因为创建的视图/副本未分配给任何对象. 修复"很简单:

as such is effectively no-operation, since the created view/copy is not assigned to anything. The "fix" is simple:

b_new = b.reshape((10, 1))

两个形状之间使用的内存量不应完全相同. numpy数组使用 strides 的概念,因此维度(10,)(10, 1)都可以使用相同的缓冲区;跳转到下一行和下一列的金额就改变了.

The amount of memory used should not differ at all between the 2 shapes. Numpy arrays use the concept of strides and so the dimensions (10,) and (10, 1) can both use the same buffer; the amounts to jump to next row and column just change.

这篇关于将Numpy(n,)向量重塑为(n,1)向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆