Question: Using the code below, 1. Calculate the loss using mean squared error loss = average ( sum (prediction - y) 2 ) for all the
Using the code below,
1. Calculate the loss using mean squared error loss = average ( sum (prediction - y)2 ) for all the training samples after the model was selected.
2. Calculate the loss using mean squared error loss = average ( sum (prediction - y)2 ) for all the testing samples after the model was selected and used for testing data predictions.
code:
import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeatures
m = 500 np.random.seed(seed=5) X = 6 * np.random.random(m).reshape(-1, 1) - 3 y = 0.5 * X**5 -X**3- X**2 + 2 + 5*np.random.randn(m, 1)
for deg in [2, 5, 8, 10, 20]: poly = PolynomialFeatures(degree=deg) X_poly = poly.fit_transform(X) #creating polynomial feature array as per the degree X_train, X_test, y_train, y_test = train_test_split(X_poly, y, test_size=0.4, random_state=5)
model = LinearRegression() model.fit(X_train,y_train) y_pred = model.predict(X_test) plt.scatter(X_test[:,1],y_test,alpha=0.3) #plotting actual test data plt.scatter(X_test[:,1],y_pred,alpha=0.5) #plotting predicted values plt.legend(["Actual y_test",f"prediction with degree={deg}"]) plt.xlabel("X") plt.ylabel("y") plt.show()
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
