error : Unable to use a value of type ClassificationNaiveBayes as an index.

I trained a Naive Bayes model using:
nb = fitcnb(x, t, 'Distribution','kernel');
but when I try to classify new data :
i = predict(nb,values);
I got this error : Unable to use a value of type ClassificationNaiveBayes as an index.
what's wrong? Can anyone help me please?
PS: I use Matlab 2019b

Risposte (1)

Hi Oujaoura,
The error you're encountering typically occurs when there's a mismatch in the way the predict function is being used. The predict function is expecting the model object as its first argument, but it seems like there might be a mistake in your code that's causing MATLAB to interpret something incorrectly.
Here’s a checklist and a corrected example to help you troubleshoot and resolve the issue:
Checklist:
  1. Model Variable: Ensure that nb is indeed your ClassificationNaiveBayes model object. Double-check that it hasn't been overwritten or modified in your code.
  2. Input Data: Make sure that values is a matrix with the same number of columns (features) as the data used to train nb. The number of features in values should match x.
  3. Function Syntax: Verify that the predict function is called correctly with the model object as the first argument.
Corrected Example:
Here's how you should be using the fitcnb and predict functions:
% Train the Naive Bayes model
x = rand(100, 5); % Example feature matrix with 100 samples and 5 features
t = randi([1, 3], 100, 1); % Example target vector with 3 classes
nb = fitcnb(x, t, 'Distribution', 'kernel');
% New data for prediction
values = rand(10, 5); % New data matrix with 10 samples and 5 features
% Predict class labels for new data
predictedLabels = predict(nb, values);
% Display predicted labels
disp('Predicted Class Labels:');
disp(predictedLabels);
Explanation:
  • Training Data (x and t): Ensure x is your training feature matrix and t is your target vector.
  • New Data (values): Ensure values has the same number of features as x.
  • predict Function: Make sure the predict function is called with nb as the first argument and values as the second.

Richiesto:

il 19 Feb 2020

Risposto:

il 5 Set 2024

Community Treasure Hunt

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

Start Hunting!

Translated by