Menu
CoddyTech

Broadcasting

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 13 of 60.

Models learn better when every feature sits around 0. So you subtract each column's mean from its column, and NumPy copies the means down every row:

The 3 by 2 table of heights and weights, minus the means row 170 and 70 copied down all three rows, equals the centered table: 0 and -10, 10 and 10, -10 and 0

In code, for three people's heights and weights:

data = np.array([[170, 60],
                 [180, 80],
                 [160, 70]])
print(data - data.mean(axis=0))

This prints:

[[  0. -10.]
 [ 10.  10.]
 [-10.   0.]]

That copying is broadcasting. The table is now centered: each value says how far it sits from its column's mean.

The means have shape (2,): one value per column of the (3, 2) table. Any other length stops with an error.

challenge icon

Challenge

Easy

A fitness app centers every table before training. The starter calls center on two tables, users (3 features) and workouts (2), and prints the results. Right now center returns the table unchanged.

Complete center so it subtracts each column's mean from that column, for any number of columns. Leave the lines below it as they are.

With two users and two workouts, the output would look like this:

Centered users:
[[-6.  7. -5.]
 [ 6. -7.  5.]]
Column means after centering: [0. 0. 0.]
Centered workouts:
[[-10. -90.]
 [ 10.  90.]]
Column means after centering: [0. 0.]

Try it yourself

import numpy as np


def center(table):
    # Return table with each column's mean subtracted
    # Write your code below
    return table


# One row per user: age, resting heart rate, minutes of exercise per day
users = np.array([[25, 62, 30],
                  [31, 70, 45],
                  [40, 58, 20],
                  [29, 66, 25]])
# One row per workout: minutes, calories burned
workouts = np.array([[30, 240],
                     [45, 410],
                     [20, 150],
                     [60, 520],
                     [35, 300]])

# Don't change the lines below
print("Centered users:")
print(center(users))
print("Column means after centering:", np.round(center(users).mean(axis=0), 2))
print("Centered workouts:")
print(center(workouts))
print("Column means after centering:", np.round(center(workouts).mean(axis=0), 2))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler