Numpy - 用向量行创建矩阵 [英] Numpy - create matrix with rows of vector

查看:46
本文介绍了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 个零后,像这样 -

Certainly possible with broadcasting after adding with m zeros along the columns, like so -

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

现在,NumPy 已经有一个内置函数 np.tile 用于完全相同的任务 -

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]])

您也可以使用 整数数组索引以获取复制,就像这样 -

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天全站免登陆