我已經開發了一個代碼,我正在尋找一種更有效的方法,因為它很慢。是否可以修改此代碼使其更快?
代碼解釋起來真的很復雜,如果我的解釋不那么令人滿意,請提前抱歉:
我正在處理這個包含 7 個維度為 50x1000 的矩陣的大矩陣。代碼以這種方式作業:
- 我取每個矩陣的第一個元素(包含在大矩陣中),創建這些元素的串列--> [a1b1, a2b1, ... a7b1]
- 創建此串列后,我對其進行插值,創建一個包含 50 個元素的新串列
- 現在,我需要重復點 (1) 和 (2),但是對于所有矩陣的第二行的第一個元素,直到最后一行的第一個元素。
- 完成第一列的所有元素后,我們可以切換到所有矩陣的第二列并重復點(1),(2),(3)
如果有什么不清楚的,請告訴我,我會盡力解釋!

import numpy as np
from scipy.interpolate import barycentric_interpolate
matrix = np.random.rand(7, 50, 1000)
X = np.linspace(0.1,0.8,7)
intervals = np.linspace(0.5,1.5,50)
matrix_tot = []
for col in range(len(matrix[0][0])):
matrix_i = []
for row in range(len(matrix[0])):
interp_1 = []
for m in range(len(matrix)):
values = matrix[m][row][col]
interp_1.append(values)
row_interpolated = barycentric_interpolate(X,np.array(interp_1),intervals)
matrix_i.append(row_interpolated)
matrix_tot.append(matrix_i)
matrix_tot = np.array(matrix_tot)
print(matrix_tot.shape)
uj5u.com熱心網友回復:
通過執行以下操作,我獲得了輕微的性能提升
import numpy as np
from scipy.interpolate import barycentric_interpolate
import time
matrix = np.random.rand(7, 50, 1000)
X = np.linspace(0.1,0.8,7)
intervals = np.linspace(0.5,1.5,50)
def interpolate(a):
return barycentric_interpolate(X, a, intervals)
start = time.process_time()
out = np.apply_along_axis(interpolate, 0, matrix)
print(time.process_time() - start)
與我機器上的 3.76 秒相比,它回傳??的時間為 ~3.52。注意,這里的輸出矩陣是 (50, 50, 1000)。要獲得矩陣的維度,只需將其轉置即可。
np.all(out.T == matrix_tot)
uj5u.com熱心網友回復:
知道了。幸運的是,您可以y在單個函式呼叫中提供多個向量。它似乎是矢量化的,因為性能增益是 2 個數量級。
import numpy as np
from scipy.interpolate import barycentric_interpolate
import time
matrix = np.random.rand(7, 50, 1000)
X = np.linspace(0.1,0.8,7)
intervals = np.linspace(0.5,1.5,50)
start = time.process_time()
matrix_tot = []
for col in range(len(matrix[0][0])):
matrix_i = []
for row in range(len(matrix[0])):
interp_1 = []
for m in range(len(matrix)):
values = matrix[m][row][col]
interp_1.append(values)
row_interpolated = barycentric_interpolate(X,np.array(interp_1),intervals)
matrix_i.append(row_interpolated)
matrix_tot.append(matrix_i)
matrix_tot = np.array(matrix_tot)
print('baseline: ', time.process_time() - start)
## ANSWER HERE:
start = time.process_time()
matrix_reshaped = matrix.reshape(7, 50 * 1000)
matrix_tot2 = barycentric_interpolate(X, matrix_reshaped, intervals).reshape(50, 50, 1000)
# this is only for comparison with matrix_tot, you may want to remove line below:
matrix_tot2 = matrix_tot2.transpose([2, 1, 0])
print('vectorised: ', time.process_time() - start)
assert np.allclose(matrix_tot, matrix_tot2, atol=1e-8)
結果:
baseline: 5.796875
vectorised: 0.015625
而不是單個 for 回圈 :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314077.html
