Hi here's code that I have written which you will need: Problem to be solved: 3.3 Plot…
- User
Hi here's code that I have written which you will need:
Problem to be solved: 3.3 Plot the two models: w(λ = 0) and w(λ∗) over the range 0 ≤ x ≤ 1. The five models can be averaged: w=np.mean(w, axis=0).
Code:
Load the models
w_lambda_0 = np.load("w_lambda_0.npy") w_lambda_star = np.load("w_lambda_star.npy")
Generate predictions for the plot range
x_plot = np.linspace(0, 1, 100) X_plot_poly = polynomial_basis(x_plot, degree)
y_pred_lambda_0 = X_plot_poly @ w_lambda_0 y_pred_lambda_star = X_plot_poly @ w_lambda_star
Plot both models
plt.plot(x_plot, y_pred_lambda_0, label="w(λ=0)") plt.plot(x_plot, y_pred_lambda_star, label=f"w(λ={best_lambda:.2e})") plt.legend() plt.xlabel('x') plt.ylabel('f(x)') plt.title('Comparison of Models') plt.show()
now for 3.4 we must:
3.4 Evaluate the two models with “test.npz” and report the two test MSEs.
I need help writing code to do that
- Assistant
To evaluate the two models using a test dataset and report the Mean Squared Errors (MSEs), you will need to follow these steps:
- Load the test data from the "test.npz" file.
- Use the polynomial basis function to transform the test data into the appropriate form for prediction.
- User
Great!!! You got it now the final steps:
3.5 Write the code “ols regresssion largeset.py” to implement a regression model with “train 1000.npz” without any regularization and cross validation. Plot the model over the range 0 ≤ x ≤ 1.
3.6. Based on your answers in 3.3, 3.4, and 3.5, please provide two possible solutions to control the effective complexity in machine learning.
For 3.5 you will find useful:
import numpy as np from sklearn.model_selection import KFold
Load train data
train_x = np.load("train.npz")["x"] train_y = np.load("train.npz")["y"]
Create polynomial basis function (x, x^2, ..., x^9)
def polynomial_basis(x, degree): return np.vstack([x**d for d in range(degree + 1)]).T
MMSE regression function
def mmse_regression(X, y): return np.linalg.inv(X.T @ X) @ X.T @ y
5-fold cross-validation
def cross_val_error(X, y, degree, k=5): kf = KFold(n_splits=k) errors = []
code - Assistant