# 如何使用 scipy.optimize.curve_fit 来使用变量列表How to use scipy.optimize.curve_fit to use lists of variable

``````from scipy.optimize import curve_fit
from matplotlib.pylab import plt
from numpy import exp

def ffunc2(x, a, b):
counter = 0
return_value = 0
while counter < len(a):
return_value += a[counter] * exp(b[counter] * x)
counter += 1
return return_value

# INITIAL DATA
x = [1, 2, 3, 5]
y = [1, 8, 81, 125]

number_variable = 2

# INTIAL GUESS
p0 = []
counter = 0
while counter < number_variable:
p0.append(0.0)
counter += 1

p, _ = curve_fit(ffunc2, x, y, p0=[0.0, 0.0])

``````

``````from numpy import exp
from scipy.optimize import curve_fit

def wrapper_fit_func(x, N, *args):
a, b, c = list(args[0][:N]), list(args[0][N:2*N]), list(args[0][2*N:3*N])
return fit_func(x, a, b)

def fit_func(x, a, b):
counter = 0
return_value = 0
while counter < len(a):
return_value += a[counter] * exp(b[counter] * x)
counter += 1
return return_value

x = [1, 2, 3, 5]
y = [1, 8, 81, 125]
params_0 = [0,1.0,2.0,3.0,4.0,5.0]

popt, pcov = curve_fit(lambda x, *params_0: wrapper_fit_func(x, 3, params_0), x, y, p0=params_0)

``````

## 2 个回复2

### #1楼 票数：1 已采纳

``````from scipy.optimize import least_squares
from matplotlib.pylab import plt
from numpy import exp
import numpy as np

# define function to fit
def ffunc2(a, x):
counter = 0
return_value = 0
while counter < len(a):
return_value += a[counter] * exp(x * a[counter + 1])
counter += 2

return return_value

def error_func(tpl, x, y):
return ffunc2(tpl,x) - y

# INPUT DATA
x = np.array([1, 2, 3, 5])
y = np.array([0.22103418, 0.24428055, 0.26997176, 0.32974425,])

# INITIAL GUESS
p0 = (1, 1)*10
output = least_squares(error_func, x0=p0, jac='2-point', bounds=(0, np.inf), method='trf', ftol=1e-08,
xtol=1e-08, gtol=1e-08, x_scale=1.0, loss='linear', f_scale=1.0, diff_step=None,
tr_solver=None,
tr_options={}, jac_sparsity=None, max_nfev=None, verbose=0, args=(x, y))

tpl_final = output.x
print (tpl_final)

final_curve = ffunc2(tpl_final,x)

plt.plot(x, y, 'r-', x, final_curve, 'g-')
plt.show()

``````

1回复

2回复

1回复

1回复

1回复

1回复

2回复

1回复