linear regression model to train the model. I would request interested readers to go through the article for the explanation of the above code (Polynomial Regression using the sklearn Python library)
In this article, we will use a pipeline to do the same. A pipeline sequentially applies a list of transforms and a final estimator. The intermediate steps of a pipeline are transforms and these transformers must implement fit and transform methods. The final estimator only needs to implement the fit method.
So, we will use a pipeline to combine the above mentioned two steps – creating additional features using the PolynomialFeatures class and passing the features to a linear regression model. We can use the following Python code for that purpose:
import seaborn
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.pipeline import Pipeline
df = seaborn.load_dataset("mpg")
print(df.head())
df = df.dropna()
X_train, X_test, y_train, y_test = train_test_split(df[["horsepower"]], df["mpg"], train_size=0.8, shuffle=True, random_state=1)
pipeline = Pipeline([("polynomial_features", PolynomialFeatures(degree=2, include_bias=False)), ("linear_regressor", LinearRegression())])
pipeline.fit(X_train, y_train)
y_test_predicted = pipeline.predict(X_test)
r2 = r2_score(y_test, y_test_predicted)
rmse = mean_squared_error(y_test, y_test_predicted, squared=False)
print("R2: ", r2)
print("RMSE: ", rmse)
Please note that the pipeline is used to combine two steps. Firstly, we the create the polynomial features and then, the polynomial features are passed to a linear regression model.
pipeline = Pipeline([("polynomial_features", PolynomialFeatures(degree=2, include_bias=False)), ("linear_regressor", LinearRegression())])
The pipeline.fit() method is used to learn from the dataset. And then pipeline.predict() is used to make predictions on the …








































0 Comments