Certainly! Here's an example of MATLAB code that demonstrates how to fit a decision tree model to a given dataset. I'll assume you have a dataset loaded into MATLAB with variables X representing your feature matrix and Y representing your labels. In this example, X is an n x m matrix where n is the number of observations and m is the number of features, while Y is a column vector of length n.
% Load your dataset here
% For example, you might load it from a CSV file:
% data = readtable('your_data.csv');
% X = data(:, 1:end-1);
% Y = data(:, end);
% Split the dataset into training and testing sets
cv = cvpartition(size(X,1),'HoldOut',0.2); % Hold out 20% of the data for testing
idx = cv.test;
% Separate to training and test data
XTrain = X(~idx,:);
YTrain = Y(~idx,:);
XTest = X(idx,:);
YTest = Y(idx,:);
% Fit a decision tree model to the training data
treeModel = fitctree(XTrain, YTrain);
% View the tree
view(treeModel, 'Mode', 'graph');
% Predict the labels of the test set
YPred = predict(treeModel, XTest);
% Calculate the accuracy of the model
accuracy = sum(YTest == YPred) / length(YTest);
fprintf('Accuracy of the decision tree model: %.2f%%\n', accuracy * 100);
% Optional: Perform cross-validation
cvModel = crossval(treeModel, 'KFold', 10); % 10-fold cross-validation
cvResults = kfoldLoss(cvModel, 'LossFun', 'ClassifError');
fprintf('10-fold cross-validation error: %.2f%%\n', cvResults * 100);
Please note that you'll need to replace 'your_data.csv' with the path to your actual CSV file and adjust the data loading part to match your dataset structure. The code above performs the following steps:
- Loads the dataset (you would need to customize this part).
- Partitions the dataset into training and testing sets.
- Trains a decision tree model on the training set.
- Visualizes the trained decision tree.
- Predicts labels for the testing set.
- Calculates and prints the accuracy of the model.
- (Optional) Performs k-fold cross-validation to estimate the performance of the model.
Make sure you have the MATLAB Statistics and Machine Learning Toolbox installed to run this code, as it provides the fitctree function and other necessary tools for machine learning.