numpy-创建带有向量行的矩阵 [英] Numpy - create matrix with rows of vector

查看:171
本文介绍了numpy-创建带有向量行的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量[x,y,z,q],我想创建一个矩阵:

I have a vector [x,y,z,q] and I want to create a matrix:

[[x,y,z,q],
 [x,y,z,q],
 [x,y,z,q],
...
 [x,y,z,q]]

有m行.我认为可以使用广播以某种巧妙的方式来完成此操作,但我只能考虑使用for循环来完成此操作.

with m rows. I think this could be done in some smart way, using broadcasting, but I can only think of doing it with a for loop.

推荐答案

使用 broadcasting ,然后在各列中添加m零,就像这样-

np.zeros((m,1),dtype=vector.dtype) + vector

现在,NumPy已经具有内置功能 用于完全相同的任务-

Now, NumPy already has an in-built function np.tile for exactly that same task -

np.tile(vector,(m,1))

样品运行-

In [496]: vector
Out[496]: array([4, 5, 8, 2])

In [497]: m = 5

In [498]: np.zeros((m,1),dtype=vector.dtype) + vector
Out[498]: 
array([[4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2]])

In [499]: np.tile(vector,(m,1))
Out[499]: 
array([[4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2]])

您还可以在之后使用 np.repeat np.newaxis/None扩展其尺寸以达到相同的效果,就像这样-

You can also use np.repeat after extending its dimension with np.newaxis/None for the same effect, like so -

In [510]: np.repeat(vector[None],m,axis=0)
Out[510]: 
array([[4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2]])

您还可以使用 integer array indexing 来获取复制品,就像这样-

You can also use integer array indexing to get the replications, like so -

In [525]: vector[None][np.zeros(m,dtype=int)]
Out[525]: 
array([[4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2]])

最后加上 np.broadcast_to ,您可以简单地在输入vector中创建一个2D视图,因此这实际上是免费的,并且不需要额外的内存.因此,我们只需要-

And finally with np.broadcast_to, you can simply create a 2D view into the input vector and as such this would be virtually free and with no extra memory requirement. So, we would simply do -

In [22]: np.broadcast_to(vector,(m,len(vector)))
Out[22]: 
array([[4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2],
       [4, 5, 8, 2]])


运行时测试-


Runtime test -

这是一个快速的运行时测试,比较了各种方法-

Here's a quick runtime test comparing the various approaches -

In [12]: vector = np.random.rand(10000)

In [13]: m = 10000

In [14]: %timeit np.broadcast_to(vector,(m,len(vector)))
100000 loops, best of 3: 3.4 µs per loop # virtually free!

In [15]: %timeit np.zeros((m,1),dtype=vector.dtype) + vector
10 loops, best of 3: 95.1 ms per loop

In [16]: %timeit np.tile(vector,(m,1))
10 loops, best of 3: 89.7 ms per loop

In [17]: %timeit np.repeat(vector[None],m,axis=0)
10 loops, best of 3: 86.2 ms per loop

In [18]: %timeit vector[None][np.zeros(m,dtype=int)]
10 loops, best of 3: 89.8 ms per loop

这篇关于numpy-创建带有向量行的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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