File Exchange

image thumbnail

Machine Learning Made Easy

version (270 KB) by

MATLAB files from the webinar

14 Ratings



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 (41)

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


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)


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)

Shashank Prasanna

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
MATLAB 8.5 (R2015a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video