Как использовать сгенерированный код из приложения классификации учащихся в MATLAB для прогнозирования новых данных? - PullRequest
0 голосов
/ 08 марта 2019

У меня проблемы с вызовом функции из сгенерированного кода, и я хочу отобразить вывод в командном окне.

function varargout = ipwebcamGUI(varargin)
% IPWEBCAMGUI MATLAB code for ipwebcamGUI.fig
%      IPWEBCAMGUI, by itself, creates a new IPWEBCAMGUI or raises the existing
%      singleton*.
%
%      H = IPWEBCAMGUI returns the handle to a new IPWEBCAMGUI or the handle to
%      the existing singleton*.
%
%      IPWEBCAMGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in IPWEBCAMGUI.M with the given input arguments.
%
%      IPWEBCAMGUI('Property','Value',...) creates a new IPWEBCAMGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ipwebcamGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ipwebcamGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help ipwebcamGUI

% Last Modified by GUIDE v2.5 07-Mar-2019 22:03:50

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ipwebcamGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @ipwebcamGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before ipwebcamGUI is made visible.
function ipwebcamGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ipwebcamGUI (see VARARGIN)

% Choose default command line output for ipwebcamGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ipwebcamGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = ipwebcamGUI_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


axes(handles.axes1);
im=imread('c1.jpg');
k=rgb2gray(im);

% Threshold image - global threshold
BW = imbinarize(k);

% Invert mask
BW = imcomplement(BW);

%clear border
BW = imclearborder(BW);

% Create masked image.
maskedImage = k;
maskedImage(~BW) = 0;

%count the white pixel in image
whitepix = sum(BW(:));

axis off;
imshow(BW);
clear


% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

T = trainClassifier2(trainingData);
yfit = trainedClassifier.predictFcn(T);
fprintf('result %d \n',yfit );
% set(handles.text2,'String',T);
% drawnow();

этот файл называется ipwebcamGUI.m и второй поезд Classifier2.m

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'', ''stats.map''), ''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);

программа считает белый пиксель на изображении. И переменная "whitepix" будет ожидаемым входным сигналом .. выходным будет A, B, C ..

В этой части возникла проблема. Я хочу отображать вывод при нажатии кнопки. Я новичок в этом, пожалуйста, помогите мне.

function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

T = trainClassifier2(trainingData);
yfit = trainedClassifier.predictFcn(T);
fprintf('result %d \n',yfit );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...