File Exchange

image thumbnail

Machine Learning Made Easy

version (270 KB) by Shashank Prasanna
MATLAB files from the webinar


Updated 01 Sep 2016

View License

These files accompany the 'Machine Learning Made Easy' webinar which can be viewed here:
About the webinar:
Machine learning is ubiquitous. From medical diagnosis, speech, and handwriting recognition to automated trading and movie recommendations, machine learning techniques are being used to make critical business and life decisions every moment of the day. Each machine learning problem is unique, so it can be challenging to manage raw data, identify key features that impact your model, train multiple models, and perform model assessments.
In this session we explore the fundamentals of machine learning using MATLAB®.
Highlights include:
• Accessing, exploring, analyzing, and visualizing data in MATLAB
• Using the Classification Learner app and functions in the Statistics and Machine Learning Toolbox® to perform common machine learning tasks such as:
o Feature selection and feature transformation
o Specifying cross-validation schemes
o Training a range of classification models, including support vector machines (SVMs), boosted and bagged decision trees, k-nearest neighbor, and discriminant analysis
o Performing model assessment and model comparisons using confusion matrices and ROC curves to help choose the best model for your data
• Integrating trained models into applications such as computer vision, signal processing, and data analytics.

Comments and Ratings (66)

Ben Wong

The detection graph is static and the labels are showing "N/A" !
Can anyone help solve this issue?

Hi everyone,
Some people have problems with 'ClassNames' the solution is to use the subclass 'ClassificationKNN' as follows:

bar (ax2, zeros (1, numel (trainedClassifier.ClassificationKNN.ClassNames)), 'FaceColor', [0.2 0.6 0.8])

Likewise the other lines:

% Step 3: Predict car using extracted features
[imagepred, probabilities] = predict (trainedClassifier.ClassificationKNN, imagefeatures);

function cname = getClassifierName (trainedClassifier)
% getClassifierName extracts name from the classifier from a trained model
cname = class (trainedClassifier.ClassificationKNN);
if isa (trainedClassifier.ClassificationKNN, 'ClassificationECOC')
     cname = 'SVM';

Also when we are going to compare 2 objects it is necessary to add ". ClassificationSVM" where necessary.

Greetings from Colombia!

Pedram Asef

Hi there,
Regarding the code of the human activity code. I could successfully import my trained model in the workspace. However, when I "run section" the last part of the code to predict based on the model, the detection graph is constant and the labels are showing "N/A" !
Can anyone help on this issue?


Ni (view profile)

Hi Girish,

How did you solve the still image problem at the last step for the testing data?


Yeoh Lipp

Hi Mr. Shashank Prasanna
I am currently facing these problem when i'm running your codes, and i have absolutely no idea what it meant.
Would you mind helping me ?

Reference to non-existent field 'ClassNames'.

Error in CarFinderLive>figureSetup (line 54)
bar(ax2,zeros(1,numel(trainedClassifier.ClassNames)),'FaceColor',[0.2 0.6 0.8])

Error in CarFinderLive (line 6)
[fig, ax1, ax2] = figureSetup(trainedClassifier);

I got it. from Edoardo Cerini

Hi people. Does someone solved the still image problem. Am struck in that process. If someone does please comment it??


Gael Gelis

@Peter Kongstad
Hi !

Did you manage to fix this problem?
I am in the same situation...

Thanks a lot

After running the Human_Activity_Learning.m file, the result of plotActivityResults is still image. 
How can i do it to solve the problem. and i'm using R2016b 

My e-mail:

Thanks a lot

How can someone save the work done on the classification app and then re use it back from where it was left, i am not able to see any save option of the classifier window changes we made.


Ahmed Gad

Data used in the code can be downloaded using the downloadSensorData.m file located inside the HumanActivity folder.
At all, the dataset can be downloaded from this link:

choi jin tae

Dear Shashank Prasanna or Everyone

After running the Human_Activity_Learning.m file, the result of plotActivityResults is still image.
How can i do it to solve the problem. and i'm using R2016b

My e-mail:

Thanks a lot

huajun Lei

haiting zhao

Ali Kasaee

Hi Shashank,
Thanks for your tutorial, it helps me much.
Unfortunately, I cannot find any data for car identifier code, May you please help me how solve the problem?
My email is


Zoe (view profile)

Can this be used for prediction/regression or is it just classification?

Kiet Pham

Hi.. Khurshid Aliev
i can help you .. if you want me to help .. contact me at address email:

