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