After that, the polynomial regressor needs to be trained. We have previously transformed X_train into X_train_transformed using the polynomial_features.fit_transform() method. So, now, we will use polynomial_regression.fit(X_train_transformed, y_train) to train the model.
After training the model, we can use the same model on the test dataset and see its performance.
X_test_transformed = polynomial_features.transform(X_test) y_test_predicted = polynomial_regression.predict(X_test_transformed)
Here, we are first transforming X_test into X_test_transformed using polynomial_features.transform(X_test). And then the model uses X_test_transformed to predict the y values of the test dataset.
So, how did the model perform? We will first see a graph that shows the polynomial regression line and the scatterplot between the mpg and the horsepower variables. But, to do so, we need to sort the X_test values based on horsepower.
df2 = pandas.DataFrame(list(zip(X_test['horsepower'], y_test, y_test_predicted)), columns=['horsepower', 'actual_mpg', 'predicted_mpg'])
df2.sort_values(by=['horsepower'], inplace=True)
print(df2.head())
pyplot.scatter(df["horsepower"], df["mpg"])
pyplot.xlabel("Horsepower")
pyplot.ylabel("MPG")
pyplot.plot(df2['horsepower'], df2['predicted_mpg'], color="red")
pyplot.savefig("poly-regression-final.png")
pyplot.close()
So, we are first creating a DataFrame with horsepower, actual mpg from the test set, and the predicted mpg from the test set. After that, the rows of the dataset are sorted based on horsepower. Now, we can plot the predicted mpg with the horsepower and see the polynomial regression line.

We can also calculate the R-squared score and the Root Mean Squared Error of the model…








































0 Comments