Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Classification lessons
Probabilities and neighbours · ML-C04 · 12–18 MIN

Labels and probabilities

Align probability columns with class labels.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeAdapt the Python
  3. TransferAdapt the Python

Understand the idea

predict_proba columns follow classes_, not a guessed order. Thresholds turn binary probabilities into labels; multiclass prediction usually chooses the largest class score.

Align probability columns with class labels.RowP(A)P(B)new 1.8.2new 2.4.6new 3.1.9Probability columns follow model.classes_; each row sums to 1.
Align probability columns with class labels.Scroll the diagram horizontally if needed.

What the syntax does

model.classes_
  • Gives the fitted class order used by probability columns.

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[['length', 'width']]
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.
CLASS180 · first 8 rows
lengthwidthlabel
236.033-0.805568A
581.2970.728558A
-1511.27-1.00866A
99.0248-0.24496A
-13.0141-0.660765A
681.1790.602475A
51.14720.873157A
362.131-0.665605A
Your task
  1. Create a dataframe of test probabilities with the actual class labels as columns.
answer
Hints

Think: Probability columns follow the estimator’s fitted class order.

Tools: predict_proba, classes_ and dataframe index.

Approach: Build the probability table with test-row indices and fitted class names.

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

Explicit row and class labels prevent a probability column from being attributed to the wrong observation or class.

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.