# 使用 numpy 或 scipy 将 3D 数据数组拟合到 1D 函数(Fitting a 3D array of data to a 1D function with numpy or scipy)

4我目前正在尝试将大量数据拟合到正弦函数中。 在我只有一组数据（一维数组）的情况下， `scipy.optimize.curve_fit()`工作正常。 但是，如果函数本身只有一维，就我所见，它不允许更高维的数据输入。 我不想使用 for 循环遍历数组，因为它在 python 中的工作速度非常慢。

``````from scipy import optimize
import numpy as np
def f(x,p1,p2,p3,p4): return p1 + p2*np.sin(2*np.pi*p3*x + p4)      #fit function

def fit(data,guess):
n = data.shape[0]
leng = np.arange(n)
param, pcov = optimize.curve_fit(f,leng,data,guess)
return param, pcov
``````

`ValueError: operands could not be broadcast together with shapes (2100,2100) (5)`

``````func1d = lambda y, *args: optimize.curve_fit(f, xdata=x, ydata=y, *args)[0] #<-- [0] to get only popt
param = np.apply_along_axis( func1d, axis=2, arr=data )
``````

``````from scipy import optimize
import numpy as np
def f(x,p1,p2,p3,p4):
return p1 + p2*np.sin(2*np.pi*p3*x + p4)
sx = 50  # size x
sy = 200 # size y
sz = 100 # size z
# creating the reference parameters
tmp = np.empty((4,sy,sz))
tmp[0,:,:] = (1.2-0.8) * np.random.random_sample((sy,sz)) + 0.8
tmp[1,:,:] = (1.2-0.8) * np.random.random_sample((sy,sz)) + 0.8
tmp[2,:,:] = np.ones((sy,sz))
tmp[3,:,:] = np.ones((sy,sz))*np.pi/4
param_ref = np.empty((4,sy,sz,sx))     # param_ref in this shape will allow an
for i in range(sx):                    # one-shot evaluation of f() to create
param_ref[:,:,:,i] = tmp           # the data sample
# creating the data sample
x = np.linspace(0,2*np.pi)
factor = (1.1-0.9)*np.random.random_sample((sy,sz,sx))+0.9
data = f(x, *param_ref) * factor       # the one-shot evalution is here
func1d = lambda y, *args: optimize.curve_fit(f, xdata=x, ydata=y, *args)[0] #<-- [0] to get only popt
param = np.apply_along_axis( func1d, axis=2, arr=data )
``````