当将非常简单函数拟合到一些随机创建的数据时,我发现Python似乎比Matlab大约两个数量级。
现在,这可能取决于具体的实现以及用于此特定拟合的函数,但是,我仍然觉得奇怪的是存在如此巨大的差异。如果有人能告诉我这是怎么发生的,我将不胜感激。
Matlab (也用于创建数据并写入文件,然后由python读取):
% Write data to file to be able to compare across languages
x = 0:9;
x = repmat(x', 1, 100);
y = x.^2;
y = y+randn(10, 100);
dlmwrite('y_mat.csv',y);
% Fit and time execution
tic
D = zeros(1, 100);
a = zeros(1, 100);
ft = fittype('4*D*x^a');
for i = 1:100
f = fit(x(:, i),y(:, i), ft);
a(i) = f.a;
D(i) = f.D;
end
toc
的Python:
import time
import numpy as np
from scipy import optimize
start_time = time.time()
data = np.loadtxt("y_mat.csv", delimiter=',');
def func(t, D, a):
return 4*D*t**a
DA = np.zeros([numParticles, 2])
for i in range(0, numParticles):
x = np.arange(10)
y = data[:,i]
popt, pcov = optimize.curve_fit(func, x, y)
DA[i, ] = popt
print("--- %s seconds ---" % (time.time() - start_time))