Compute Binary Log-Loss With sklearn.metrics.log_loss
Quick Overview
Compute the mean binary log-loss for 0/1 labels and positive-class probabilities using scikit-learn's log_loss. It tests how the metric reads a 1-D probability array, how it infers the label set, and what happens with single-class batches or probabilities at 0 or 1.
Compute Binary Log-Loss With sklearn.metrics.log_loss
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `sklearn_binary_log_loss(y_true, y_pred)`. `y_true` is a 1-D array of 0/1 labels of shape `(n,)` containing both classes, and `y_pred` is a 1-D array of shape `(n,)` of positive-class probabilities P(y=1). Return the mean per-sample log-loss as a Python `float`.
Call `sklearn.metrics.log_loss` with the 1-D probabilities directly (no `(n, 2)` form needed).
Example:
```python
y_true = [1, 0, 1, 1, 0]
y_pred = [0.9, 0.1, 0.8, 0.6, 0.3]
sklearn_binary_log_loss(np.array(y_true), np.array(y_pred))
# -> 0.26027303006691704
```
```hint Know what the metric expects
Look up how `log_loss` interprets a 1-D `y_pred`, and how it works out which labels exist when you do not pass them.
```
### Constraints & Assumptions
- `y_true` and `y_pred` have the same length n.
- `y_true` contains only 0 and 1, and both classes appear at least once.
- `y_pred` holds the probability of label 1 for each sample.
### What a Strong Answer Covers
- Passing the labels and the 1-D positive-class probabilities straight to `log_loss`, in the order `(y_true, y_pred)`.
- How sklearn reads a 1-D `y_pred` as P(y=1) and builds the negative-class column itself.
- Why the "both classes present" condition matters, and what to pass when a batch has only one class.
- Returning a plain Python `float`.
- What sklearn does with probabilities of exactly 0 or 1.
### Follow-up Questions
- A validation batch contains only positive labels. What does `log_loss` do, and how do you change the call?
- What would the loss look like if someone passed `model.predict(X)` (hard 0/1 labels) instead of probabilities?
- How would you weight some samples more than others in this metric?
- A from-scratch NumPy version and sklearn disagree when a prediction is exactly 0 or 1. Why?
Overview: Compute the mean binary log-loss for 0/1 labels and positive-class probabilities using scikit-learn's log_loss. It tests how the metric reads a 1-D probability array, how it infers the label set, and what happens with single-class batches or probabilities at 0 or 1.
Compute Binary Log-Loss With sklearn.metrics.log_loss
General
Nov 24, 2026
easyData ScientistOtherMachine Learning
0
0
Implement sklearn_binary_log_loss(y_true, y_pred). y_true is a 1-D array of 0/1 labels of shape (n,) containing both classes, and y_pred is a 1-D array of shape (n,) of positive-class probabilities P(y=1). Return the mean per-sample log-loss as a Python float.
Call sklearn.metrics.log_loss with the 1-D probabilities directly (no (n, 2) form needed).