How to Build and Visualize Polynomial Regression in Python

This article walks through loading CSV data, fitting both linear and degree‑6 polynomial regression models with scikit‑learn, and visualizing the original points, fitted lines, and predictions on test data using matplotlib.

YiSu Grain
YiSu Grain
YiSu Grain
How to Build and Visualize Polynomial Regression in Python

Import libraries

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

Load and visualize data

data = np.genfromtxt("job.csv", delimiter=",")
x_data = data[1:, 1]
y_data = data[1:, 2]
plt.scatter(x_data, y_data)
plt.show()

Reshape for scikit-learn

x_data = x_data[:, np.newaxis]
y_data = y_data[:, np.newaxis]

Linear regression

model = LinearRegression()
model.fit(x_data, y_data)
plt.plot(x_data, y_data, 'b.')
plt.plot(x_data, model.predict(x_data), 'r')
plt.show()

Polynomial regression (degree 6)

poly_reg = PolynomialFeatures(degree=6)
x_poly = poly_reg.fit_transform(x_data)
lin_reg = LinearRegression()
lin_reg.fit(x_poly, y_data)
plt.plot(x_data, y_data, 'b.')
plt.plot(x_data, lin_reg.predict(poly_reg.fit_transform(x_data)), c='r')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

Prediction on a dense test grid

x_test = np.linspace(1, 10, 100)
x_test = x_test[:, np.newaxis]
plt.plot(x_data, y_data, 'b.')
plt.plot(x_test, lin_reg.predict(poly_reg.fit_transform(x_test)), c='r')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData VisualizationLinear Regressionscikit-learnPolynomial Regression
YiSu Grain
Written by

YiSu Grain

A fleeting mayfly in the world, a single grain in the boundless sea.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.