liveBook · Manning

Indicator function

As explained in Machine Learning Algorithms in Depth

An indicator function returns one when a stated condition is true and zero otherwise.

An indicator function turns a condition into a number: 1[A] equals 1 if A is true and 0 otherwise. It lets a sum or average count only the cases that satisfy A. section 2.2 section 1.1

For a circle of radius R, 1[x² + y² ≤ R²] selects points inside the circle. Draw N points uniformly from the square [−R, R] × [−R, R]. The square has area 4R², so the estimated circle area is (4R²/N)Σᵢ1[xᵢ² + yᵢ² ≤ R²]. Dividing by R² gives π̂ = (4/N)Σᵢ1[xᵢ² + yᵢ² ≤ R²]. Each draw contributes either 4/N or zero to the estimate. section 2.2

Counting classification mistakes

For predictions f(xᵢ; θ) and true labels yᵢ, 1[f(xᵢ; θ) ≠ yᵢ] marks a mistake. Averaging these indicators over n examples gives the misclassification rate. With ±1 labels, a binary classifier can instead count mistakes when the true and predicted labels have a negative product. section 1.1 section 5.2

Listing 2.1 Pi estimator
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)     #1

def pi_est(radius=1, num_iter=int(1e4)):     #2


    X = np.random.uniform(-radius,+radius,num_iter)
    Y = np.random.uniform(-radius,+radius,num_iter)

    R2 = X**2 + Y**2
    inside = R2 < radius**2
    outside = ~inside

    samples = (2*radius)*(2*radius)*inside

    I_hat = np.mean(samples)
    pi_hat = I_hat/radius ** 2     #3
    pi_hat_se = np.std(samples)/np.sqrt(num_iter)    #4
    print("pi est: {} +/- {:f}".format(pi_hat, pi_hat_se))

    plt.figure()
    plt.scatter(X[inside],Y[inside], c='b', alpha=0.5)
    plt.scatter(X[outside],Y[outside], c='r', alpha=0.5)
    plt.show()

if __name__ == "__main__":

    pi_est()

The NumPy pi estimator forms an inside-circle Boolean array, scales it by the square’s area, and averages it before dividing by R². Its scatter plot distinguishes accepted and rejected samples. section 2.2

How Machine Learning Algorithms in Depth covers it

How deep it goes
Defines the notation, derives its role in a Monte Carlo pi estimate, and implements that estimate with a Boolean array.
Examples
Uses points inside a circle, a NumPy pi estimator, and mismatches between predicted and true labels.
What it assumes
Assumes familiarity with Boolean comparisons, averages, uniform sampling, and classifier predictions while defining indicator notation explicitly.
What you can do after
Build it from scratch to estimate pi from uniform samples or compute a classification mistake rate from labels.
How it connects
Links Monte Carlo integration to sample averages and connects classification loss to misclassification rate and binary classifiers.

Also explained in

Compare how 2 books explain indicator function →

This explainer was generated by Manning's knowledge graph from the text of Machine Learning Algorithms in Depth. The section links point to the parts of the book it draws on.