- Load the data using “readtable” function.
- Select the features you want to use out of all the features in the dataset.
- Handle missing values in the dataset if any.
- Split the data into train and test.
- Train the linear regression model using “fitlm” function.
- Test the model using the “predict” function.
How to train and test linear regression model.
8 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
Meet
on 5 Sep 2024
Hi Priyanka,
You can perform the following steps to load data, train and test a linear regression model:
% 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:
0 Comments
See Also
Categories
Find more on Linear Regression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!