Artificial Intelligence 5 min read
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
Import libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegressionLoad 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.
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 contactand we will review it promptly.
Reader feedback
How this landed with the community
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
