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:
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
EasyA 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature Grid3Array Math
Math on Whole ArraysSummary StatisticsStatistics by AxisBroadcastingBoolean MasksRecap: Exam Scores9Grouping and Cleaning
Counting ValuesGrouping DataSeveral SummariesMissing ValuesRecap: Survey ResultsPractice on your own: Online Python compiler