Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I'm trying to plot the polynomial regression but my code is making outputting what looks like red scribbles instead of a red curve. Here is

I'm trying to plot the polynomial regression but my code is making outputting what looks like red scribbles instead of a red curve.

Here is my code:

import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error

m = 500 np.random.seed(seed=5)

# 1. Generate 500 random X values from -3 to 3. X = 6 * np.random.random(m).reshape(-1, 1) - 3 # generate x

# 2. Generate 500 Y values using distribution "y=0.5*X5 - X3 - X2 +2+a little bit randomness (both positive and negative) " y = 0.5 * X**5 -X**3- X**2 + 2 + 5*np.random.randn(m, 1) # generate y

# 3. Use X and Y as the whole dataset and use 200 samples as testing + 300 samples as training. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40, random_state=42)

# 4. Try Linear Regression and Polynomial Regression (PolynomialFeatures + LinearRegression) in SKLearn from degree 2 to 25 to fit the training data samples. # Linear regression model reg1 = LinearRegression() reg1.fit(X_train, y_train) # train the model y_pred1 = reg1.predict(X_test) # do the prediction

#polynomial regression model degree=5 reg2 = LinearRegression() poly2_features = PolynomialFeatures(degree=degree, include_bias = False) X_poly2 = poly2_features.fit_transform(X_train) X_poly2_test = poly2_features.fit_transform(X_test) reg2.fit(X_poly2, y_train) y_pred2 = reg2.predict(X_poly2_test)

#calclulate the mean squared loss score1 = mean_squared_error(y_test, y_pred1) # loss for linear regression model score2 = mean_squared_error(y_test, y_pred2) # loss for polynomial regression model print(score1) # print linear regression loss print(score2) # print polynomial loss

plt.scatter(X_test, y_test, color='black') plt.plot(X_test, y_pred1, color='blue', linewidth=3) plt.plot(X_test, y_pred2, color='red', linewidth=3)

plt.show()

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Machine Learning And Knowledge Discovery In Databases European Conference Ecml Pkdd 2014 Nancy France September 15 19 2014 Proceedings Part I Lnai 8724

Authors: Toon Calders ,Floriana Esposito ,Eyke Hullermeier ,Rosa Meo

2014th Edition

3662448475, 978-3662448472

Students also viewed these Databases questions