0
我想轉換一些Matlab代碼,我有曲線擬合我的數據到Python代碼,但我有麻煩得到類似的答案。這些數據是:指數曲線擬合與python
x = array([ 0. , 12.5 , 24.5 , 37.75, 54. , 70.25, 87.5 ,
108.5 , 129.5 , 150.5 , 171.5 , 193.75, 233.75, 273.75])
y = array([-8.79182857, -5.56347794, -5.45683824, -4.30737662, -1.4394612 ,
-1.58047016, -0.93225927, -0.6719836 , -0.45977157, -0.37622436,
-0.56115757, -0.3038559 , -0.26594558, -0.26496367])
的Matlab代碼是:
function [estimates, model] = curvefit(xdata, ydata)
% fits data to the curve y(x)=A-B*e(-lambda*x)
start_point = rand(1,3);
model [email protected];
options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
estimates = fminsearch(model, start_point,options);
% expfun accepts curve parameters as inputs, and outputs sse,
% the sum of squares error for A -B* exp(-lambda * xdata) - ydata,
% and the FittedCurve.
function [sse,FittedCurve] = efun(v)
A=v(1);
B=v(2);
lambda=v(3);
FittedCurve =A - B*exp(-lambda*xdata);
ErrorVector=FittedCurve-ydata;
sse = sum(ErrorVector .^2);
end
end
err = Inf;
numattempts = 100;
for k=1:numattempts
[intermed,model]=curvefit(x, y));
[thiserr,thismodel]=model(intermed);
if thiserr<err
err = thiserr;
coeffs = intermed;
ymodel = thismodel;
end
,並在Python到目前爲止,我:
import numpy as np
from pandas import Series, DataFrame
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import curve_fit
import pickle
def fitFunc(A, B, k, t):
return A - B*np.exp(-k*t)
init_vals = np.random.rand(1,3)
fitParams, fitCovariances = curve_fit(fitFunc, y, x], p0=init_vals)
我想我必須做一些事情上運行的100次嘗試p0,但曲線只會收斂大約1/10倍,並且會收斂到一條直線,與我在Matlab中獲得的值相反。還有關於曲線擬合的大多數問題,我已經看到使用B np.exp(-k t)+ A,但是我有上面的指數公式是我必須使用的數據。有什麼想法嗎?感謝您的時間!
這很好知道,謝謝! – adamluco
歡迎來到python!請閱讀這些功能和示例的文檔。他們非常有用。 – plasmon360
您可以選擇其中一個答案並接受答案,以便讓人們知道問題已經完成嗎? – plasmon360