Open In App

How To Build Decision Tree in MATLAB?

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

MATLAB is a numerical and programming computation platform that is primarily used for research, modeling, simulation, and analysis  in academics, engineering, physics, finance, and biology. MATLAB, which stands for “MATrix LABoratory,” was first trying out typical tasks such as matrices operations, linear algebra, and  signal processing

It has additional use in artificial intelligence, deep learning, and machine learning, and it contains a variety of toolboxes for certain applications including control systems, optimization, and image processing.

How to build a decision tree in MATLAB?

  • For this demonstration, we make use of the MATLAB dataset fisheriris which is pre-defined.
  • The fisheriris dataset comprises measurements of iris flowers.
  • PetalLength and PetalWidth are the two parameters we choose to act as predictors, and then we develop a categorical response variable depending on the iris species.
  • Then, use cvpartition function to divide the data into training and testing sets.
  • In order to predict the class labels of the test data, first utilize the training data to build a decision tree using the fitctree function.
  • The classification accuracy is then calculated by contrasting the anticipated labels with the actual labels of the test data.

Example 1:

Matlab




% Loading the Iris dataset.
load fisheriris
 
% Splitting the data into training and testing.
 
cv = cvpartition(species,'HoldOut',0.3);
Xtrain = meas(cv.training,:);
Ytrain = species(cv.training);
Xtest = meas(cv.test,:);
Ytest = species(cv.test);
 
% Training the decision tree model.
tree = fitctree(Xtrain, Ytrain);
 
% Viewing the decision tree.
view(tree,'Mode','graph');
 
% Predicting the classes of the testing set.
Ypred = predict(tree, Xtest);
 
% Calculate the accuracy of the model.
 
accuracy = sum(Ypred == Ytest)/length(Ytest);
disp(['Accuracy: ' num2str(accuracy)]);


Output:

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads