The Wayback Machine - https://web.archive.org/web/20241004223510/https://www.geeksforgeeks.org/box-office-revenue-prediction-using-linear-regression-in-ml/
Open In App

Box Office Revenue Prediction Using Linear Regression in ML

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When a movie is produced then the director would certainly like to maximize his/her movie’s revenue. But can we predict what will be the revenue of a movie by using its genre or budget information? This is exactly what we’ll learn in this article, we will learn how to implement a machine learning algorithm that can predict a box office revenue by using the genre of the movie and other related features.

Importing Libraries and Dataset

Python libraries make it easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib/Seaborn – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries are having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
  • XGBoost – This contains the eXtreme Gradient Boosting machine learning algorithm which is one of the algorithms which helps us to achieve high accuracy on predictions.
Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import metrics
from xgboost import XGBRegressor

import warnings
warnings.filterwarnings('ignore')

Now load the dataset into the panda’s data frame.

Python
df = pd.read_csv('boxoffice.csv',
                 encoding='latin-1')
df.head()

Output:

Screenshot-2024-09-29-165741

df.head()

Now let’s check the size of the dataset.

Python
df.shape

Output:

(2694, 10)

Let’s check which column of the dataset contains which type of data.

Python
df.info()

Output:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2694 entries, 0 to 2693
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 title 2694 non-null object
1 domestic_revenue 2694 non-null int64
2 world_revenue 2694 non-null int64
3 distributor 2694 non-null object
4 opening_revenue 2694 non-null int64
5 opening_theaters 2694 non-null int64
6 budget 2694 non-null int64
7 MPAA 2694 non-null object
8 genres 2694 non-null object
9 release_days 2694 non-null int64
dtypes: int64(6), object(4)
memory usage: 210.6+ KB

Here we can observe an unusual discrepancy in the dtype column the columns which should be in the number format are also in the object type. This means we need to clean the data before moving any further.

Python
df.describe().T

Output:

Screenshot-2024-09-29-165834

Describe

Data Cleaning

There are times when we need to clean the data because the raw data contains lots of noise and irregularities and we cannot train an ML model on such data. Hence, data cleaning is an important part of any machine-learning pipeline.

Python
# We will be predicting only
# domestic_revenue in this article.

to_remove = ['world_revenue', 'opening_revenue']
df.drop(to_remove, axis=1, inplace=True)

Let’s check what is the percentage of entries in each column that is null.

Python
df.isnull().sum() * 100 / df.shape[0]

Output :

Screenshot-2024-09-29-165843

percentage of entries in each column that is null


Python
# Handling the null value columns
df.drop('budget', axis=1, inplace=True)

for col in ['MPAA', 'genres']:
    df[col] = df[col].fillna(df[col].mode()[0])

df.dropna(inplace=True)

df.isnull().sum().sum()

Output:

0
Python
df['domestic_revenue'] = df['domestic_revenue'].astype(str).str[1:]

for col in ['domestic_revenue', 'opening_theaters', 'release_days']:
    df[col] = df[col].astype(str).str.replace(',', '') 

    # Selecting rows with no null values 
    # in the columns on which we are iterating. 
    temp = (~df[col].isnull()) 
    df[temp][col] = df[temp][col].convert_dtypes(float) 

    df[col] = pd.to_numeric(df[col], errors='coerce')
    
# This code is modified by Susobhan Akhuli

Exploratory Data Analysis

EDA is an approach to analyzing the data using visual techniques. It is used to discover trends, and patterns, or to check assumptions with the help of statistical summaries and graphical representations. 

Python
plt.figure(figsize=(10, 5))
sb.countplot(df['MPAA'])
plt.show()

Output:

download

countplot

Python
df.groupby('MPAA')['domestic_revenue'].mean()

# This code is modified by Susobhan Akhuli

Output:

MPAA    domestic_revenue
G 3.426099e+07
NC-17 3.452006e+07
PG 3.697347e+07
PG-13 3.510989e+07
R 3.670206e+07

dtype: float64

