- 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 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Meet
2024년 9월 5일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Linear Regression에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!