I have create uitable in Matlab with drop downmenu.
somehow the drop down menu doesn't get updated with switch/case
I tried substituting the switch/case with if else condition.
the drop down menu gets updated but it doesn't give me the desired output!
to simulate please run the code below
Any idea or pointers ?
function [] =foouitable()
f = figure('Position',[100 100 400 150]);
% Column names and column format
columnname = {'Available','Options','SubOptions'};
columnformat = {'logical','bank',{'CheckBox' 'SelectSubOptions'}};
% Define the data
d = {false 'Reconstruction' 'CheckBox';...
false 'Segmentation' 'CheckBox';...
false 'ComputerTomography' 'CheckBox';...
false, 'UltraSound', 'CheckBox';...
false, 'AcousticEmission', 'CheckBox'};
% Create the uitable
t = uitable('Data', d,...
'ColumnWidth', {70 120 100},...
'ColumnName', columnname,...
'ColumnFormat', columnformat,...
'ColumnEditable', [true false true],...
'RowName',[],...
'CellEditCallback',#edit)
set(t,'Tag','Config_table');
function edit(src,evt)
if evt.Indices(2) == 1
modifyPopup( src)
end
end
% Set width and height
t.Position(3) = t.Extent(3);
t.Position(4) = t.Extent(4);
function modifyPopup(src)
id_group_1 = {'A.1';'A.2';'A.3'};
id_group_2 = {'B.1';'B.2';'B.3'};
id_group_3 = {'C.1';'C.2';'C.3'};
id_group_4 = {'D.1';'D.2';'D.3'};
id_group_5 = {'E.1';'E.2';'E.3'};
id_default = {'CheckBox'};
config_data = get(src,'Data');
selector = config_data(1:5,1);
selector = cell2mat(selector);
config_format = get(src,'ColumnFormat');
if isequal(selector(1),1)
config_format{3} = id_group_1';
elseif isequal(selector(2),1)
config_format{3} = id_group_2';
elseif isequal(selector(3),1)
config_format{3} = id_group_3';
elseif isequal(selector(4),1)
config_format{3} = id_group_4';
elseif isequal(selector(5),1)
config_format{3} = id_group_5';
else
config_format{3} = id_default;
end
set(src,'Data',config_data);
set(src,'ColumnFormat',config_format);
end
end
Thanks in advance!
Thanks for the hint excaza. I implemented it
But the id_group_1 now consist of a 3x3 char array in one of its rows.
[1] 'Reconstruction' [3x3 char]
[0] 'Segmentation' 'CheckBox'
[0] 'ComputerTomography' 'CheckBox'
[0] 'UltraSound' 'CheckBox'
[0] 'AcousticEmission' 'CheckBox'
enter image description here
as set(src,'Data',config_data); does not permit a cell array. At the moment it seems like I cannot avoid using config_format inside the if/else condition!!
function modifyPopup(src)
id_group_1 = {true 'Reconstruction'...
['A.1'; 'A.2'; 'A.3'];...
false 'Segmentation' 'CheckBox';...
false 'ComputerTomography' 'CheckBox';...
false, 'UltraSound', 'CheckBox';...
false, 'AcousticEmission', 'CheckBox'};
id_group_2 = {false 'Reconstruction' 'CheckBox';...
true 'Segmentation' ['B.1'; 'B.2'; 'B.3'];...
false 'ComputerTomography' 'CheckBox';...
false, 'UltraSound', 'CheckBox';...
false, 'AcousticEmission', 'CheckBox'};
id_group_3 = {false 'Reconstruction' 'CheckBox';...
false 'Segmentation' 'CheckBox';...
true 'ComputerTomography'...
['C.1'; 'C.2'; 'C.3'];...
false, 'UltraSound', 'CheckBox';...
false, 'AcousticEmission', 'CheckBox'};
id_group_4 = {false 'Reconstruction' 'CheckBox';...
false 'Segmentation' 'CheckBox';...
false 'ComputerTomography' 'CheckBox';...
true, 'UltraSound',...
['D.1'; 'D.2'; 'D.3'];...
false, 'AcousticEmission', 'CheckBox'};
id_group_5 = {false 'Reconstruction' 'CheckBox';...
false 'Segmentation' 'CheckBox';...
false 'ComputerTomography' 'CheckBox';...
false, 'UltraSound', 'CheckBox';...
true, 'AcousticEmission', ['E.1'; 'E.2'; 'E.3']};
id_default = d;
config_data = get(src,'Data');
selector = config_data(1:5,1);
selector = cell2mat(selector);
config_format = get(src,'ColumnFormat')
if isequal(selector(1),1)
config_data = id_group_1;
elseif isequal(selector(2),1)
config_data = id_group_2;
elseif isequal(selector(3),1)
config_data = id_group_3;
elseif isequal(selector(4),1)
config_data = id_group_4;
elseif isequal(selector(5),1)
config_data = id_group_5;
else
config_data = id_default;
end
%set(src,'ColumnFormat', config_format)
set(src,'Data',config_data);
end
end
Related
I Want to select a row or column of a table with the edit field component and do some actions on these data and show the result in the first cell of table ([1,1])
rowNames={1:100}
columnName={A:ZZ}
like this:
sum(A1:A20) or Max(AA5:AA10)
I want to write above order in the edit field component
and show the result of them in cell[A,1]
How can I do that?
Here's an implementation that might be similar to what you are attempting to achieve.
Any subset can be calculated using the command such as: Sum(A1:A2)U(B2:B3)
Where A indicates the columns apart of the set and B indicates the rows apart of the set.
Some more test functions include:
Sum(A1:A4) and
Sum(B1:B4)
%Random data%
global Data;
Data = [1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4];
%Converting data into table%
Data = array2table(Data);
%Grabbing the size of the data%
[Number_Of_Rows, Number_Of_Columns] = size(Data);
%Creating arrays for setting the row and column names%
Row_Labels = strings(1,Number_Of_Rows);
Column_Labels = strings(1,Number_Of_Columns);
for Row_Scanner = 1: +1: Number_Of_Rows
Row_Labels(1,Row_Scanner) = ["B" + num2str(Row_Scanner)];
end
for Column_Scanner = 1: +1: Number_Of_Columns
Column_Labels(1,Column_Scanner) = ["A" + num2str(Column_Scanner)];
end
Row_Labels = cellstr(Row_Labels);
Column_Labels = cellstr(Column_Labels);
%UItable%
Main_Figure = uifigure;
Table = uitable(Main_Figure,'Data',Data);
Table.ColumnName = Column_Labels;
Table.RowName = Row_Labels;
set(Table,'ColumnEditable',true(1,Number_Of_Columns))
%Callback function to update the table%
% Table.CellEditCallback = #(Table,event) Update_Table_Data(Table);
%UIeditfield%
Selection_Field = uieditfield(Main_Figure,'text');
Field_Height = 20;
Field_Width = 100;
X_Position = 350;
Y_Position = 200;
Selection_Field.Position = [X_Position Y_Position Field_Width Field_Height];
Result_Label = uilabel(Main_Figure);
Result_Label.Position = [X_Position Y_Position-100 Field_Width Field_Height];
Selection_Field.ValueChangedFcn = #(Selection_Field,event) Compute_Value(Table,Selection_Field,Result_Label);
%Computing value
function [Data] = Compute_Value(Table,Selection_Field,Result_Label)
Data = Table.Data;
User_Input_Function = string(Selection_Field.Value);
Function = extractBefore(User_Input_Function,"(");
% fprintf("Function: %s \n",Function);
Key_Pairs = extractBetween(User_Input_Function,"(",")");
% fprintf("Key Pairs: (%s)\n", Key_Pairs);
Key_1 = extractBefore(Key_Pairs(1,1),":");
Key_2 = extractAfter(Key_Pairs(1,1),":");
Key_1
Key_2
if length(Key_Pairs) == 2
Key_3 = extractBefore(Key_Pairs(2,1),":");
Key_4 = extractAfter(Key_Pairs(2,1),":");
Key_3
Key_4
end
%Exracting the letters of each key
if contains(Key_1, "A") == 1
% fprintf("Function on columns\n")
Minimum_Column = str2num(extractAfter(Key_1,"A"));
Maximum_Column = str2num(extractAfter(Key_2,"A"));
Table_Subset = Data(1,Minimum_Column:Maximum_Column);
end
if contains(Key_1, "B") == 1
% fprintf("Function on rows\n")
Minimum_Row = str2num(extractAfter(Key_1,"B"));
Maximum_Row = str2num(extractAfter(Key_2,"B"));
Table_Subset = Data(Minimum_Row:Maximum_Row,1);
end
if length(Key_Pairs) == 2
Minimum_Column = str2num(extractAfter(Key_1,"A"));
Maximum_Column = str2num(extractAfter(Key_2,"A"));
Minimum_Row = str2num(extractAfter(Key_3,"B"));
Maximum_Row = str2num(extractAfter(Key_4,"B"));
Table_Subset = Data(Minimum_Row:Maximum_Row,Minimum_Column:Maximum_Column);
end
Table_Subset = table2array(Table_Subset);
%Statements for each function%
if (Function == 'Sum' || Function == 'sum')
fprintf("Computing sum\n");
Result_Sum = sum(Table_Subset,'all');
Result_Sum
Result_Label.Text = "Result: " + num2str(Result_Sum);
end
if (Function == 'Max' || Function == 'max')
fprintf("Computing maximum\n");
Result_Max = max(Table_Subset);
Result_Max
Result_Label.Text = "Result: " + num2str(Result_Max);
end
if (Function == 'Min' || Function == 'min')
fprintf("Computing minimum\n");
Result_Min = min(Table_Subset);
Result_Min
Result_Label.Text = "Result: " + num2str(Result_Min);
end
end
Within a function I've programmatically created an editable uitable with a plot. Whenever the cell values change, the plot updates. I'd like to set the new edited table as the output. My code so far:
function outputTable = begrenzung()
t = table(Drehzahl, Drehmoment, 'RowNames',{'Startpunkt' 'P1' 'P2' 'P3' 'Endpunkt'});
fig = uifigure;
fig.Position(3:4) = [822 360];
uit = uitable(fig,'ColumnEditable',true);
uit.Data = t;
uit.FontSize = 10;
uit.FontWeight = 'bold';
uit.ColumnEditable = true;
uit.Position(3) = 375;
ax = uiaxes(fig);
ax.Position(1) = 415;
ax.YLabel.String = 'Drehmoment [Nm]';
ax.XLabel.String = 'Drehzahl [rpm]';
x = t{:,1};
y = t{:,2};
area(ax,x,y);
ax.XLim = [0 45];
ax.YLim = [0 2000];
ax.Title.String = 'Feld der gefahrenen Punkte';
uit.CellEditCallback = #updatePlot;
function outputTable = updatePlot(src,event)
area(ax,uit.Data{:,1},uit.Data{:,2});
end
end
How can I save the updated uitable after each value-change?
I have found a solution, even though this might not be the elegant way:
function [outputTable] = begrenzung()
t = table(Drehzahl, Drehmoment,...
'RowNames',{'Startpunkt' 'P1' 'P2' 'P3' 'P4' 'Endpunkt'});
fig = uifigure;
fig.Position(3:4) = [822 360];
uit = uitable(fig);
uit.Data = t;
uit.FontSize = 10;
uit.FontWeight = 'bold';
uit.ColumnEditable = true;
uit.Position(3) = 375;
ax = uiaxes(fig);
ax.Position(1) = 415;
ax.YLabel.String = 'Drehmoment [Nm]';
ax.XLabel.String = 'Drehzahl [rpm]';
x = t{:,1};
y = t{:,2};
fill(ax,x,y,'c');
ax.XLim = [0 45];
ax.YLim = [0 2000];
ax.Title.String = 'Feld der gefahrenen Punkte';
uit.CellEditCallback = #updatePlot;
function [test] = updatePlot(src,event)
fill(ax,uit.Data{:,1},uit.Data{:,2},'c');
outputTable = uit.Data;
end
outputTable = uit.Data;
uiwait(fig);
end
this way, my Output is the changed table
I have a code for ID3 decision tree but I cannot find the appropriate code for plotting or viewing the Tree
I have used several view MATLAB functions like view(Mdl,'Mode','graph') but none of them worked the code currently produces result of decision tree structure as
DECISION TREE STRUCTURE:
parent: root attribute: IsRich falseChild:HasScholarship trueChild:GoodLetters
parent: IsRich attribute: HasScholarship falseChild:false trueChild:GoodSAT
parent: HasScholarship false
parent: HasScholarship attribute: GoodSAT falseChild:false trueChild:GoodLetters
parent: GoodSAT false
parent: GoodSAT attribute: GoodLetters falseChild:false trueChild:true
parent: GoodLetters false
parent: GoodLetters true
parent: IsRich attribute: GoodLetters falseChild:GoodGrades trueChild:GoodGrades
parent: GoodLetters attribute: GoodGrades falseChild:false trueChild:SchoolActivities
parent: GoodGrades false
parent: GoodGrades attribute: SchoolActivities falseChild:false trueChild:true
parent: SchoolActivities false
parent: SchoolActivities true
parent: GoodLetters attribute: GoodGrades falseChild:GoodSAT trueChild:true
parent: GoodGrades attribute: GoodSAT falseChild:false trueChild:true
parent: GoodSAT false
parent: GoodSAT true
parent: GoodGrades true
So I would like to plot this Tree Structure , any help will much appreciated
% ID3 Decision Tree Algorithm
function[] = decisiontree(inputFileName, trainingSetSize, numberOfTrials,...
verbose)
% DECISIONTREE Create a decision tree by following the ID3 algorithm
% args:
% inputFileName - the fully specified path to input file
% trainingSetSize - integer specifying number of examples from input
% used to train the dataset
% numberOfTrials - integer specifying how many times decision tree
% will be built from a randomly selected subset
% of the training examples
% verbose - string that must be eiher '1' or '0', if '1'
% output includes training and test sets, else
% it will only contain description of tree and
% results for the trials
% Read in the specified text file contain the examples
fid = fopen(inputFileName, 'rt');
dataInput = textscan(fid, '%s');
% Close the file
fclose(fid);
% Reformat the data into attribute array and data matrix of 1s and 0s for
% true or false
i = 1;
% First store the attributes into a cell array
while (~strcmp(dataInput{1}{i}, 'CLASS'));
i = i + 1;
end
attributes = cell(1,i);
for j=1:i;
attributes{j} = dataInput{1}{j};
end
% NOTE: The classification will be the final attribute in the data rows
% below
numAttributes = i;
numInstances = (length(dataInput{1}) - numAttributes) / numAttributes;
% Then store the data into matrix
data = zeros(numInstances, numAttributes);
i = i + 1;
for j=1:numInstances
for k=1:numAttributes
data(j, k) = strcmp(dataInput{1}{i}, 'true');
i = i + 1;
end
end
% Here is where the trials start
for i=1:numberOfTrials;
% Print the trial number
fprintf('TRIAL NUMBER: %d\n\n', i);
% Split data into training and testing sets randomly
% Use randsample to get a vector of row numbers for the training set
rows = sort(randsample(numInstances, trainingSetSize));
% Initialize two new matrices, training set and test set
trainingSet = zeros(trainingSetSize, numAttributes);
testingSetSize = (numInstances - trainingSetSize);
testingSet = zeros(testingSetSize, numAttributes);
% Loop through data matrix, copying relevant rows to each matrix
training_index = 1;
testing_index = 1;
for data_index=1:numInstances;
if (rows(training_index) == data_index);
trainingSet(training_index, :) = data(data_index, :);
if (training_index < trainingSetSize);
training_index = training_index + 1;
end
else
testingSet(testing_index, :) = data(data_index, :);
if (testing_index < testingSetSize);
testing_index = testing_index + 1;
end
end
end
% If verbose, print out training set
if (verbose);
for ii=1:numAttributes;
fprintf('%s\t', attributes{ii});
end
fprintf('\n');
for ii=1:trainingSetSize;
for jj=1:numAttributes;
if (trainingSet(ii, jj));
fprintf('%s\t', 'true');
else
fprintf('%s\t', 'false');
end
end
fprintf('\n');
end
end
% Estimate the expected prior probability of TRUE and FALSE based on
% training set
if (sum(trainingSet(:, numAttributes)) >= trainingSetSize);
expectedPrior = 'true';
else
expectedPrior = 'false';
end
% Construct a decision tree on the training set using the ID3 algorithm
activeAttributes = ones(1, length(attributes) - 1);
new_attributes = attributes(1:length(attributes)-1);
tree = ID3(trainingSet, attributes, activeAttributes); % Here ID3 function
% Print out the tree
fprintf('DECISION TREE STRUCTURE:\n');
PrintTree(tree, 'root');
end
The ID3 function is
function [tree] = ID3(examples, attributes, activeAttributes)
% ID3 Runs the ID3 algorithm on the matrix of examples and attributes
% args:
% examples - matrix of 1s and 0s for trues and falses, the
% last value in each row being the value of the
% classifying attribute
% attributes - cell array of attribute strings (no CLASS)
% activeAttributes - vector of 1s and 0s, 1 if corresponding attr.
% active (no CLASS)
% return:
% tree - the root node of a decision tree
% tree struct:
% value - will be the string for the splitting
% attribute, or 'true' or 'false' for leaf
% left - left pointer to another tree node (left means
% the splitting attribute was false)
% right - right pointer to another tree node (right
% means the splitting attribute was true)
if (isempty(examples));
error('Must provide examples');
end
% Constants
numberAttributes = length(activeAttributes);
numberExamples = length(examples(:,1));
% Create the tree node
tree = struct('value', 'null', 'left', 'null', 'right', 'null');
% If last value of all rows in examples is 1, return tree labeled 'true'
lastColumnSum = sum(examples(:, numberAttributes + 1));
if (lastColumnSum == numberExamples);
tree.value = 'true';
return
end
% If last value of all rows in examples is 0, return tree labeled 'false'
if (lastColumnSum == 0);
tree.value = 'false';
return
end
% If activeAttributes is empty, then return tree with label as most common
% value
if (sum(activeAttributes) == 0);
if (lastColumnSum >= numberExamples / 2);
tree.value = 'true';
else
tree.value = 'false';
end
return
end
% Find the current entropy
p1 = lastColumnSum / numberExamples;
if (p1 == 0);
p1_eq = 0;
else
p1_eq = -1*p1*log2(p1);
end
p0 = (numberExamples - lastColumnSum) / numberExamples;
if (p0 == 0);
p0_eq = 0;
else
p0_eq = -1*p0*log2(p0);
end
currentEntropy = p1_eq + p0_eq;
% Find the attribute that maximizes information gain
gains = -1*ones(1,numberAttributes); %-1 if inactive, gains for all else
% Loop through attributes updating gains, making sure they are still active
for i=1:numberAttributes;
if (activeAttributes(i)) % this one is still active, update its gain
s0 = 0; s0_and_true = 0;
s1 = 0; s1_and_true = 0;
for j=1:numberExamples;
if (examples(j,i)); % this instance has splitting attr. true
s1 = s1 + 1;
if (examples(j, numberAttributes + 1)); %target attr is true
s1_and_true = s1_and_true + 1;
end
else
s0 = s0 + 1;
if (examples(j, numberAttributes + 1)); %target attr is true
s0_and_true = s0_and_true + 1;
end
end
end
% Entropy for S(v=1)
if (~s1);
p1 = 0;
else
p1 = (s1_and_true / s1);
end
if (p1 == 0);
p1_eq = 0;
else
p1_eq = -1*(p1)*log2(p1);
end
if (~s1);
p0 = 0;
else
p0 = ((s1 - s1_and_true) / s1);
end
if (p0 == 0);
p0_eq = 0;
else
p0_eq = -1*(p0)*log2(p0);
end
entropy_s1 = p1_eq + p0_eq;
% Entropy for S(v=0)
if (~s0);
p1 = 0;
else
p1 = (s0_and_true / s0);
end
if (p1 == 0);
p1_eq = 0;
else
p1_eq = -1*(p1)*log2(p1);
end
if (~s0);
p0 = 0;
else
p0 = ((s0 - s0_and_true) / s0);
end
if (p0 == 0);
p0_eq = 0;
else
p0_eq = -1*(p0)*log2(p0);
end
entropy_s0 = p1_eq + p0_eq;
gains(i) = currentEntropy - ((s1/numberExamples)*entropy_s1) - ((s0/numberExamples)*entropy_s0);
end
end
% Pick the attribute that maximizes gains
[~, bestAttribute] = max(gains);
% Set tree.value to bestAttribute's relevant string
tree.value = attributes{bestAttribute};
% Remove splitting attribute from activeAttributes
activeAttributes(bestAttribute) = 0;
% Initialize and create the new example matrices
examples_0 = []; examples_0_index = 1;
examples_1 = []; examples_1_index = 1;
for i=1:numberExamples;
if (examples(i, bestAttribute)); % this instance has it as 1/true
examples_1(examples_1_index, :) = examples(i, :); % copy over
examples_1_index = examples_1_index + 1;
else
examples_0(examples_0_index, :) = examples(i, :);
examples_0_index = examples_0_index + 1;
end
end
% For both values of the splitting attribute
% For value = false or 0, corresponds to left branch
% If examples_0 is empty, add leaf node to the left with relevant label
if (isempty(examples_0));
leaf = struct('value', 'null', 'left', 'null', 'right', 'null');
if (lastColumnSum >= numberExamples / 2); % for matrix examples
leaf.value = 'true';
else
leaf.value = 'false';
end
tree.left = leaf;
else
% Here is were we can recur
tree.left = ID3(examples_0, attributes, activeAttributes);
end
% For value = true or 1, corresponds to right branch
% If examples_1 is empty, add leaf node to the right with relevant label
if (isempty(examples_1));
leaf = struct('value', 'null', 'left', 'null', 'right', 'null');
if (lastColumnSum >= numberExamples / 2); % for matrix examples
leaf.value = 'true';
else
leaf.value = 'false';
end
tree.right = leaf;
else
% Here is were we can recur
tree.right = ID3(examples_1, attributes, activeAttributes);
end
% Now we can return tree
return
end
PrintTree.m
function [] = PrintTree(tree, parent)
% Prints the tree structure (preorder traversal)
% Print current node
if (strcmp(tree.value, 'true'));
fprintf('parent: %s\ttrue\n', parent);
return
elseif (strcmp(tree.value, 'false'));
fprintf('parent: %s\tfalse\n', parent);
return
else
% Current node an attribute splitter
fprintf('parent: %s\tattribute: %s\tfalseChild:%s\ttrueChild:%s\n', ...
parent, tree.value, tree.left.value, tree.right.value);
end
% Recur the left subtree
PrintTree(tree.left, tree.value);
% Recur the right subtree
PrintTree(tree.right, tree.value);
%treeplot(node)
end
in matlab while compiling to c code imcrop failed to run.
is there is any alternative method or any way to suppress?
I am using Matlab2016a. Below is code snippet:
if ~isempty(bbox);
bbox = bbox(1,1:4);
Ic = imcrop(im,bbox);
bboxeye = step(faceDetectorLeye, Ic);
end
Edit:
fullcode
function signal = detectFatigue(im)
% Create a detector object
faceDetector = vision.CascadeObjectDetector('ClassificationModel','FrontalFaceLBP','MinSize',[100 100]);
faceDetectorLeye = vision.CascadeObjectDetector('EyePairBig');
% Detect faces
bbox = step(faceDetector, im);
if ~isempty(bbox);
bbox = bbox(1,1:4);
Ic = imcrop(im,bbox);
bboxeye = step(faceDetectorLeye, Ic);
if ~isempty(bboxeye);
bboxeye = bboxeye(1,1:4);
Eeye = imcrop(Ic,bboxeye);
[~, nce, ~ ] = size(Eeye);
% Divide into two parts
Leye = Eeye(:,1:round(nce/2),:);
Reye = Eeye(:,round(nce/2+1):end,:);
% make grascale
Leye = rgb2gray(Leye);
Reye = rgb2gray(Reye);
Leye = filterim(Leye);
Reye = filterim(Reye);
lroi = [ 12 5 30 16 ];
rroi = [ 18 5 30 16 ];
Leyeroi = imcrop(Leye,lroi);
Reyeroi = imcrop(Reye,rroi);
[lc, ~ ] = findcircle(Leyeroi);
[rc, ~ ] = findcircle(Reyeroi);
if isempty(lc) && isempty(rc)
signal = 1;
else
signal = 0;
end
end
end
function Leye=filterim(Leye)
se = strel('disk',2,4);
% dilate graysacle
Leye = imdilate(Leye,se);
% erode grayscale
Leye = imerode(Leye,se);
Leye = imadjust(Leye);
Leye = imcomplement(Leye);
Leye = im2bw(Leye,0.95);
Leye = imresize(Leye,[30 60]);
function [c, r] = findcircle(Leyeroi)
[c ,r ] = imfindcircles(Leyeroi,[5 9],'ObjectPolarity','bright','Sensitivity',0.95);
[rm,id] = max(r);
r = rm;
c = c(id,:);
if ~isempty(c)
c(1) = c(1) + 15;
c(2) = c(2) + 7;
end
and to test the detectFatigue.m below is the function
function testdetectFatigue()
vid=webcam(1);
for loop=1:10
im=snapshot(vid);
detectFatigue(im);
end
I'm doing quite simple SVM classification at the moment. I use a precomputed kernel in LibSVM with RBF and DTW.
When I compute the similarity (kernel-) matrix, everything seems to work very fine ... until I permute my data, before I compute the kernel matrix.
An SVM is of course invariant to permutations of input-data. In the below Matlab-code, the line marked with '<- !!!!!!!!!!' decides about the classification accuracy (not permuted: 100% -- permuted: 0% to 100%, dependant on the seed of rng). But why does permuting the file-string-array (named fileList) make any difference? What am I doing wrong? Have I misunderstood the concept of 'permutation invariance' or is it a problem with my Matlab-code?
My csv-files are formatted as: LABEL, val1, val2, ..., valN and all the csv-files are stored in the folder dirName. So the string array contains the entries '10_0.csv 10_1.csv .... 11_7.csv, 11_8.csv' (not permuted) or some other order when permuted.
I also tried to permute the vector of sample serial numbers, too, but that makes no difference.
function [SimilarityMatrixTrain, SimilarityMatrixTest, trainLabels, testLabels, PermSimilarityMatrixTrain, PermSimilarityMatrixTest, permTrainLabels, permTestLabels] = computeDistanceMatrix(dirName, verificationClass, trainFrac)
fileList = getAllFiles(dirName);
fileList = fileList(1:36);
trainLabels = [];
testLabels = [];
trainFiles = {};
testFiles = {};
permTrainLabels = [];
permTestLabels = [];
permTrainFiles = {};
permTestFiles = {};
n = 0;
sigma = 0.01;
trainFiles = fileList(1:2:end);
testFiles = fileList(2:2:end);
rng(3);
permTrain = randperm(length(trainFiles))
%rng(3); <- !!!!!!!!!!!
permTest = randperm(length(testFiles));
permTrainFiles = trainFiles(permTrain)
permTestFiles = testFiles(permTest);
noTrain = size(trainFiles);
noTest = size(testFiles);
SimilarityMatrixTrain = eye(noTrain);
PermSimilarityMatrixTrain = (noTrain);
SimilarityMatrixTest = eye(noTest);
PermSimilarityMatrixTest = eye(noTest);
% UNPERM
%Train
for i = 1 : noTrain
x = csvread(trainFiles{i});
label = x(1);
trainLabels = [trainLabels, label];
for j = 1 : noTrain
y = csvread(trainFiles{j});
dtwDistance = dtwWrapper(x(2:end), y(2:end));
rbfValue = exp((dtwDistance.^2)./(-2*sigma));
SimilarityMatrixTrain(i, j) = rbfValue;
n=n+1
end
end
SimilarityMatrixTrain = [(1:size(SimilarityMatrixTrain, 1))', SimilarityMatrixTrain];
%Test
for i = 1 : noTest
x = csvread(testFiles{i});
label = x(1);
testLabels = [testLabels, label];
for j = 1 : noTest
y = csvread(testFiles{j});
dtwDistance = dtwWrapper(x(2:end), y(2:end));
rbfValue = exp((dtwDistance.^2)./(-2*sigma));
SimilarityMatrixTest(i, j) = rbfValue;
n=n+1
end
end
SimilarityMatrixTest = [(1:size(SimilarityMatrixTest, 1))', SimilarityMatrixTest];
% PERM
%Train
for i = 1 : noTrain
x = csvread(permTrainFiles{i});
label = x(1);
permTrainLabels = [permTrainLabels, label];
for j = 1 : noTrain
y = csvread(permTrainFiles{j});
dtwDistance = dtwWrapper(x(2:end), y(2:end));
rbfValue = exp((dtwDistance.^2)./(-2*sigma));
PermSimilarityMatrixTrain(i, j) = rbfValue;
n=n+1
end
end
PermSimilarityMatrixTrain = [(1:size(PermSimilarityMatrixTrain, 1))', PermSimilarityMatrixTrain];
%Test
for i = 1 : noTest
x = csvread(permTestFiles{i});
label = x(1);
permTestLabels = [permTestLabels, label];
for j = 1 : noTest
y = csvread(permTestFiles{j});
dtwDistance = dtwWrapper(x(2:end), y(2:end));
rbfValue = exp((dtwDistance.^2)./(-2*sigma));
PermSimilarityMatrixTest(i, j) = rbfValue;
n=n+1
end
end
PermSimilarityMatrixTest = [(1:size(PermSimilarityMatrixTest, 1))', PermSimilarityMatrixTest];
mdlU = svmtrain(trainLabels', SimilarityMatrixTrain, '-t 4 -c 0.5');
mdlP = svmtrain(permTrainLabels', PermSimilarityMatrixTrain, '-t 4 -c 0.5');
[pclassU, xU, yU] = svmpredict(testLabels', SimilarityMatrixTest, mdlU);
[pclassP, xP, yP] = svmpredict(permTestLabels', PermSimilarityMatrixTest, mdlP);
xU
xP
end
I'd be very thankful for any answer!
Regards
Benjamin
after cleaning up the code and letting a colleague of mine have a look on it, we/he finally found the bug. Of course, I have to compute the testing matrix from the training and testing samples (to let the SVM predict the testing data by using the sum over the product of alpha-values of the training vectors (they are zero for non support vectors)). Hope this clarifies the problem for any of you. To make it more clear, see my revised code below. But, as for example in using precomputed kernels with libsvm, there one with sharp eyes can also see the computation of the testing matrix with train and test vectors, too. Feel free to put comments or/and answers to this post if you have any further remarks/questions/tips!
function [tacc, testacc, mdl, SimilarityMatrixTrain, SimilarityMatrixTest, trainLabels, testLabels] = computeSimilarityMatrix(dirName)
fileList = getAllFiles(dirName);
fileList = fileList(1:72);
trainLabels = [];
testLabels = [];
trainFiles = {};
testFiles = {};
n = 0;
sigma = 0.01;
trainFiles = fileList(1:2:end);
testFiles = fileList(2:5:end);
noTrain = size(trainFiles);
noTest = size(testFiles);
permTrain = randperm(noTrain(1));
permTest = randperm(noTest(1));
trainFiles = trainFiles(permTrain);
testFiles = testFiles(permTest);
%Train
for i = 1 : noTrain(1)
x = csvread(trainFiles{i});
label = x(1);
trainlabel = label;
trainLabels = [trainLabels, label];
for j = 1 : noTrain(1)
y = csvread(trainFiles{j});
dtwDistance = dtwWrapper(x(2:end), y(2:end));
rbfValue = exp((dtwDistance.^2)./(-2*sigma.^2));
SimilarityMatrixTrain(i, j) = rbfValue;
end
end
SimilarityMatrixTrain = [(1:size(SimilarityMatrixTrain, 1))', SimilarityMatrixTrain];
%Test
for i = 1 : noTest(1)
x = csvread(testFiles{i});
label = x(1);
testlabel = label;
testLabels = [testLabels, label];
for j = 1 : noTrain(1)
y = csvread(trainFiles{j});
dtwDistance = dtwWrapper(x(2:end), y(2:end));
rbfValue = exp((dtwDistance.^2)./(-2*sigma.^2));
SimilarityMatrixTest(i, j) = rbfValue;
end
end
SimilarityMatrixTest = [(1:size(SimilarityMatrixTest, 1))', SimilarityMatrixTest];
mdlU = svmtrain(trainLabels', SimilarityMatrixTrain, '-t 4 -c 1000 -q');
fprintf('TEST: '); [pclassU, xU, yU] = svmpredict(testLabels', SimilarityMatrixTest, mdlU);
fprintf('TRAIN: ');[pclassT, xT, yT] = svmpredict(trainLabels', SimilarityMatrixTrain, mdlU);
tacc = xT(1);
testacc = xU(1);
mdl = mdlU;
end
Regards
Benjamin