Skip to main content
v2026.11,986 entries · CC-BY 4.0

Scikit-learn Naive Bayes: Fit, Predict and Check

Fit GaussianNB to Iris measurements, evaluate held-out classes, and keep class names, probability columns and analysis settings aligned.

Written and maintained by CASRAI Editorial Board

Published

On this page

Scikit-learn naive Bayes classifiers learn class labels from a feature matrix using class-specific probability models. For continuous research measurements, start with GaussianNB, fit it on training data, then predict held-out labels. The worked Iris example below also checks class-name alignment, reports each class separately, and records the settings needed to reproduce the calculation.

What it is used for in research

Naive Bayes is supervised classification: the training observations already have labels, and the fitted model assigns labels to further observations. The defining assumption is that features are conditionally independent given the class. This differs from saying that every feature is independent in the pooled dataset. Scikit-learn’s naive Bayes user guide distinguishes the estimators by their feature-distribution assumptions.

Sklearn naive Bayes: match the model to the representation

GaussianNB uses a Gaussian likelihood for each feature within each class. The example uses the library’s Iris measurements to demonstrate that interface. It is an illustrative analysis of a built-in research dataset, not evidence that the classifier will perform similarly in another study. For the loader’s return structures and the distinction between loading and fetching data, see scikit-learn dataset loaders.

Keep the statistical question separate from the software call. In this walkthrough, the question is whether four recorded flower measurements can predict a known species label in the held-out subset. A successful call to fit answers whether the software accepted the inputs; the held-out comparison answers a different question about the resulting predictions. Neither, by itself, demonstrates that the model’s assumptions describe the study population.

Install or access

Install the distribution named scikit-learn; its Python import name is sklearn. The official installation instructions recommend a virtual environment to avoid conflicts with other packages. On Linux or macOS, the documented commands are:

python -m venv sklearn-env
source sklearn-env/bin/activate
pip install -U scikit-learn

On Windows, replace the activation line with sklearn-envScriptsactivate. After activation, check the installed package and its dependencies using the official diagnostic commands:

python -m pip show scikit-learn
python -m pip freeze
python -c "import sklearn; sklearn.show_versions()"

Keep that environment record with the analysis script. The example output here was computed with scikit-learn 1.9.1; it is a record of this run, rather than an instruction to assume the same version is installed everywhere. The broader scikit-learn research tutorial covers the surrounding estimator workflow.

Step-by-step task: naive Bayes sklearn example

  1. Load the measurements and their labels. load_iris() returns a Bunch containing the feature matrix, targets, feature names and target names. Its API documents 150 observations, four real-valued features and three classes with 50 observations each. Retaining the Bunch keeps the names available when the numerical labels are reported.
  2. Split before fitting. Use test_size=0.30, random_state=42 and stratify=y. These are choices for this example. The test fraction is a proportion, the integer seed makes repeated calls reproducible, and stratification uses the supplied labels. The resulting arrays contain 105 training observations and 45 test observations.
  3. Construct and fit the estimator. Pass X_train and y_train to fit. Here priors=None leaves class priors unspecified, while var_smoothing=1e-9 explicitly records the documented default. Smoothing supports numerical stability; it is not a class-rebalancing option.
  4. Predict without refitting. Call predict(X_test) on the fitted object. Keep the test labels solely for evaluation. Calling fit again on the test subset would replace this evaluation with a different procedure.
  5. Report and inspect. Compare predicted with observed labels, print the classification report, and display the class order before interpreting probability columns. Save the output alongside the script so numerical results remain connected to their settings.

The syntax follows the official load_iris API, train_test_split API, and GaussianNB API. This complete example can be run as a Python script:

import sklearn
from sklearn.datasets import load_iris
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB

iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.30, random_state=42, stratify=y
)
model = GaussianNB(priors=None, var_smoothing=1e-9)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print('scikit-learn:', sklearn.__version__)
print('train/test:', X_train.shape, X_test.shape)
print('classes:', model.classes_)
print('errors:', int((y_test != y_pred).sum()))
print('accuracy:', model.score(X_test, y_test))
print(classification_report(
    y_test, y_pred, labels=model.classes_,
    target_names=iris.target_names[model.classes_], digits=3,
    zero_division=0
))
print('probability columns:', iris.target_names[model.classes_])
print('first probability row:', model.predict_proba(X_test[:1]))
print('means/variances:', model.theta_.shape, model.var_.shape)

Naive Bayes classifier sklearn arguments to preserve

For a methods record, separate the dataset settings, split settings and estimator settings. The same constructor can produce different evaluations if the observations assigned to training and testing change. Conversely, recording only the split seed leaves out the feature representation and the estimator’s assumptions. The data table below brings together the relevant API objects and reproduction checks from several documentation pages.

The matrix and target must describe the same observations in the same order. In the documented interface, X has shape (n_samples, n_features), and y has shape (n_samples,). In this script, splitting the two together preserves their pairing. A table of measurements and a separately sorted label column would no longer represent the same analysis, even if their lengths matched.

Output and how to read it

The following is the computed output of the illustrative script above. It contains four errors among 45 held-out observations: 41 correct predictions divided by 45 gives 0.911111…, displayed as 0.911 in the formatted report. This is a result for this partition of Iris, not an expected accuracy for new research data.

scikit-learn: 1.9.1
train/test: (105, 4) (45, 4)
classes: [0 1 2]
errors: 4
accuracy: 0.9111111111111111
              precision    recall  f1-score   support

      setosa      1.000     1.000     1.000        15
  versicolor      0.824     0.933     0.875        15
   virginica      0.923     0.800     0.857        15

    accuracy                          0.911        45
   macro avg      0.916     0.911     0.911        45
weighted avg      0.916     0.911     0.911        45

probability columns: ['setosa' 'versicolor' 'virginica']
first probability row: [[8.13304046e-287 4.09974086e-007 9.99999590e-001]]
means/variances: (3, 4) (3, 4)

Each class has 15 test observations in this split. The versicolor recall of 0.933 corresponds to 14 correct assignments out of 15; virginica recall of 0.800 corresponds to 12 out of 15. Together with 15 correct setosa assignments, those counts give the 41 correct classifications. This arithmetic makes the aggregate accuracy traceable to the individual classes.

classification_report prints precision, recall, F1 and support for each label. Its macro average treats classes equally, whereas its weighted average uses support. The equal supports here explain why the two displayed average rows match. digits=3 controls display precision; output_dict=True returns a dictionary without rounding the metric values to that display setting.

target_names must follow the order of labels. The example makes this relationship explicit with iris.target_names[model.classes_]. Probability columns likewise follow classes_. The first probability row strongly favours the third listed class, virginica; its location in the row matters as much as the number. Do not infer column meanings from an alphabetical list prepared separately.

Scikit-learn cautions that naive Bayes probability estimates can be poor even when classification is useful. A value close to one is therefore not, by itself, a validated frequency statement. If the task depends on trustworthy probabilities, classification accuracy alone is insufficient. To investigate which labels are confused, use a scikit-learn confusion matrix alongside the class report.

A methods record for this illustrative run

A concise record could read: “We fitted scikit-learn 1.9.1 GaussianNB to the four features returned by load_iris. We used a stratified 70:30 training/test split with random_state=42, priors=None and var_smoothing=1e-9. The held-out set contained 45 observations; 41 were classified correctly. We reported class-specific precision, recall, F1 and support.” This wording describes the executed example only. Replace its dataset, settings and results with the actual study details when reporting another analysis.

Troubleshooting

Check array shape and feature identity

A single observation still needs a two-dimensional feature matrix. The example uses X_test[:1], which keeps the sample dimension, for its first probability prediction. It also retains all four columns in their training order. As an analysis check, print the matrix shape and feature names before substituting your own measurements; compatible dimensions cannot establish that column meanings are correct.

