【问题标题】:Numpy submatrix(selected random index) calculation performanceNumpy submatrix(selected random index)计算性能
【发布时间】:2017-02-03 15:29:45
【问题描述】:

我尝试使用 Numpy 计算子矩阵。

矩阵的形状是

A : (15000, 100)

B : (15000, 100)

B_ : (3000, 100)

C : (100, 100)

sample_index = np.random.choice(np.arange(int(15000*0.2)), size=int(int(15000*0.2)), replace=False)

第一个代码是

for ki in range(100):
    self.A[sample_index, k] += B_[:, k] - np.dot(self.A[sample_index, : ], C[:, k])

仅使用从 sample_index 切片的子矩阵

第二个代码是

for k in range(100):
    self.A[:, k] += B[:, k] - np.dot(self.A[:, : ], C[:, k])

使用所有矩阵。

但是第一个代码的计算时间比第二个代码慢。

你知道加速的任何原因或解决方案吗?

【问题讨论】:

  • 改用A[:3000, k];切片索引比数组索引更快(基本索引与高级索引)。
  • 为什么会看到k?为什么不A[:,:] += B - np.dot(A, C)
  • 其实我想选择随机索引 sample_index = np.random.choice(np.arange(int(15000*0.2)), size=int(15000*0.2), replace=False) 和sample_index = np.arange(int(15000*0.2)) 仅用于测试
  • 无论如何都要权衡取舍。索引减少了计算的大小,但本身需要时间。
  • 顺便说一句,我认为sample_index=np.random.permutation(int(15000*.2)) 会比你的第一步更快

标签: python numpy matrix-multiplication


【解决方案1】:

您实际上是在复制输入矩阵。如果您只是读取输入,则不必复制它。

import numpy as np
a = np.random.rand(10000).reshape(100, 100)
b = np.random.rand(10000).reshape(100, 100)
i = list(range(10))
a_sub0 = a[:10] # view
a_sub1 = a[i] # copying

# you can change the original matrix from the view
a_sub0[0, 0] = 100
(a[0, 0] == 100.0) and (a_sub1[0, 0] != 100.0) # True

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 2020-09-27
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2014-07-12
    • 2012-03-09
    相关资源
    最近更新 更多