What are the coordinates of the point of intersection of the two lines above?
Solution
The two lines intersect at (xΛ,yΛβ)β.
The best constant model is the horizontal line y=yΛβ. To see where the regression line meets it, recall that w0ββ=yΛββw1ββxΛ. Plugging x=xΛ into the regression line gives:
So, both models predict the average commute time at the average departure time. The regression line shown has a non-zero slope, so this is its only intersection with the horizontal line.
A fact we mentioned earlier β and you restated in Homework 1 β is that the mean squared error of the best constant model is the variance of the data. We can see this by substituting wβ=yΛβ into mean squared error:
This gives us a nice baseline from which to compare the performance of more sophisticated models. If a model we create has a mean squared error thatβs higher than the variance of the data, we know weβve done something wrong, because a constant model would be better!
The mean squared error of the best simple linear regression model on the data is:
This formula alone isnβt particularly enlightening, but it turns out this is equivalent to Οy2β(1βr2), where r is the correlation coefficient between x and y. (The proof of this is an optional component of Homework 2.)
This means that the best simple linear regression model canβt perform worse than the best constant model. If r=0, then the best simple linear regression model has a slope of 0, and is just the best constant model! Otherwise, the best simple linear regression model will have a non-zero slope, which is chosen to minimize mean squared error.
Least squares is the general term for minimizing mean squared error β or equivalently, the sum of squared errors β to find optimal model parameters. Least squares appears quite frequently outside of machine learning contexts, too.
I glossed over something important above. I said that minimizing mean squared error is equivalent to minimizing the sum of squared errors.
Why is that true? Letβs consider a particular example, of finding w0ββ and w1ββ for the simple linear regression model h(xiβ)=w0β+w1βxiβ.
The two functions differ only by a positive constant factor:
Rsqβ(w0β,w1β)=n1βSsqβ(w0β,w1β)
Here, n is the number of points in our fixed dataset. It doesnβt change when we change w0β or w1β.
If one pair of parameters gives a smaller sum of squared errors than another pair, dividing both sums by the same positive number n preserves that comparison. So, the pair that gives the smallest sum also gives the smallest average.
The minimum values of the two functions can be different, but the parameters where those minima occur are the same. Multiplying the height of a loss surface by a positive constant doesnβt move its lowest point!
For example, population ecologists use least squares to model the growth of populations (say, of an animal species) over time.
import numpy as np
import plotly.graph_objects as go
from scipy.optimize import curve_fit
# Generate data
np.random.seed(0)
x = np.linspace(0, 2, 30)
y_true = 3 * np.exp(2 * x)
noise = np.random.normal(0, 0.2 * y_true, size=x.shape)
y = y_true + noise
# Define the model function
def exp_model(x, a, b):
return a * np.exp(b * x)
# Fit the model to the data
z = np.log(y)
w1, w0 = np.polyfit(x, z, 1)
a_fit, b_fit = np.e ** w0, w1
# Prepare fitted curve
x_fit = np.linspace(x.min(), x.max(), 200)
y_fit = (np.e ** (w0)) * np.e ** (w1 * x_fit)# * #exp_model(x_fit, a_fit, b_fit)
# Plot with plotly and custom style
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x, y=y, mode='markers', name='Data',
marker=dict(color='#3d81f6', size=8, opacity=0.8)
))
fig.add_trace(go.Scatter(
x=x_fit, y=y_fit, mode='lines',
name=f'Fit: y = {a_fit:.2f} e^{{{b_fit:.2f}x}}',
line=dict(color='orange', width=3)
))
fig.update_layout(
xaxis_title='x',
yaxis_title='y',
legend_title='Legend',
width=800,
height=500,
font=dict(family='Palatino, serif', size=16),
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False,
annotations=[
dict(
xref='paper', yref='paper',
x=0.5, y=1.08, showarrow=False,
text=fr'$$h(x_i) = {a_fit:.2f} e^{{{b_fit:.2f}x}}$$',
font=dict(size=40, family='Palatino, serif'),
xanchor='center'
)
]
)
fig.update_xaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif')
)
fig.update_yaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif'),
)
fig.show(renderer='png', scale=3)
The orange curve above is of the form h(xiβ)=aebxiβ, where a and b are parameters. Iβve chosen the form aebxiβ because itβs a good fit for the data; itβs how we model exponential growth.
a and bcould be chosen by minimizing mean squared error directly:
Rsqβ(a,b)=n1βi=1βnβ(yiββaebxiβ)2
If we wanted to minimize Rsqβ(a,b), weβd need to take partial derivatives with respect to a and b, set them to 0, and solve the resulting system of equations. However, the function h(xiβ)=aebxiβ involves a parameter (b) in the exponent, which means the resulting partial derivatives of Rsqβ will be complicated and the resulting system of equations will be challenging to solve. (Donβt believe me? Try finding βbβRsqββ.)
In this particular case, thereβs a transformation we can apply to the data so that we can reduce the minimization problem to something weβve seen before! Consider what happens if we take the logarithm of both sides of the equation yiββaebxiβ:
yiββaebxiββΉlog(yiβ)βlog(a)+bxiβ
Iβve written the β symbol to remind us that yiβ is not exactly equal to aebxiβ, but rather, the goal is to choose a and b so that aebxiβ is approximately equal to yiβ, across all points i.
When we take the logarithm of each y-value in our dataset, the resulting plot looks like:
import numpy as np
import plotly.graph_objects as go
# Generate data
np.random.seed(0)
x = np.linspace(0, 2, 30)
y_true = 3 * np.exp(2 * x)
noise = np.random.normal(0, 0.2 * y_true, size=x.shape)
y = y_true + noise
# Take the log of each y value
log_y = np.log(y)
# Plot just the data (x vs log(y))
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x, y=log_y, mode='markers', name='log(y)',
marker=dict(color='#3d81f6', size=8, opacity=0.8)
))
fig.update_layout(
xaxis_title='x',
yaxis_title='log(y)',
width=800,
height=500,
font=dict(family='Palatino, serif', size=16),
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False
)
fig.update_xaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif')
)
fig.update_yaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif'),
)
fig.show(renderer='png', scale=3)
The transformed data looks roughly linear!
How does this transformation help us find a and b? Now, instead of minimizing:
Rsqβ(a,b)=n1βi=1βnβ(yiββaebxiβ)2
Iβm claiming that since log(yiβ)βlog(a)+bxiβ, we can instead minimize:
We just spent all of Chapter 2.3 finding the optimal values of w0ββ and w1ββ in the empirical risk function above, so the optimal values of w0ββ and w1ββ are well known to us!
Note that Iβve computed w0ββ=1.24 and w1ββ=1.92 using the transformed data, (x1β,z1β),β¦,(xnβ,znβ). On the transformed data, this line looks like:
import numpy as np
import plotly.graph_objects as go
# Generate data
np.random.seed(0)
x = np.linspace(0, 2, 30)
y_true = 3 * np.exp(2 * x)
noise = np.random.normal(0, 0.2 * y_true, size=x.shape)
y = y_true + noise
# Take the log of each y value
log_y = np.log(y)
# Fit a line: log_y = w0 + w1 * x
w1, w0 = np.polyfit(x, log_y, 1)
line_y = w0 + w1 * x
# Plot data and fitted line
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x, y=log_y, mode='markers', name='log(y)',
marker=dict(color='#3d81f6', size=8, opacity=0.8)
))
fig.add_trace(go.Scatter(
x=x, y=line_y, mode='lines', name='Fitted line',
line=dict(color='orange', width=3)
))
# Equation string for annotation
eqn = f"$$\log(y_i) \\approx {w0:.2f} + {w1:.2f}x_i$$"
fig.update_layout(
xaxis_title='x',
yaxis_title='log(y)',
width=800,
height=500,
font=dict(family='Palatino, serif', size=16),
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False,
annotations=[
dict(
xref='paper', yref='paper',
x=0.5, y=1.08, showarrow=False,
text=eqn,
font=dict(size=40, family='Palatino, serif'),
xanchor='center'
)
]
)
fig.update_xaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif')
)
fig.update_yaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif'),
)
fig.show(renderer='png', scale=3)
How do we turn this back into a curve on the original data? To transform the data, we applied the following substitutions that we need to invert:
w0β=log(a)βΉa=ew0βb=w1β
So, using the above, we can find:
aβ=ew0ββ=e1.24=3.46bβ=w1ββ=1.92
So, the curve weβre looking for is:
h(xiβ)=3.46e1.92xiβ
And this is the equation of the orange curve I first showed you!
import numpy as np
import plotly.graph_objects as go
from scipy.optimize import curve_fit
# Generate data
np.random.seed(0)
x = np.linspace(0, 2, 30)
y_true = 3 * np.exp(2 * x)
noise = np.random.normal(0, 0.2 * y_true, size=x.shape)
y = y_true + noise
# Define the model function
def exp_model(x, a, b):
return a * np.exp(b * x)
# Fit the model to the data
z = np.log(y)
w1, w0 = np.polyfit(x, z, 1)
a_fit, b_fit = np.e ** w0, w1
# Prepare fitted curve
x_fit = np.linspace(x.min(), x.max(), 200)
y_fit = (np.e ** (w0)) * np.e ** (w1 * x_fit)# * #exp_model(x_fit, a_fit, b_fit)
# Plot with plotly and custom style
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x, y=y, mode='markers', name='Data',
marker=dict(color='#3d81f6', size=8, opacity=0.8)
))
fig.add_trace(go.Scatter(
x=x_fit, y=y_fit, mode='lines',
name=f'Fit: y = {a_fit:.2f} e^{{{b_fit:.2f}x}}',
line=dict(color='orange', width=3)
))
fig.update_layout(
xaxis_title='x',
yaxis_title='y',
legend_title='Legend',
width=800,
height=500,
font=dict(family='Palatino, serif', size=16),
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False,
annotations=[
dict(
xref='paper', yref='paper',
x=0.5, y=1.08, showarrow=False,
text=fr'$$h(x_i) = {a_fit:.2f} e^{{{b_fit:.2f}x}}$$',
font=dict(size=40, family='Palatino, serif'),
xanchor='center'
)
]
)
fig.update_xaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif')
)
fig.update_yaxes(
showgrid=True,
gridcolor='#f0f0f0',
zeroline=False,
showline=True,
linecolor='black',
ticks='outside',
tickfont=dict(family='Palatino, serif'),
)
fig.show(renderer='png', scale=3)
Not every least squares problem can be reduced to the simple linear regression problem weβve been studying. But, in the rare cases that it can, itβs satisfying to be able to reuse our work.
Following Chapter 2.3, the next natural question to ask is, how do we use multiple features (input variables) to make predictions?
When we first introduced the commute times example back in Chapter 1.2, we saw that the dataset weβre working with has a few features beyond the departure hour.
Up until now, weβve been using the departure_hour feature to predict the minutes column.
It would be great if we could figure out a way to use the day of the week as a feature, since our intuition tells us this might have an effect on commute times (traffic is known to be bad on Monday mornings and Friday afternoons). But, the day column currently contains strings, not numbers, so weβll have to think critically about how to encode this data numerically. (Youβll see how to do this in a later homework.)
For now, letβs extract the day of the month from the date column, and try and use day_of_month along with departure_hour as our two features.
This is called a multiple linear regression model, since it uses multiple features. (To keep the equation short, Iβve used dom to refer to the day of the month.)
The first hypothesis function, with one input variable, looked like a line in two dimensions. Our new multiple linear regression model looks like a plane in three dimensions!
from pathlib import Path
import sys
_notes_root = next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / 'myst.yml').exists())
if str(_notes_root) not in sys.path:
sys.path.insert(0, str(_notes_root))
from plane_style import (BLUE, ORANGE, PINK, GRAY, plane_figure, add_plane,
vector3, vector_label, line3, label3,
style_surface_planes, projection_figure)
import numpy as np
import plotly.graph_objects as go
from sklearn.linear_model import LinearRegression
import numpy as np
import plotly.graph_objs as go
# Prepare features and target
X = df[['departure_hour', 'day_of_month']].values
y = df['minutes'].values
# Fit linear regression
model = LinearRegression()
model.fit(X, y)
# Create grid for plane
departure_hour_range = np.linspace(df['departure_hour'].min(), df['departure_hour'].max(), 30)
day_of_month_range = np.linspace(df['day_of_month'].min(), df['day_of_month'].max(), 30)
dh_grid, dom_grid = np.meshgrid(departure_hour_range, day_of_month_range)
X_grid = np.c_[dh_grid.ravel(), dom_grid.ravel()]
y_pred_grid = model.predict(X_grid).reshape(dh_grid.shape)
# Scatter plot for data points
scatter = go.Scatter3d(
x=df['departure_hour'],
y=df['day_of_month'],
z=df['minutes'],
mode='markers',
marker=dict(size=6, color='#3d81f6'),
name='Data'
)
# Surface plot for regression plane
surface = go.Surface(
x=dh_grid,
y=dom_grid,
z=y_pred_grid,
colorscale='OrRd',
opacity=0.7,
showscale=False,
name='Prediction Plane'
)
fig = go.Figure(data=[surface, scatter])
fig.update_layout(
scene=dict(
xaxis_title='Departure Time',
yaxis_title='Day of Month',
zaxis_title='Commute Time (Minutes)',
xaxis=dict(
backgroundcolor='white',
gridcolor='#f0f0f0',
zerolinecolor='#f0f0f0'
),
yaxis=dict(
backgroundcolor='white',
gridcolor='#f0f0f0',
zerolinecolor='#f0f0f0'
),
zaxis=dict(
backgroundcolor='white',
gridcolor='#f0f0f0',
zerolinecolor='#f0f0f0'
),
bgcolor='white'
),
scene_camera=dict(
eye=dict(x=1.5, y=-1.5, z=0.2)
),
font=dict(family='Palatino, serif', size=12),
height=500,
width=700
)
style_surface_planes(fig, [0], colors=[ORANGE], height=520)
fig.show(renderer='plotly_mimetype')
Loading...
In two dimensional space, a line has a constant rate of change, described by its slope.
In three dimensional space, a plane has a constant rate of change along both the x and y axes. The planeβs rate of change in the x (departure time) direction is given by w1ββ, and its rate of change in the y (day of month) direction is given by w2ββ.
Finding the optimal values of w0ββ, w1ββ, and w2ββ involves minimizing, yet again, mean squared error:
Mean squared error here is a function of three variables, so weβd need four dimensions to visualize it, which, of course, we cannot do. To minimize Rsqβ above, weβd need to find three partial derivatives, set them all to 0, and solve the resulting system of 3 equations and 3 unknowns.
While we could do this, eventually, weβll want to consider a third feature, a fourth, and so on. In general, if we want d features, weβll have d+1 parameters to optimize (one per feature, plus one for the intercept, w0β), and weβll need to solve a system of d+1 equations and d+1 unknowns to find them. Continuing this approach sounds painful.
This is where linear algebra comes in. Linear algebra provides a compact, efficient way to represent and manipulate systems of linear equations, and to find solutions to them.
Chapters 3 through 6 are dedicated to introducing the ideas from linear algebra that weβll need to solve this problem: the problem of finding the parameters that minimize mean squared error for the multiple linear regression model. It will take some time to get there, and at times, itβll seem like what weβre doing is unrelated to this goal of finding optimal parameters.
But, I promise that we will close the loop in Chapter 7, when we return to multiple linear regression.