How to extract equation from a polynomial fit?

2024/10/11 0:25:58

My goal is to fit some data to a polynomial function and obtain the actual equation including the fitted parameter values.

I adapted this example to my data and the outcome is as expected.

Here is my code:

import numpy as np
import matplotlib.pyplot as pltfrom sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipelinex = np.array([0., 4., 9., 12., 16., 20., 24., 27.])
y = np.array([2.9,4.3,66.7,91.4,109.2,114.8,135.5,134.2])x_plot = np.linspace(0, max(x), 100)
# create matrix versions of these arrays
X = x[:, np.newaxis]
X_plot = x_plot[:, np.newaxis]plt.scatter(x, y, label="training points")for degree in np.arange(3, 6, 1):model = make_pipeline(PolynomialFeatures(degree), Ridge())model.fit(X, y)y_plot = model.predict(X_plot)plt.plot(x_plot, y_plot, label="degree %d" % degree)plt.legend(loc='lower left')plt.show()

enter image description here

However, I now don't know where to extract the actual equation and fitted parameter values for the respective fits. Where do I access the actual fitted equation?

EDIT:

The variable model has the following attributes:

model.decision_function  model.fit_transform      model.inverse_transform  model.predict            model.predict_proba      model.set_params         model.transform          
model.fit                model.get_params         model.named_steps        model.predict_log_proba  model.score              model.steps

model.get_params does not store the desired parameters.

Answer

The coefficients of the linear model are stored in the intercept_ and coeff_ attributes of the model.

You can see this more clearly by turning-down the regularization and feeding-in a known model; e.g.

import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeaturesx = 10 * np.random.random(100)
y = -4 + 2 * x - 3 * x ** 2model = make_pipeline(PolynomialFeatures(2), Ridge(alpha=1E-8, fit_intercept=False))
model.fit(x[:, None], y)
ridge = model.named_steps['ridge']
print(ridge.coef_)
# array([-4.,  2., -3.])

Also note that the PolynomialFeatures by default includes a bias term, so fitting the intercept in Ridge will be redundant for small alpha.

https://en.xdnf.cn/q/69831.html

Related Q&A

python dictionary conundrum

On the console I typed in>>> class S(str): pass ... >>> a = hello >>> b = S(hello) >>> d = {a:a, b:b} >>> d {hello: hello} >>> type(d[a]) <class…

Celery 4 not auto-discovering tasks

I have a Django 1.11 and Celery 4.1 project, and Ive configured it according to the setup docs. My celery_init.py looks likefrom __future__ import absolute_importimport osfrom celery import Celery# set…

Is it possible to use a custom filter function in pandas?

Can I use my helper function to determine if a shot was a three pointer as a filter function in Pandas? My actual function is much more complex, but i simplified it for this question.def isThree(x, y…

what is request in Django view

In the Django tutorial for the first app in Django we havefrom django.http import HttpResponsedef index(request):return HttpResponse("Hello, world. Youre at the polls index.")And then the url…

Cannot update python package on anaconda to latest version

Some of my python packages on anaconda cannot be updated to the latest version.For instance, beautifulsoup4 latest version on anaconda is v4.71 as seen in the release notes. https://docs.anaconda.com/a…

How does tensorflow.pad work?

There is the example of tensorflow.pad():# t = is [[1, 2, 3], [4, 5, 6]]. # paddings is [[1, 1,], [2, 2]]. # rank of t is 2.tf.pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],[…

Installing PyPotrace on Windows 10

I would like to install Potrace on my Windows 10 Computer and I will be using it with python 2.7.5. I am following the installation instruction from this site.( https://pypi.python.org/pypi/pypotrace) …

dateutil 2.5.0 is the minimum required version

Im running the jupyter notebook (Enthought Canopy python distribution 2.7) on Mac OSX (v 10.13.6). When I try to import pandas (import pandas as pd), I am getting the complaint: ImportError: dateutil …

pytest fixture - get value and avoid error Fixture X called directly

I have updated pytest to 4.3.0 and now I need to rework test code since calling fixtures directly is deprecated. I have an issue with fixtures used in an unittest.TestCase, how do I get the value retur…

Django limit the number of requests per minute

Im trying to limit the number of requests from an IP in case I get too many requests from it. For example: if I will get more than 50 requests per minute I want to block that IP for 5 minutes. When I u…