Dear Shashank Prasanna,

You have done very good tutorial. I really approcciate, If you could help us with following error:

Reference to non-existent field 'ClassNames'.

Error in CarFinderLive>figureSetup (line 54)
bar(ax2,zeros(1,numel(trainedClassifier.ClassNames)),'FaceColor',[0.2 0.6 0.8])

Error in CarFinderLive (line 6)
[fig, ax1, ax2] = figureSetup(trainedClassifier);

Error in CarIdentification (line 40)

If someone had the same problem and solved it,could you please share your experience.

Thanks in advance!

Peter Dallas

I cannot find the CarData Folder

where can i get the cardata folder?

Hansu Kim

Ruojun Li

I find that predict function need a 'classification' type input arguments. But in the machine learning app, the export model is structure type. Using the trainedmodel.classificationSVM(which depends the algorithm you use) to replace the trainedmodel in the activityresultplot function. That will help to understand the human activity code.

Ruojun Li

Hi, the expert there. I run the human activity learning code. It helps me much to understand the Machine Learning app. But the plotactivityresult doesn't work well. The Actual Activity and predicted activity are both NA. And the result is static, not active.

Keep getting an error that the ClassNames cant be found in the CarFinderLive.
bar(ax2,zeros(1,numel(trainedClassifier.ClassNames)),'FaceColor',[0.2 0.6 0.8])

Even when this is corrected with a specific path to the ClassNames Such as trainedClassifier.ClassifierSVM.ClassNames,
Then a new error occurs called out by "predict". Where it points to line 12 if I remember correct, which states "throw(E)".

I cant get this working even with using all your files.
Which is a shame, I really like this piece and would love to get it to work.

Adam Stephen

Surprised to find that the file manipulations are non-portable, assuming Windows path separator. Trivial to replace using string concatenation and the filesep construct, but irritating.


ycyyou (view profile)

Azmat Ali

Thanks Edoardo Cerini
its working
I love it

Amulya Patil

K. Kojima

K. Kojima

@Azmat Ali you are right. I solve the issue doing:
this happens since the exported data from classificationLearner with new versions of matlab is a struct (and not the was that was supposed with older versions), so the plot function is expecting "classificationKNN" but you send a struct.
export classificationKNN from the struct, and take that value as the input of the plot function. it will work

Azmat Ali

After running the code the final result is a still image.
same as
After executing the function : plotActivityResults(trainedClassifier,rawSensorDataTest,humanActivityData,0.1) ----------> it's showing still picture. I can't call loop.

I'm using Matlab 2016a, but I get these errors when I run the Human Activity Prediction Code.
please give me a solution to this

Undefined function or variable 'trainedClassifier'.

Error in Human_Activity_Learning (line 115)

the value of my trained model is struct 1*1, where as in the video it is ClassificationPredictor or ClassificationPrediction (it is not seen in the video).
how to convert or change the value of the trained model
i am using R2017a version.

Tsinghua THU

Robert Jukes

I have the same error too - have tried amending the code to access 'ClassNames' from trainedClassifier.classificationSVM.ClassNames but that doesn't work either.

I get the same error when executing the CarFinderLive function:

Reference to non-existent field 'ClassNames'.

Can't find any field with this name in the documentation, too. Is there a solution? Was this changed in any version of Matlab?

Peng Sun

Nevrus Kaja

I get the following errors when i run this :

Reference to non-existent field 'ClassNames'.

Error in TSR_LiveTestProbability>figureSetup (line 51)
bar(ax2,zeros(1,numel(trainedClassifier.ClassNames)),'FaceColor',[0.2 0.6 0.8])

Error in TSR_LiveTestProbability (line 4)
[fig, ax1, ax2] = figureSetup(trainedClassifier);

any help?

I have a shimmer 3D accelerator and software that write x,y,z axis data in dat file.I want to detect, real time activities detection where 128 readings/window (2.56 sec data) and 50% overlap like the dataset for human activity learning.please help me.
below code:

if ~exist('rawSensorData_train.mat','file') && ~exist('rawSensorData_test.mat','file')

load rawSensorData_train

rawSensorDataTrain = table(...
total_acc_x_train, total_acc_y_train, total_acc_z_train);

T_mean = varfun(@Wmean, rawSensorDataTrain);
T_stdv = varfun(@Wstd,rawSensorDataTrain);
T_pca = varfun(@Wpca1,rawSensorDataTrain);

humanActivityData = [T_mean, T_stdv, T_pca];
humanActivityData.activity = trainActivity;


