有时将行向量或列向量“克隆”到矩阵中是有用的。克隆的意思是转换行向量,比如

[1, 2, 3]

变成一个矩阵

[[1, 2, 3],
 [1, 2, 3],
 [1, 2, 3]]

或者一个列向量,比如

[[1],
 [2],
 [3]]

into

[[1, 1, 1]
 [2, 2, 2]
 [3, 3, 3]]

在MATLAB或八度音阶中,这很容易做到:

 x = [1, 2, 3]
 a = ones(3, 1) * x
 a =

    1   2   3
    1   2   3
    1   2   3
    
 b = (x') * ones(1, 3)
 b =

    1   1   1
    2   2   2
    3   3   3

我想在numpy中重复这一点,但不成功

In [14]: x = array([1, 2, 3])
In [14]: ones((3, 1)) * x
Out[14]:
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])
# so far so good
In [16]: x.transpose() * ones((1, 3))
Out[16]: array([[ 1.,  2.,  3.]])
# DAMN
# I end up with 
In [17]: (ones((3, 1)) * x).transpose()
Out[17]:
array([[ 1.,  1.,  1.],
       [ 2.,  2.,  2.],
       [ 3.,  3.,  3.]])

为什么第一种方法(在[16])不工作?有没有一种更优雅的方法在python中实现这个任务?


当前回答

Let:

>>> n = 1000
>>> x = np.arange(n)
>>> reps = 10000

零成本分配

视图不占用任何额外的内存。因此,这些声明是瞬时的:

# New axis
x[np.newaxis, ...]

# Broadcast to specific shape
np.broadcast_to(x, (reps, n))

强制分配

如果你想强制内容驻留在内存中:

>>> %timeit np.array(np.broadcast_to(x, (reps, n)))
10.2 ms ± 62.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit np.repeat(x[np.newaxis, :], reps, axis=0)
9.88 ms ± 52.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit np.tile(x, (reps, 1))
9.97 ms ± 77.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

这三种方法的速度大致相同。

计算

>>> a = np.arange(reps * n).reshape(reps, n)
>>> x_tiled = np.tile(x, (reps, 1))

>>> %timeit np.broadcast_to(x, (reps, n)) * a
17.1 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit x[np.newaxis, :] * a
17.5 ms ± 300 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

>>> %timeit x_tiled * a
17.6 ms ± 240 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

这三种方法的速度大致相同。


结论

如果您希望在计算之前进行复制,请考虑使用“零成本分配”方法之一。你不会遭受“强制分配”的性能损失。

其他回答

另一个解决方案

>> x = np.array([1,2,3])
>> y = x[None, :] * np.ones((3,))[:, None]
>> y
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])

为什么?当然,重复和平铺是正确的方法。但是None索引是一个强大的工具,它可以让我多次快速向量化操作(尽管它很快就会非常消耗内存!)

下面是我自己代码中的一个例子:

# trajectory is a sequence of xy coordinates [n_points, 2]
# xy_obstacles is a list of obstacles' xy coordinates [n_obstacles, 2]
# to compute dx, dy distance between every obstacle and every pose in the trajectory
deltas = trajectory[:, None, :2] - xy_obstacles[None, :, :2]
# we can easily convert x-y distance to a norm
distances = np.linalg.norm(deltas, axis=-1)
# distances is now [timesteps, obstacles]. Now we can for example find the closest obstacle at every point in the trajectory by doing
closest_obstacles = np.argmin(distances, axis=1)
# we could also find how safe the trajectory is, by finding the smallest distance over the entire trajectory
danger = np.min(distances)

你可以使用

np.tile(x,3).reshape((4,3))

Tile将生成向量的代表

重塑会给你想要的形状

import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)

收益率:

[[ 1.  1.  1.]
 [ 2.  2.  2.]
 [ 3.  3.  3.]]

一个干净的解决方案是使用NumPy的外积函数和一个1的向量:

np.outer(np.ones(n), x)

给出n个重复行。切换参数顺序以获得重复列。为了得到相等的行数和列数

np.outer(np.ones_like(x), x)

我认为在numpy中使用broadcast是最好的,而且更快

我做了如下比较

import numpy as np
b = np.random.randn(1000)
In [105]: %timeit c = np.tile(b[:, newaxis], (1,100))
1000 loops, best of 3: 354 µs per loop

In [106]: %timeit c = np.repeat(b[:, newaxis], 100, axis=1)
1000 loops, best of 3: 347 µs per loop

In [107]: %timeit c = np.array([b,]*100).transpose()
100 loops, best of 3: 5.56 ms per loop

使用广播大约快15倍