Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Classification lessons
Class distributions · ML-C15 · 25–40 MIN

Gaussian Naive Bayes

Combine class priors with continuous feature evidence.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeCompute and inspect the evidence
  3. TransferCompute and inspect the evidence
  4. ApplyBuild a guided full workflow

Understand the idea

GaussianNB models each feature’s class-conditional density and combines evidence using a conditional-independence assumption. Posterior class probabilities and probability densities are different quantities.

Combine class priors with continuous feature evidence.Class AClass BGaussian NB: independent feature likelihoods within a class.
Combine class priors with continuous feature evidence.Scroll the diagram horizontally if needed.

What the syntax does

model.class_prior_
  • Reads the fitted probability assigned to each class before feature evidence.

Supplied for this practice

These objects are prepared afresh before your editor runs.

X
Feature dataframe for the declared population, preserving row indices.
X = df[['x1', 'x2']]
y
Target series, aligned with X.
y = df.label
X_train / X_test / y_train / y_test
Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with X_train. Final-test targets, aligned with X_test.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model
Already fitted on X_train, y_train. Fitted estimator or pipeline for the requested model family. Fitted on X_train, y_train; reuse without refitting.

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
priors
  1. Fitted class prior probabilities in the estimator’s class order.
COV90 · first 8 rows
x1x2label
-0.878151-0.683719A
-2.05616-0.327603A
1.30311.29443A
-0.995383-0.240343A
-0.654128-0.314893A
-2.112-0.509527A
-1.497460.375701A
-1.09822-0.763825A
Your task
  1. Store posterior class probabilities in answer, indexed by X_test rows and labelled by model.classes_.
  2. Store the fitted class priors in priors, in that same class order.
answerpriors
Hints

Think: Posterior columns and prior entries both follow fitted class order.

Tools: predict_proba, classes_ and class_prior_.

Approach: Label posterior probabilities by test row and class, then inspect the fitted priors.

Explained solution
answer=pd.DataFrame(model.predict_proba(X_test),columns=model.classes_,index=X_test.index)
priors=model.class_prior_

The labelled table distinguishes row-specific posterior evidence from the model’s overall class-prior frequencies.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.