load rawSensorData_test

rawSensorDataTest = table(...
total_acc_x_test, total_acc_y_test, total_acc_z_test);

T_mean = varfun(@Wmean, rawSensorDataTest);
T_stdv = varfun(@Wstd,rawSensorDataTest);
T_pca = varfun(@Wpca1,rawSensorDataTest);

humanActivityData = [T_mean, T_stdv, T_pca];
humanActivityData.activity = testActivity;


I have a shimmer 3D accelerator and software that write x,y,z axis data in dat file.I want to detect, real time activities detection where 128 readings/window (2.56 sec data) and 50% overlap like the dataset for human activity learning.please help me.

@ azza allouch : use this equation in excel for data arrange: =OFFSET($A$1,(ROW()-1)*128+INT((COLUMN()-3)),MOD(COLUMN()-3,1))

Just past any cell and can go across row randomly by dragging and again drag below. For 50% overlap just change 64 to 128.

sehla zayen

I am new in classification images and Matlab. I write a script to classify an image but i don't guess if i must use "image" or "image feature" as parameters in the "predict" function.
Must i use:
feature = double (encode (bag , img))
[labelIdx, scores] = predict(categoryClassifier, feature)


[labelIdx, scores] = predict(categoryClassifier, img)

Can you help me to understand the difference in results?

@ azza allouch --> knock me on my skype or e-mail. I'll try to help you.

skype id: iamfarhadbd

azza allouch

please anyone can help me

azza allouch

i have data collected from accelerometer at a constant rate of 50Hz.
can some one help me sampling in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window) like the dataset for human activity learning

@ Shariful Islam -- plotActivityResults.m, working.........Thanks a lot. Many many thanks, Shariful Islam bro

@Farhad Hossain- there needs some change inside the plotActivityResults.m

I modified this as below use this-

function plotActivityResults(mdl,rawSensorDataTest,humanActivityTest,delay)
% Use trained model to predict activity on new sensor data
% Copyright (c) 2015, MathWorks, Inc.
if nargin < 4
delay = 0.02;
g = 9.81; % in m/s^2
time = linspace(0,2.56,128);

fig = figure('Name','Human Activity Detection','NumberTitle','off','Visible','off');
fig.Position(3:4) = 600;
fig.Visible = 'on';

ax1 = subplot(2,1,1,'Parent',fig,'Xgrid','on','Ygrid','on',...
'XLim',[time(1) time(end)],'YLim',[-2*g 2*g]);
ax2 = subplot(2,1,2,'Parent',fig,'Xgrid','on','Ygrid','on',...
'XLim',[time(1) time(end)],'YLim',[-2 2]);
% axis(ax1,'square'), axis(ax2,'square')

clr = get(groot,'DefaultAxesColorOrder');
L(1) = line(time,g*rawSensorDataTest.total_acc_x_test(1,:),'color',clr(1,:),'Parent',ax1,'LineWidth',1.5,'DisplayName','Accelerometer X');
L(2) = line(time,g*rawSensorDataTest.total_acc_y_test(1,:),'color',clr(2,:),'Parent',ax1,'LineWidth',1.5,'DisplayName','Accelerometer Y');
L(3) = line(time,g*rawSensorDataTest.total_acc_z_test(1,:),'color',clr(3,:),'Parent',ax1,'LineWidth',1.5,'DisplayName','Accelerometer Z');

L(4) = line(time, rawSensorDataTest.body_gyro_x_test(1,:),'color',clr(4,:),'Parent',ax2,'LineWidth',1.5,'DisplayName','Gyroscope X');
L(5) = line(time, rawSensorDataTest.body_gyro_y_test(1,:),'color',clr(5,:),'Parent',ax2,'LineWidth',1.5,'DisplayName','Gyroscope Y');
L(6) = line(time, rawSensorDataTest.body_gyro_z_test(1,:),'color',clr(6,:),'Parent',ax2,'LineWidth',1.5,'DisplayName','Gyroscope Z');

xlabel(ax1,'Time (s)')
ylabel(ax1,'(Accelerometer Readings (m \cdot s^{-2})')
title(ax1,sprintf('Human Activity Mobile Sensor Data'));

xlabel(ax2,'Time (s)')
ylabel(ax2,'Gyroscope Readings rad \cdot sec{-1}')
title(ax2,['Classifier: ', getClassifierName(mdl)]);

