Matmul和Numpy.Dot:使用Numpy内置函数加速代码

2024-09-30 23:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的代码中加速一个函数

我写的最初函数是:

def f(self):
    temp = 0
    for i in range(self.N):
        for j in range(self.N):
            a = self.Asolution[:, j]
            b = self.Bsolution[:, i]
            c = self.Matrix[j][i]

            d = c*np.multiply(a, b)
            temp += simps(d, self.time)
    return temp

其中self.Asolution = odeint(...) ,与self.Bsolution相同

self.Matrix是一个大小为self.N x self.N的平方矩阵,simps是辛普森积分self.Asolutionself.Bsolution有维度(txn)

但是,我需要多次调用此函数,而且由于self.N相当大,调用时间太长。在此之前,我决定尝试一下numpy内置函数,因为我主要处理矩阵乘法。我倾向于对所有东西使用for循环,这不是最明智的选择。。。因此,我对内置的numpy函数有点不熟悉。我将函数修改为:

def f(self):
   d = np.dot(np.dot(self.Asolution, self.Matrix), self.Bsolution.transpose())
   d = np.array(d)
   temp = simps(d, self.time)
   temp = sum(temp)
 
   return temp

这是显着更快,但我没有得到同样的结果如上所述

我想我误解了np.dot的用法,或者我错过了矩阵相乘的方法。 我的主要目标是从第一个代码中删除double for循环,因为它需要永远。我错过了什么?提前感谢您的任何提示

编辑:

self.Asolution self.Bsolution有大小(t x N)-每列都是不同的位置,行表示位置随时间的变化

self.Matrix具有大小(nxn)


Tags: 函数代码inselffordefnprange
2条回答

让我们试试这个-


# self.t x self.N   > self.N x self.t x 1
# arranging one column in one layer
self.Bsolution = np.swapaxes(np.expand_dims(self.Bsolution, axis=-1), 0, 1)

# self.N x self.t x self.N == N columns of Bsolution multiplied with N columns of Asolution
# multiplying 1 column of B with N columns of A in a layer done for N layers
product = np.multiply(self.Bsolution, self.Asolution)

# self.N x self.N   > self.N x 1 x self.N 
self.Matrix = np.expand_dims(self.Matrix, axis=1)

# integration need to take place along axis=1 i believe
# multiplying each of N x N columns(4 rows in length) with N x N matrix elements
result = np.sum(simps(np.multiply(self.Matrix, product), self.time))

让我知道它是否有效

经过多次尝试和错误,我设法找到了一种比双for循环更快地获得相同结果的方法。我发布它只是为了完整性和结束问题

n = len(self.time)
d = [np.matmul(np.matmul(self.Asolution[:][i], self.Matrix),
     self.Bsolution[:][i].transpose) for i in range(n)]
temp = np.simps(d, self.time)

相关问题 更多 >