Skip to main content
 首页 » 编程设计

python之我可以对 sklearn 进行对数回归吗

2025年05月04日11powertoolsteam

我不知道“对数回归”是否是正确的术语,我需要在我的数据上拟合一条曲线,就像一条多项式曲线,但最后是平坦的。

这是一张图片,蓝色曲线是我的(二阶多项式回归),洋红色曲线是我需要的。

我搜索了很多都找不到,只有线性回归,多项式回归,但没有在sklearn上进行对数回归。我需要绘制曲线,然后使用该回归进行预测。

编辑

这是我发布的绘图图像的数据:

x,y 
670,75 
707,46 
565,47 
342,77 
433,73 
472,46 
569,52 
611,60 
616,63 
493,67 
572,11 
745,12 
483,75 
637,75 
218,251 
444,72 
305,75 
746,64 
444,98 
342,117 
272,85 
128,275 
500,75 
654,65 
241,150 
217,150 
426,131 
155,153 
841,66 
737,70 
722,70 
754,60 
664,60 
688,60 
796,55 
799,62 
229,150 
232,95 
116,480 
340,49 
501,65 

请您参考如下方法:

如果我没理解错的话,你想用像 y = a * exp(-b * (x - c)) + d 这样的函数来拟合数据。

我不确定 sklearn 是否可以做到。但是您可以使用 scipy.optimize.curve_fit() 来使用您定义的任何函数来拟合数据。(scipy):

对于您的情况,我对您的数据进行了实验,结果如下:

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit 
 
my_data = np.genfromtxt('yourdata.csv', delimiter=',') 
my_data = my_data[my_data[:,0].argsort()] 
xdata = my_data[:,0].transpose() 
ydata = my_data[:,1].transpose() 
 
# define a function for fitting 
def func(x, a, b, c, d): 
    return a * np.exp(-b * (x - c)) + d 
 
init_vals = [50, 0, 90, 63] 
# fit your data and getting fit parameters 
popt, pcov = curve_fit(func, xdata, ydata, p0=init_vals, bounds=([0, 0, 90, 0], [1000, 0.1, 200, 200])) 
# predict new data based on your fit 
y_pred = func(200, *popt) 
print(y_pred) 
 
plt.plot(xdata, ydata, 'bo', label='data') 
plt.plot(xdata, func(xdata, *popt), '-', label='fit') 
plt.xlabel('x') 
plt.ylabel('y') 
plt.legend() 
plt.show() 

我发现 b 的初始值对于拟合至关重要。我为它估计了一个小范围,然后拟合数据。

如果你对x和y之间的关系没有先验知识,你可以使用sklearn提供的回归方法,如线性回归,核岭回归(KRR )、最近邻回归、高斯过程回归等来拟合非线性数据。 Find the documentation here