【发布时间】: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