-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodal.m
118 lines (104 loc) · 5.67 KB
/
modal.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
function [trainedClassifier, validationAccuracy] = trainClassifier(trainingData)
% [trainedClassifier, validationAccuracy] = trainClassifier(trainingData)
% Returns a trained classifier and its accuracy. This code recreates the
% classification model trained in Classification Learner app. Use the
% generated code to automate training the same model with new data, or to
% learn how to programmatically train models.
%
% Input:
% trainingData: A table containing the same predictor and response
% columns as those imported into the app.
%
% 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.
%
% 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 T2,
% use
% yfit = trainedClassifier.predictFcn(T2)
%
% T2 must be a table containing at least the same predictor columns as used
% during training. For details, enter:
% trainedClassifier.HowToPredict
% Auto-generated by MATLAB on 17-Apr-2021 15:15:18
% Extract predictors and response
% This code processes the data into the right shape for training the
% model.
inputTable = trainigData;
predictorNames = {'N', 'P', 'K', 'Temperature', 'Humidity', 'pH', 'Rainfall'};
predictors = inputTable(:, predictorNames);
response = inputTable.Crop;
isCategoricalPredictor = [false, false, false, false, false, false, false];
% Train a classifier
% This code specifies all the classifier options and trains the classifier.
classificationKNN = fitcknn(...
predictors, ...
response, ...
'Distance', 'Euclidean', ...
'Exponent', [], ...
'NumNeighbors', 10, ...
'DistanceWeight', 'SquaredInverse', ...
'Standardize', true, ...
'ClassNames', categorical({'apple'; 'banana'; 'blackgram'; 'chickpea'; 'coconut'; 'coffee'; 'cotton'; 'grapes'; 'jute'; 'kidneybeans'; 'lentil'; 'maize'; 'mango'; 'mothbeans'; 'mungbean'; 'muskmelon'; 'orange'; 'papaya'; 'pigeonpeas'; 'pomegranate'; 'rice'; 'watermelon'}));
% Create the result struct with predict function
predictorExtractionFcn = @(t) t(:, predictorNames);
knnPredictFcn = @(x) predict(classificationKNN, x);
trainedClassifier.predictFcn = @(x) knnPredictFcn(predictorExtractionFcn(x));
% Add additional fields to the result struct
trainedClassifier.RequiredVariables = {'Humidity', 'K', 'N', 'P', 'Rainfall', 'Temperature', 'pH'};
trainedClassifier.ClassificationKNN = classificationKNN;
trainedClassifier.About = 'This struct is a trained model exported from Classification Learner R2021a.';
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. ''trainedModel''. \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
% model.
inputTable = trainingData;
predictorNames = {'N', 'P', 'K', 'Temperature', 'Humidity', 'pH', 'Rainfall'};
predictors = inputTable(:, predictorNames);
response = inputTable.Crop;
isCategoricalPredictor = [false, false, false, false, false, false, false];
% Set up holdout validation
cvp = cvpartition(response, 'Holdout', 0.25);
trainingPredictors = predictors(cvp.training, :);
trainingResponse = response(cvp.training, :);
trainingIsCategoricalPredictor = isCategoricalPredictor;
% Train a classifier
% This code specifies all the classifier options and trains the classifier.
classificationKNN = fitcknn(...
trainingPredictors, ...
trainingResponse, ...
'Distance', 'Euclidean', ...
'Exponent', [], ...
'NumNeighbors', 10, ...
'DistanceWeight', 'SquaredInverse', ...
'Standardize', true, ...
'ClassNames', categorical({'apple'; 'banana'; 'blackgram'; 'chickpea'; 'coconut'; 'coffee'; 'cotton'; 'grapes'; 'jute'; 'kidneybeans'; 'lentil'; 'maize'; 'mango'; 'mothbeans'; 'mungbean'; 'muskmelon'; 'orange'; 'papaya'; 'pigeonpeas'; 'pomegranate'; 'rice'; 'watermelon'}));
% Create the result struct with predict function
knnPredictFcn = @(x) predict(classificationKNN, x);
validationPredictFcn = @(x) knnPredictFcn(x);
% Add additional fields to the result struct
% Compute validation predictions
validationPredictors = predictors(cvp.test, :);
validationResponse = response(cvp.test, :);
[validationPredictions, validationScores] = validationPredictFcn(validationPredictors);
% Compute validation accuracy
correctPredictions = (validationPredictions == validationResponse);
isMissing = ismissing(validationResponse);
correctPredictions = correctPredictions(~isMissing);
validationAccuracy = sum(correctPredictions)/length(correctPredictions);