design the function function out = mse_vs_m(x_tr, t_tr, x_te, t_te) that uses all given samples in the split data setsand then computes the empirical 5 mse test loss in matlab

Here's a possible implementation of the mse_vs_m function in MATLAB:

main.m
function out = mse_vs_m(x_tr, t_tr, x_te, t_te)
% Calculates the mean squared error for different model complexities
% using a training set and a testing set

% Number of samples in the training set
n_tr = size(x_tr, 1);

% Number of samples in the testing set
n_te = size(x_te, 1);

% Maximum model complexity (adjust as needed)
M = 10;

% Preallocate arrays to store the MSE values
mse_train = zeros(M, 1);
mse_test = zeros(M, 1);

for m = 0:M-1
    % Fit a polynomial regression model of degree m to the training data
    X_tr = [ones(n_tr, 1), x_tr.^1, x_tr.^2, ..., x_tr.^m];
    w = (X_tr' * X_tr) \ (X_tr' * t_tr);
    
    % Evaluate the model on the training set and calculate the MSE
    y_tr = X_tr * w;
    mse_train(m+1) = mean((y_tr - t_tr).^2);
    
    % Evaluate the model on the testing set and calculate the MSE
    X_te = [ones(n_te, 1), x_te.^1, x_te.^2, ..., x_te.^m];
    y_te = X_te * w;
    mse_test(m+1) = mean((y_te - t_te).^2);
end

% Store the results in a struct
out = struct('mse_train', mse_train, 'mse_test', mse_test);
1053 chars
35 lines

The function takes four input arguments:

  • x_tr is a column vector with the input values for the training set
  • t_tr is a column vector with the target values for the training set
  • x_te is a column vector with the input values for the testing set
  • t_te is a column vector with the target values for the testing set

It returns a struct with two fields:

  • mse_train is a column vector with the MSE values for the training set, as a function of the model complexity (polynomial degree)
  • mse_test is a column vector with the MSE values for the testing set, as a function of the model complexity

The function uses polynomial regression to fit models of increasing complexity to the training set, and evaluates their performance on both the training and testing sets using the MSE metric. The results are stored in the output struct, which you can plot or analyze further as needed.

gistlibby LogSnag