【发布时间】:2017-03-13 17:20:11
【问题描述】:
我正在使用 np.dot() 在 NumPy 中进行矩阵乘法。由于数据集非常大,我想尽可能减少整体运行时间 - 即尽可能少地执行 np.dot() 产品。
具体来说,我需要从我的值向量的每个元素计算整个矩阵乘积以及相关流。 NumPy 有没有办法在一两个 np.dot() 产品中计算所有这些? 在下面的代码中,有没有办法减少 np.dot() 产品的数量并仍然获得相同的输出?
import pandas as pd
import numpy as np
vector = pd.DataFrame([1, 2, 3],
['A', 'B', 'C'], ["Values"])
matrix = pd.DataFrame([[0.5, 0.4, 0.1],
[0.2, 0.6, 0.2],
[0.1, 0.3, 0.6]],
index = ['A', 'B', 'C'], columns = ['A', 'B', 'C'])
# Can the number of matrix multiplications in this part be reduced?
overall = np.dot(vector.T, matrix)
from_A = np.dot(vector.T * [1,0,0], matrix)
from_B = np.dot(vector.T * [0,1,0], matrix)
from_C = np.dot(vector.T * [0,0,1], matrix)
print("Overall:", overall)
print("From A:", from_A)
print("From B:", from_B)
print("From C:", from_C)
【问题讨论】:
-
在这里查看讨论 - stackoverflow.com/questions/21562986/…
-
您能否提供一个更好的输入和输出示例?不清楚你到底想要什么。
-
这里根本不需要矩阵乘法。看我的回答。我觉得比目前选的那个好。