Keep preprocessing inside the training procedure

The official common pitfalls guide recommends splitting before learning transformations. Fit any learned preprocessing on training data, then apply that fitted transformation to test data. A pipeline helps keep these operations together. Applying a transformation during training and omitting it at prediction changes the feature representation.

The Iris script uses its loaded numerical matrix directly. If you add feature selection, imputation or scaling, that becomes part of the analysis to document and validate. Do not use the held-out results to repeatedly choose preprocessing or model settings and then present that same subset as untouched evaluation data. The documentation specifically warns against using test data to make model choices.

Inspect undefined metrics rather than hiding them

The report call sets zero_division=0 explicitly. This chooses the returned value when a metric calculation divides by zero; it does not repair the predictions. The default 'warn' also returns zero in those cases and raises a warning. If a class has no predicted members or no observed support, inspect the labels, split and predictions before treating its report entry as an ordinary measured zero.

Do not interchange smoothing parameters

GaussianNB exposes var_smoothing; discrete naive Bayes models expose additive smoothing through alpha. They are different mechanisms. Copying an alpha argument into the Gaussian constructor does not specify its variance adjustment. If explicit priors are supplied, the GaussianNB documentation says they are not adjusted according to the data. Record such a choice instead of describing it as the default fit.

Supply the complete class list for incremental fitting

For data processed in batches, GaussianNB also provides partial_fit. The first call requires the complete list of possible class labels, including classes absent from that first batch. Later calls can omit that list. This is a separate workflow from the single fit call above: preserve the batch procedure in the analysis record rather than silently substituting it. The API also notes overhead from incremental updates, so batching is not automatically preferable for a small dataset already held in memory.

Free alternatives

Within scikit-learn’s BSD-licensed library, the following estimators are alternatives to the Gaussian model when the feature representation differs. They are all naive Bayes variants; switching one into this measurement example without reconsidering its assumptions would change the statistical model. The distinctions below come from the official naive Bayes guide.

Estimator Documented representation or role Distinction from this example
MultinomialNB Word counts; TF-IDF can also work Models count-like text features rather than Gaussian measurements
BernoulliNB Binary indicators Represents occurrence and absence rather than measurement magnitude
CategoricalNB Separate categorical distribution for each feature Requires per-feature category codes from zero through the number of categories minus one
ComplementNB Multinomial adaptation suited to imbalanced datasets Uses statistics from the complement of each class

Use this table to identify an assumption to investigate, rather than a promised winner. For a comparative analysis, write down the feature representation and evaluation procedure before interpreting a difference in scores. The reporting pattern shown above provides a consistent record of labels, class supports and outputs; it does not establish that two differently represented tasks are equivalent.

Sources

Data: Naive Bayes workflow settings and output checks

Original cross-document compilation of the loader, split, GaussianNB and reporting API semantics used in the Iris walkthrough. Reproduction checks are editorial applications of the cited API definitions; example choices are not universal recommendations.

Naive Bayes workflow settings and output checks
Object or settingDocumented meaningWalkthrough reproduction checkSource
load_iris().feature_namesNames of the dataset feature columnsKeep the loaded feature identity with the matrixhttps://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html
train_test_split: test_sizeA float specifies the proportion assigned to testingRecord the example choice 0.30https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
train_test_split: random_stateAn integer provides reproducible splits across callsRecord the example choice 42https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
GaussianNB: priorsExplicit priors are not adjusted according to the dataRecord None in this examplehttps://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html
GaussianNB: var_smoothingPortion of the largest feature variance added for stabilityRecord 1e-9 in this examplehttps://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html
GaussianNB: predict_probaProbability columns follow classes_Keep class names aligned with the printed columnshttps://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html
classification_report: target_namesDisplay names must follow the labels orderIndex target_names with model.classes_https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html
classification_report: zero_divisionControls the returned value for undefined divisionsRecord the example choice 0https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Scikit-learn Naive Bayes: Fit, Predict and Check

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →