How to train and test linear regression model.

8 views (last 30 days)
priyanka
priyanka on 6 Oct 2021
Answered: Meet on 5 Sep 2024
I have an excel file with 10 column and need to use 3 column train a linear regression model and then to test it. how to train and test a linear regression model.

Answers (1)

Meet
Meet on 5 Sep 2024
Hi Priyanka,
You can perform the following steps to load data, train and test a linear regression model:
  1. Load the data using “readtable” function.
  2. Select the features you want to use out of all the features in the dataset.
  3. Handle missing values in the dataset if any.
  4. Split the data into train and test.
  5. Train the linear regression model using “fitlm” function.
  6. Test the model using the “predict” function.
% You can load your csv file here, in this case I am attaching publicly
% available airlinesmall dataset
data = readtable('airlinesmall.csv');
% Out of your 10 columns/variables you can select any of them you want to
% choose
features = data{:, {'Year', 'Month', 'DayofMonth'}};
target = cellfun(@str2double, data.ArrDelay);
% Handle missing data by removing rows with NaNs if any in your dataset
nanRows = any(isnan(features), 2) | any(isnan(target), 2);
% Removing rows with NaNs
features = features(~nanRows, :);
target = target(~nanRows);
% Split the data into training and testing sets
n = size(features, 1);
idx = randperm(n);
trainIdx = idx(1:round(0.8 * n));
testIdx = idx(round(0.8 * n) + 1:end);
trainFeatures = features(trainIdx, :);
trainTarget = target(trainIdx);
testFeatures = features(testIdx, :);
testTarget = target(testIdx);
% Train the linear regression model
mdl = fitlm(trainFeatures, trainTarget);
% Display the model summary
disp(mdl);
% Test the model on the test set
predictions = predict(mdl, testFeatures);
% Calculate performance metrics
mse = mean((predictions - testTarget).^2);
disp(['Mean Squared Error on Test Set: ', num2str(mse)]);
You can refer to the resources below for more information:

Products


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!