Model Fitting on a Loss Function
This lesson will focus on implementing the mean squared error loss function in Python and applying optimization to obtain the best performing model.
We'll cover the following...
In the last lesson, we learned how loss functions can be used in theory to find out the best model for our problem. Now, we need to implement the mean squared error function in Python to our dataset.
Coding up the loss function
First, we will write the MSE (mean squared error) function, and then use that on our dataset.
def mse_loss(y_pred,y_actual):sq_error = (y_pred - y_actual)**2loss = sq_error.mean()return loss
We define a function that will work on two columns of dataframe, i.e., Series objects. We have two input series y_pred
which has predicted values and y_actual
which has the actual values. In line 2, we first calculate the error and then take the square by using the **
operator. Since these are Series objects, Python will automatically subtract the corresponding y_actual
and y_pred
values. In the next line, we use the function mean
on sq_error
and return the loss
.
Getting predictions
Now we will get predictions using the data that we have for a single model parameter and then compute the loss for that model.
import pandas as pd# define our loss fucntiondef mse_loss(y_pred,y_actual):sq_error = (y_pred - y_actual)**2loss = sq_error.mean()return loss# read the filedf = pd.read_csv('tips.csv')# compute predicted valuestheta = 0.15predicted_values = theta * df['total_bill']#compute lossloss = mse_loss(y_pred = predicted_values, y_actual = df['tip'])print(loss)
We define our function, mse_loss
, in lines 4-7. Then we read the data in line 10. After that we compute the predicted values in line 14 by multiplying theta
with total_bill
column. This gives us predicted values for each row in the dataset. Next, we compute the loss in line 17. We use the function mse_loss
defined above. We give predicted_values
as y_pred
and the column tip
as ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy