【问题标题】:fast way to stack vectors into a matrix in Python在 Python 中将向量堆叠到矩阵中的快速方法
【发布时间】:2018-08-24 14:26:35
【问题描述】:

我想在 python 中将相同长度 (500) 的 100k 向量堆叠到单个矩阵中,但这需要太多时间。

这是我的代码:

stacked = all_vectors[0]
for i in range(1,100000):
    stacked = np.column_stack((stacked ,all_vectors[i]))

你知道如何更快吗?

【问题讨论】:

  • 任何原因np.column_stack(all_vectors) 不起作用?
  • 是的,但 all_vectors 实际上包含 500k 个向量,我只想要其中的一个子集
  • 你不能先选择向量的子集,例如all_vectors[n:m]? Columnstack 每次都会创建一个新数组,因此不应迭代使用。列表索引和追加速度更快。

标签: python loops numpy matrix vector


【解决方案1】:

你应该得到你想要的答案

stacked = np.column_stack(all_vectors[:100000])

这和这似乎没有区别

stacked = np.array(all_vectors[:100000]).transpose()

正如您在本次互动会话中所见:

>>> stacked = np.column_stack(all_vectors[:100000])
>>> sstacked = np.array(all_vectors[:100000]).transpose()
>>> stacked == sstacked
array([[ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       ...,
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True]], dtype=bool)
>>> (stacked == sstacked).all()
True

编辑:计时结果似乎更喜欢第二种方法:

%%timeit
vector = list(range(1, 1+10))
all_vectors = [vector] *100_000
result = np.column_stack(all_vectors)

396 ms ± 18.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
vector = list(range(1, 1+10))
all_vectors = [vector] *100_000
result = np.array(all_vectors)
np.array(all_vectors[:100000]).transpose()

152 ms ± 3.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

【讨论】:

  • column_stack 将所有输入转换为二维数组,然后进行axis=1 连接。
  • 谢谢。我添加了时间来显示数组创建后跟换位更快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 2012-08-30
相关资源
最近更新 更多