MATLAB Answers

how make prediction with new data and display it?

17 views (last 30 days)
Eihmz Abe
Eihmz Abe on 10 Mar 2019
i have exported the auto generated code from the classisification learner app.i want to use to predict new data from another file.
function [trainedClassifier, validationAccuracy] = trainClassifier2(trainingData)
% trainClassifier(trainingData)
% returns a trained classifier and its accuracy.
% This code recreates the classification model trained in
% Classification Learner app.
% Input:
% trainingData: the training data of same data type as imported
% in the app (table or matrix).
% Output:
% trainedClassifier: a struct containing the trained classifier.
% The struct contains various fields with information about the
% trained classifier.
% trainedClassifier.predictFcn: a function to make predictions
% on new data. It takes an input of the same form as this training
% code (table or matrix) and returns predictions for the response.
% If you supply a matrix, include only the predictors columns (or
% rows).
% validationAccuracy: a double containing the accuracy in
% percent. In the app, the History list displays this
% overall accuracy score for each model.
% Use the code to train the model with new data.
% To retrain your classifier, call the function from the command line
% with your original data or new data as the input argument trainingData.
% For example, to retrain a classifier trained with the original data set
% T, enter:
% [trainedClassifier, validationAccuracy] = trainClassifier(T)
% To make predictions with the returned 'trainedClassifier' on new data T,
% use
% yfit = trainedClassifier.predictFcn(T)
% To automate training the same classifier with new data, or to learn how
% to programmatically train classifiers, examine the generated code.
% Auto-generated by MATLAB on 03-Mar-2019 14:35:31
% Extract predictors and response
% This code processes the data into the right shape for training the
% classifier.
inputTable = trainingData;
predictorNames = {'VarName1'};
predictors = inputTable(:, predictorNames);
response = inputTable.A;
isCategoricalPredictor = [false];
% Train a classifier
% This code specifies all the classifier options and trains the classifier.
classificationTree = fitctree(...
predictors, ...
response, ...
'SplitCriterion', 'gdi', ...
'MaxNumSplits', 100, ...
'Surrogate', 'off', ...
'ClassNames', {'A'; 'B'; 'C'});
% Create the result struct with predict function
predictorExtractionFcn = @(t) t(:, predictorNames);
treePredictFcn = @(x) predict(classificationTree, x);
trainedClassifier.predictFcn = @(x) treePredictFcn(predictorExtractionFcn(x));
% Add additional fields to the result struct
trainedClassifier.RequiredVariables = {'VarName1'};
trainedClassifier.ClassificationTree = classificationTree;
trainedClassifier.About = 'This struct is a trained classifier exported from Classification Learner R2016a.';
trainedClassifier.HowToPredict = sprintf('To make predictions on a new table, T, use: \n yfit = c.predictFcn(T) \nreplacing ''c'' with the name of the variable that is this struct, e.g. ''trainedClassifier''. \n \nThe table, T, must contain the variables returned by: \n c.RequiredVariables \nVariable formats (e.g. matrix/vector, datatype) must match the original training data. \nAdditional variables are ignored. \n \nFor more information, see <a href="matlab:helpview(fullfile(docroot, ''stats'', ''''), ''appclassification_exportmodeltoworkspace'')">How to predict using an exported model</a>.');
% Extract predictors and response
% This code processes the data into the right shape for training the
% classifier.
inputTable = trainingData;
predictorNames = {'VarName1'};
predictors = inputTable(:, predictorNames);
response = inputTable.A;
isCategoricalPredictor = [false];
% Perform cross-validation
partitionedModel = crossval(trainedClassifier.ClassificationTree, 'KFold', 5);
% Compute validation accuracy
validationAccuracy = 1 - kfoldLoss(partitionedModel, 'LossFun', 'ClassifError');
% Compute validation predictions and scores
[validationPredictions, validationScores] = kfoldPredict(partitionedModel);
and here is the gui for the button..i want to display the output when i clicked the button but i having trouble.
the expected input would be the total variable..pls help me.
error shows
Undefined function or variable 'trainingData'
Error in sampleFigure>ButtonClassify_Callback (line 87)
[trainedClassifier, validationAccuracy] =
function ButtonClassify_Callback(hObject, eventdata, handles)
% hObject handle to ButtonClassify (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global whitepix;
global whitepix2
total= whitepix + whitepix2;
[trainedClassifier, validationAccuracy] = trainClassifier2(trainingData);
% fprintf(' total%i \n', pre);

Answers (2)

Mrutyunjaya Hiremath
Mrutyunjaya Hiremath on 12 Apr 2020
Phase 01: Training
'trainingData.xlsx' contains data need to Train.
trainingData = xlsread('trainingData.xlsx');
[trainedClassifier, resubstitutionAccuracy] = trainClassifier2(trainingData);
Phase 02: Testing
'testingData.xlsx' contains data need to Test.
testingData = xlsread('testingData.xlsx');

I want to know if your 'trainingdata' has any data. When the classifier app you used to generate this model and code, it will generate with a variable called 'trainingdata'. you have to edit that variable and change to your main data file you want to train on. for example, i want to train data 'A' and use it to predict 'B' and see the accuracy. then according to your model and function:
[trainedClassifier, validationAccuracy] = trainClassifier2(A);
Now I have new data 'C' and want to see if it can predict 'B' again;
Now you have to make sure that new data has same variables (predictors) as 'trainingdata' A had. You can check the required variables by using:
and check whether 'C' has those variables. If it has extra variables and required variables, this code will ignore those extra variables. Use 'confusionmat()' to see your effeciency of your model. Let me know if this helps.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!