Here we can observe that the movies with PG or R ratings generally have their revenue higher than the other rating class.

Python
plt.subplots(figsize=(15, 5))

features = ['domestic_revenue', 'opening_theaters', 'release_days']
for i, col in enumerate(features):
    plt.subplot(1, 3, i+1)
    sb.distplot(df[col])
plt.tight_layout()
plt.show()

Output:

downlo

distplot

Python
plt.subplots(figsize=(15, 5))
for i, col in enumerate(features):
    plt.subplot(1, 3, i+1)
    sb.boxplot(df[col])
plt.tight_layout()
plt.show()

Output:

do

Outliers

Certainly, there are no outliers in the above features.

Python
for col in features:
  df[col] = df[col].apply(lambda x: np.log10(x))

Now the data in the columns we have visualized above should be close to normal distribution.

Python
plt.subplots(figsize=(15, 5))
for i, col in enumerate(features):
    plt.subplot(1, 3, i+1)
    sb.distplot(df[col])
plt.tight_layout()
plt.show()

Output:

downl

normal distribution

Creating Features from the Genre

Python
vectorizer = CountVectorizer() 
vectorizer.fit(df['genres']) 
features = vectorizer.transform(df['genres']).toarray() 

genres = vectorizer.get_feature_names_out() 
for i, name in enumerate(genres): 
    df[name] = features[:, i] 

df.drop('genres', axis=1, inplace=True)

# This code is modified by Susobhan Akhuli

But there will be certain genres that are not that frequent which will lead to increases in the complexity of the model unnecessarily. So, we will remove those genres which are very rare.

Python
removed = 0
# Check if 'action' and 'western' columns exist before slicing
if 'action' in df.columns and 'western' in df.columns:
    for col in df.loc[:, 'action':'western'].columns: 

        # Removing columns having more 
        # than 95% of the values as zero. 
        if (df[col] == 0).mean() > 0.95: 
            removed += 1
            df.drop(col, axis=1, inplace=True) 

print(removed) 
print(df.shape)

# This code is modified by Susobhan Akhuli

Output:

0
(2694, 12)
Python
for col in ['distributor', 'MPAA']:
    le = LabelEncoder()
    df[col] = le.fit_transform(df[col])

As all the categorical features have been labeled encoded let’s check if there are highly correlated features in the dataset.

Python
plt.figure(figsize=(8, 8))
sb.heatmap(df.select_dtypes(include=np.number).corr() > 0.8, 
            annot=True, 
            cbar=False) 
plt.show()

# This code is modified by Susobhan Akhuli

Output:

downl

heatmap

Model Development

Now we will separate the features and target variables and split them into training and the testing data by using which we will select the model which is performing best on the validation data.

Python
features = df.drop(['title', 'domestic_revenue'], axis=1) 
target = df['domestic_revenue'].values 

X_train, X_val, Y_train, Y_val = train_test_split(features, target, 
                                    test_size=0.1, 
                                    random_state=22) 
X_train.shape, X_val.shape 

# This code is modified by Susobhan Akhuli

Output:

((2424, 10), (270, 10))
Python
# Normalizing the features for stable and fast training.
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)

XGBoost library models help to achieve state-of-the-art results most of the time so, we will also train this model to get better results.

Python
from sklearn.metrics import mean_absolute_error as mae
model = XGBRegressor()
model.fit(X_train, Y_train)

We can now use the leftover validation dataset to evaluate the performance of the model.

Python
train_preds = model.predict(X_train) 
print('Training Error : ', mae(Y_train, train_preds)) 

val_preds = model.predict(X_val) 
print('Validation Error : ', mae(Y_val, val_preds)) 
print() 

# This code is modified by Susobhan Akhuli

Output:

Training Error :  0.2104541861999253
Validation Error : 0.6358190127903746

This mean absolute error value we are looking at is between the logarithm of the predicted values and the actual values so, the actual error will be higher than what we are observing above.

Get the Complete notebook:

Notebook: click here.

Dataset : click here.



Previous Article
Next Article

Similar Reads

