Skip to content

A DVD rental company needs your help! They want to figure out how many days a customer will rent a DVD for based on some features and has approached you for help. They want you to try out some regression models which will help predict the number of days a customer will rent a DVD for. The company wants a model which yeilds a MSE of 3 or less on a test set. The model you make will help the company become more efficient inventory planning.

The data they provided is in the csv file rental_info.csv. It has the following features:

  • "rental_date": The date (and time) the customer rents the DVD.
  • "return_date": The date (and time) the customer returns the DVD.
  • "amount": The amount paid by the customer for renting the DVD.
  • "amount_2": The square of "amount".
  • "rental_rate": The rate at which the DVD is rented for.
  • "rental_rate_2": The square of "rental_rate".
  • "release_year": The year the movie being rented was released.
  • "length": Lenght of the movie being rented, in minuites.
  • "length_2": The square of "length".
  • "replacement_cost": The amount it will cost the company to replace the DVD.
  • "special_features": Any special features, for example trailers/deleted scenes that the DVD also has.
  • "NC-17", "PG", "PG-13", "R": These columns are dummy variables of the rating of the movie. It takes the value 1 if the move is rated as the column name and 0 otherwise. For your convinience, the reference dummy has already been dropped.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error 
from sklearn.model_selection import RandomizedSearchCV,train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Lasso
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor

df = pd.read_csv('rental_info.csv')
print(df.isna().sum())
df['rental_length'] = pd.to_datetime(df['return_date']) - pd.to_datetime(df['rental_date'])
df['rental_length_days'] = df['rental_length'].dt.days
df['deleted_scenes'] = np.where(df['special_features'].str.contains("Deleted Scenes"),1 ,0)
df['behind_the_scenes'] = np.where(df['special_features'].str.contains("Behind the Scenes"),1,0)

columns_drop = ['special_features','rental_length','return_date','rental_date', 'rental_length_days']
X = df.drop(columns_drop, axis=1)
y = df['rental_length_days']

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2, random_state = 9)

lasso = Lasso(random_state = 9)
lasso.fit(X_train,y_train)
lasso_pred = lasso.predict(X_test)
lasso_rsme = mean_squared_error(y_test,lasso_pred)

lr = LinearRegression()
lr.fit(X_train,y_train)
lr_pred = lr.predict(X_test)
lr_rsme = mean_squared_error(y_test,lr_pred)


rf = RandomForestRegressor()
rf.fit(X_train,y_train)
rf_pred = rf.predict(X_test)
rf_rsme = mean_squared_error(y_test,rf_pred)

print("The mean squared error of Lasso is : {}".format(lasso_rsme))
print("The mean squared error of LinearRegression is : {}".format(lr_rsme))
print("The mean squared error of RandomForest is : {}".format(rf_rsme))

"""
The best model untuned is RandomForestRegressor with the lowest MSE, so it will be our model for this data set.
"""
best_model = rf
best_mse = rf_rsme

plt.figure(figsize=(8, 6))
plt.scatter(y_test, rf_pred, color='green')
plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], color='red')  # 
plt.title('Actual vs. Predicted Values')
plt.xlabel('Actual')
plt.ylabel('Predicted')
plt.grid(True)
plt.show()