简体   繁体   English

如何使用 sklearn 适应更复杂的功能?

[英]How to fit more complex funtions with sklearn?

I used sklearn in python to fit polynomial functions:我在 python 中使用 sklearn 来拟合多项式函数:

 from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression poly = PolynomialFeatures(degree=2, include_bias=False) poly_reg_model = LinearRegression() poly_features = poly.fit_transform(xvalues.reshape(-1, 1)) poly_reg_model.fit(poly_features, y_values) final_predicted = poly_reg_model.predict(poly_features)...

Instead of only using x^n parts, I want to incude a (1-x^2)^(1/2) part in the fit-function.我不想只使用 x^n 部分,而是想在拟合函数中包含 (1-x^2)^(1/2) 部分。 Is this possible with sklearn? sklearn可以吗?

I tried to define a Feature which includes more complex terms but I falied to achieve this.我试图定义一个包含更复杂术语的功能,但我未能实现这一点。

No idea whether it is possible within scikitlearn - after all polynomial fit is constrained to specific polynomial formulations from the mathematical stanndpoint.不知道在 scikitlearn 中是否可行——毕竟从数学的角度来看,多项式拟合被限制为特定的多项式公式。 If you want to fit a formula with some unknown parameters, you can use scipy.optimize.curve_fit .如果你想用一些未知参数拟合一个公式,你可以使用scipy.optimize.curve_fit First let us generate some dummy data with noise:首先让我们生成一些带有噪声的虚拟数据:

import numpy as np 
from matplotlib import pyplot as plt

def f(x):
    return (1-x**2)**(1/2)

xvalues = np.linspace(-1, 1, 30)
yvalues = [f(x) + np.random.randint(-10, 10)/100 for x in xvalues]

Then, we set up our function to be optimized:然后,我们设置要优化的函数:

from scipy.optimize import curve_fit

def f_opt(x, a, b):
    return (a-x**2)**(1/b)

popt, pcov = curve_fit(f_opt, xvalues, yvalues)

You can of course modify this function to be more elastic.您当然可以修改此功能以使其更具弹性。 Finally we plot the results最后我们绘制结果

plt.scatter(xvalues, yvalues, label='data')
plt.plot(xvalues, f_opt(xvalues, *popt), 'r-', label='fit')
plt.legend()

优化函数的拟合

So now you can use f_opt(new_x, *popt) to predict new points (alternatively you can print the values and hard-code them).所以现在您可以使用f_opt(new_x, *popt)来预测新点(或者您可以打印值并对其进行硬编码)。 popt basically has the parameters that you specify in f_opt except x - for more details check the documentation I've linked! popt基本上具有您在f_opt中指定的参数,除了x - 有关更多详细信息,请查看我链接的文档!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM