0

亲爱的大家:我有一个包含多个 3D 数据点的数据集,我正在尝试找到该数据集的最佳拟合曲线。我可以在 2D 中执行此操作,如下所示。

import numpy as np
import os
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
df_reg1=pd.read_csv('C:\\Users\\wilso\\python\\datasets\\PCD\\df_clean_rail.csv')
df_reg=df_reg1[['x','y','z']]
data = df_reg.values
x, y, z = data[:, 0], data[:, 1], data[:, 2]
def objective(x, a, b, c):
    return a * x + b * x**2 + c
popt, _ = curve_fit(objective, x, y)
a, b, c = popt
print('y = %.5f * x + %.5f * x^2 + %.5f' % (a, b, c))
plt.scatter(x, y)
x_line = np.arange(min(x), max(x), 1)
y_line = objective(x_line, a, b, c)
plt.plot(x_line, y_line, '--', color='red')
plt.xlim(-100,10)
plt.ylim(-10,10)
plt.show()

在此处输入图像描述 但是,如果我在 3D 中尝试相同的方法,我会得到回溯

def objective(x, y, a, b, c):
    return a * x + b * y**2 + c
popt, _ = curve_fit(objective, x, y, z)
TypeError: objective() takes 5 positional arguments but 14884 were given

任何人都可以请给我一些提示吗?非常感谢您的时间和大力支持。

真挚地

威尔逊

4

1 回答 1

1

该函数curve_fit可用于多维曲线,但不能像您那样调用。

所有的自变量都应该在xdata. 例如:

In [121]: data.shape
Out[121]: (1000, 3)
In [122]: f = lambda x,a,b,c,d: a*x[0]**2 +b*x[1]**2 + c*x[0]*x[1]+d
In [123]: curve_fit(f, data[:, :2].T, ydata=data[:, 2])

这里我所有的数据都在一个数组中,我分别输入自变量和因变量。

于 2021-01-15T07:09:56.057 回答