ML | Rainfall prediction using Linear regression
Rainfall prediction is a common application of machine learning, and linear regression is a simple and effective technique that can be used for this purpose. In this task, the goal is to predict the amount of rainfall based on historical data. Linear regression is a supervised learning algorithm that is used to model the relationship between a depe
7 min read
Linear Regression for Single Prediction
Linear regression is a fundamental statistical method used to model the relationship between a dependent variable and one or more independent variables. The primary goal is to predict the value of the dependent variable based on the values of the independent variables. This article will guide you through the process of using a linear regression mod
6 min read
ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
The Difference between Linear Regression and Nonlinear Regression Models
areRegression analysis is a fundamental tool in statistical modelling used to understand the relationship between a dependent variable and one or more independent variables. Two primary types of regression models are linear regression and nonlinear regression. This article delves into the key differences between these models, their applications, an
7 min read
Support Vector Regression (SVR) using Linear and Non-Linear Kernels in Scikit Learn
Support vector regression (SVR) is a type of support vector machine (SVM) that is used for regression tasks. It tries to find a function that best predicts the continuous output value for a given input value. SVR can use both linear and non-linear kernels. A linear kernel is a simple dot product between two input vectors, while a non-linear kernel
5 min read
Placement prediction using Logistic Regression
Prerequisites: Understanding Logistic Regression, Logistic Regression using Python In this article, we are going to discuss how to predict the placement status of a student based on various student attributes using Logistic regression algorithm. Placements hold great importance for students and educational institutions. It helps a student to build
4 min read
Heart Disease Prediction Using Logistic Regression in R
Machine learning can effectively identify patterns in data, providing valuable insights from this data. This article explores one of these machine learning techniques called Logistic regression and how it can analyze the key patient details and determine the probability of heart disease based on patient health data in R Programming Language. Logist
13 min read
Transport Demand Prediction using Regression
Transport demand prediction is a crucial aspect of transportation planning and management. Accurate demand forecasts enable efficient resource allocation, improved service planning, and enhanced customer satisfaction. Regression analysis, a statistical method for modeling relationships between variables, is widely used for predicting transport dema
8 min read
ML | Heart Disease Prediction Using Logistic Regression
World Health Organization has estimated that four out of five cardiovascular disease (CVD) deaths are due to heart attacks. This whole research intends to pinpoint the ratio of patients who possess a good chance of being affected by CVD and also to predict the overall risk using Logistic Regression. What is Logistic Regression?Logistic Regression i
4 min read
Bounding Box Prediction using PyTorch
In the realm of computer vision, PyTorch has emerged as a powerful framework for developing sophisticated models. One fascinating application within this field is bounding box prediction, a crucial task for object detection. In this article, we delve into the world of bounding box prediction using PyTorch, providing a step-by-step guide and insight
7 min read
Regression Models for California Housing Price Prediction
In this article, we will build a machine-learning model that predicts the median housing price using the California housing price dataset from the StatLib repository. The dataset is based on the 1990 California census and has metrics. It is a supervised learning task (labeled training) because each instance has an expected output (median housing pr
15+ min read
How to improve the performance of segmented regression using quantile regression in R?
Segmented regression, also known as piecewise or broken-line regression is a powerful statistical technique used to identify changes in the relationship between a dependent variable and one or more independent variables. Quantile regression, on the other hand, estimates the conditional quantiles of a response variable distribution in the linear mod
8 min read
Multiple Linear Regression using R
Prerequisite: Simple Linear-Regression using RLinear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach for modeling the relationship between a dependent variable and a given set of independent variables.These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Mul
3 min read
Linear Regression using PyTorch
Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep lea
4 min read
ML | Multiple Linear Regression using Python
Linear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables. These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Multiple Linear Regression using Python. Multiple
6 min read
A Practical approach to Simple Linear Regression using R
Simple Linear Regression is a statistical method that allows us to summarize and study relationships between two continuous (quantitative) variables. One variable denoted x is regarded as an independent variable and other one denoted y is regarded as a dependent variable. It is assumed that the two variables are linearly related. Hence, we try to f
9 min read
Pyspark | Linear regression with Advanced Feature Dataset using Apache MLlib
Ames Housing Data: The Ames Housing dataset was compiled by Dean De Cock for use in data science education and expanded version of the often-cited Boston Housing dataset. The dataset provided has 80 features and 1459 instances. Dataset description is as below: For demo few columns are displayed but there are a lot more columns are there in the data
4 min read
Linear Regression Implementation From Scratch using Python
Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for predicti
4 min read
Locally weighted linear Regression using Python
Locally weighted linear regression is the nonparametric regression methods that combine k-nearest neighbor based machine learning. It is referred to as locally weighted because for a query point the function is approximated on the basis of data near that and weighted because the contribution is weighted by its distance from the query point. Locally
4 min read
Multiple Linear Regression using R to predict housing prices
Predicting housing prices is a common task in the field of data science and statistics. Multiple Linear Regression is a valuable tool for this purpose as it allows you to model the relationship between multiple independent variables and a dependent variable, such as housing prices. In this article, we'll walk you through the process of performing M
12 min read
Linear Regression Assumptions and Diagnostics using R
Linear regression is a statistical method used to model the relationship between a dependent variable and one or more independent variables. Before interpreting the results of a linear regression analysis in R, it's important to check and ensure that the assumptions of linear regression are met. Assumptions of linear regression include linearity, i
7 min read
7 Steps to Run a Linear Regression Analysis using R
Linear Regression is a useful statistical tool for modelling the relationship between a dependent variable and one or more independent variables. It is widely used in many disciplines, such as science, medicine, economics, and education. For instance, several areas of education employ linear regression to estimate student performance or identify th
9 min read
Hierarchical linear regression using R
Linear Regression model is used to establish a connection between two or more variables. These variables are either dependent or independent. Linear Regression In R Programming Language is used to give predictions based on the given data about a particular topic, It helps us to have valuable insights and give conclusions that help us in many future
9 min read
Python | Linear Regression using sklearn
Prerequisite: Linear Regression Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on –
3 min read
Linear Regression using Turicreate
Linear Regression is a method or approach for Supervised Learning.Supervised Learning takes the historical or past data and then train the model and predict the things according to the past results.Linear Regression comes from the word 'Linear' and 'Regression'.Regression concept deals with predicting the future using the past data.Linear means the
2 min read
Multiple linear regression analysis of Boston Housing Dataset using R
In this article, we are going to perform multiple linear regression analyses on the Boston Housing dataset using the R programming language. What is Multiple Linear Regression?Multiple Linear Regression is a supervised learning model, which is an extension of simple linear regression, where instead of just one independent variable, we have multiple
13 min read
Multiple linear regression using R for the Real estate data set
Multiple linear regression is widely used in machine learning and data science. In this article, We will discuss the Multiple linear regression by building a step-by-step project on a Real estate data set. Multiple linear regressionMultiple Linear Regression is a statistical method used to model the relationship between a dependent variable (or tar
9 min read
Step-by-Step Guide to Modeling Time Series Data Using Linear Regression
Time series data is a sequence of data points collected or recorded at specific time intervals. Modeling time series data is crucial in various fields such as finance, economics, environmental science, and many others. One of the simplest yet powerful methods to model time series data is using linear regression. This article will delve into the tec
6 min read
Reason for Using RMSE Instead of MSE in Linear Regression
Answer: RMSE is preferred over MSE in linear regression because it is in the same units as the response variable, making interpretation easier.In linear regression analysis, both the Mean Squared Error (MSE) and the Root Mean Squared Error (RMSE) serve as measures to evaluate model performance, specifically regarding how well the model predicts the
2 min read
Interpreting the results of Linear Regression using OLS Summary
This article is to tell you the whole interpretation of the regression summary table. There are many statistical softwares that are used for regression analysis like Matlab, Minitab, spss, R etc. but this article uses python. The Interpretation is the same for other tools as well. This article needs the basics of statistics including basic knowledg
6 min read