ann1 = annotation(fig,'textbox',[ax1.Position(1:3) 0.04],...
'String','Predicted Activity : NA','FontSize',12,'FitBoxToText','off',...
'BackgroundColor',[0 0.7 0.3],'HorizontalAlignment','Center','VerticalAlignment','middle','FaceAlpha',0.5);
ann2 = annotation(fig,'textbox',[ax1.Position(1) ax1.Position(2)+0.04 ax1.Position(3) 0.04],...
'String','Actual Activity : NA','FontSize',12,'FitBoxToText','off',...
'BackgroundColor',[0 0.7 0.3],'HorizontalAlignment','Center','VerticalAlignment','middle','FaceAlpha',0.5);

%% Loop through the raw data and plot the sensor values
for ii = 600:height(humanActivityTest)
mycell1 = fieldnames(mdl);
myclassifier1 = strcat('mdl.',mycell1(3));
activity = predict(eval(myclassifier1{:}),humanActivityTest{ii,1:end-1});

if activity == humanActivityTest.activity(ii)
predclr = [0 0.7 0.3];
predclr = [1 0 0];
set(ann1,'String',['Predicted Activity : ' char(activity)],...
set(ann2,'String',['Actual Activity : ' char(humanActivityTest.activity(ii))],...
'BackgroundColor',[0 0.7 0.3]);

L(1).YData = g*rawSensorDataTest.total_acc_x_test(ii,:);
L(2).YData = g*rawSensorDataTest.total_acc_y_test(ii,:);
L(3).YData = g*rawSensorDataTest.total_acc_z_test(ii,:);

L(4).YData = rawSensorDataTest.body_gyro_x_test(ii,:);
L(5).YData = rawSensorDataTest.body_gyro_y_test(ii,:);
L(6).YData = rawSensorDataTest.body_gyro_z_test(ii,:);

catch err

function cname = getClassifierName(trainedClassifier)
mycell = fieldnames(trainedClassifier);
cname = mycell(3);

Shashank Prasanna, pls help me

After executing the function : plotActivityResults(trainedClassifier,rawSensorDataTest,humanActivityData,0.1) ----------> it's showing still picture. I can't call loop.
Someone pls help me...........

I can't run "Human_Activity_Learning". Showing error: Error in saveSensorDataAsMATFiles (line 16)
trainActivity = categorical(importdata('UCI HAR

please help me

very good tutorial!
easy to use and get fast results

Thank you for your tutorial! I want to plot ROC curve after training. How can I make it after applying

yfit = trainedClassifier1.predictFcn(T);


Thank you for sharing this tutorial,
I am going to implement the same concept that you did, but I am going to recognize different activities. they are walking, sitting, standing, running and fall down.

So, can I load my sensor data of tri-accelerometer files into your code to classify the activities?

I really need your help
Fatimah Mohammed


HAJI (view profile)

i am trying to implement car finder code on real car data. [code and demo is provided in "machine learning made easy" webinar] i am facing the problem that after using classification learner app my classifier is exported as struct (it is supposed to be exported as classification object) .this problem is addressed in bug report.
but i am still unable to solve the problem.
should i try to export classifier by option "generate code" and then where i am supposed to change the code
For example, change this R2015a code:

yfit = predict(trainedClassifier,T{:,trainedClassifier.PredictorNames})

To this R2015b code:

yfit = trainedClassifier.predictFcn(T)


HAJI (view profile)

Basti Borsti

Hey i would like to work with your "SearchPattern" function but unfortunately i can not download your test data.

504 Gateway Time-out
The server didn't respond in time.

Shi Shu

This is great! can I do feature selection tho? like SelectKBest or PCA?

Hi Shashank,
Thanks for your tutorial, it's helping me so much.
I meet a problem when I execute the function'saveSensorDataAsMATFiles' finding a error about 'No public field ReadSize exists for class'
I dont know what can solve it.
Could you tell you what method can solve it?
thanks you again^^.

Ilan Sinai

this is nice tool.
can i add new models and/or steps of my own to this tool ?
i.e. can we see the code that generated this tool?


korkam (view profile)

Soutrik, the examples in this submission are associated with the linked webinar and are classification only.
However, parametric and nonparametric regression tools are available in the Statistics and Machine Learning Toolbox.

Does it also have tools for regression-based problems ?


Updated license

Fixed the webinar video link

Added link to the webinar recording

Updated required products list

Updated required products

Updated formatting in the published script

MATLAB Release Compatibility
Created with R2015a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.

Learn About Live Editor