top of page
  • Writer's pictureHackers Realm

Black Friday Sales Prediction Analysis using Python | Regression | Machine Learning Project Tutorial

Black Friday Sales Prediction is a regression problem where we have to analyze and predict the sales of an product in the retail store based on various aspects of the dataset. The objective is to build a predictive model and discover the sales of each product.

In this project tutorial, we analyze and predict the sales during Black Friday, and display the results through plot graphs and different prediction models.

You can watch the video-based tutorial with step by step explanation down below

Dataset Information

This dataset comprises of sales transactions captured at a retail store. It’s a classic dataset to explore and expand your feature engineering skills and day to day understanding from multiple shopping experiences. This is a regression problem. The dataset has 550,069 rows and 12 columns.

Problem: Predict purchase amount


  • Masked attributes hide the data information.

Download the Dataset here

Import modules

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
%matplotlib inline

  • pandas - used to perform data manipulation and analysis

  • numpy - used to perform a wide variety of mathematical operations on arrays

  • matplotlib - used for data visualization and graphical plotting

  • seaborn - built on top of matplotlib with similar functionalities

  • %matplotlib - to enable the inline plotting.

  • warnings - to manipulate warnings details

  • filterwarnings('ignore') is to ignore the warnings thrown by the modules (gives clean results)

Loading the dataset

df = pd.read_csv('train.csv')
  • Some columns have null values, those values must be replaced for a relevant value for further processing.

Let us see the statistical information of the attributes

# statistical info
  • Statistical information of the data

  • Product_Category_2 and Product_Category_3 have lower number of samples than Product_Category_1, both could be sub categories.

Let us see the data type information of the attributes

# datatype info
  • We have categorical as well as numerical attributes which we will process separately.

  • Product_Category_1 data type is different from Product_Category_2 and Product_Category_3, that won't affect the process or the result.

# find unique values
df.apply(lambda x: len(x.unique()))
  • Attributes containing many unique values are of numerical type. The remaining attributes are of categorical type.

Exploratory Data Analysis

# distplot for purchase'fivethirtyeight')
plt.figure(figsize=(13, 7))
sns.distplot(df['Purchase'], bins=25)
  • First part of the graph has a normal distribution and later forming some peaks in the graph

  • Evaluating the whole graph, it has a normal distribution

# distribution of numeric variables
  • Many buyers are male while the minority are female.

  • Difference is due to the categories on sale during Black Friday, evaluating a particular category may change the count between genders.

  • There are 7 categories defined to classify the age of the buyers

  • Majority of the buyers are single

  • Display of the occupation of the buyers

  • Occupation 8 has extremely low count compared with the others; it can be ignored for the calculation since it won't affect much the result.

  • Majority of the products are in category 1, 5 and 8.

  • The low no. categories can be combined into a single category to greatly reduce the complexity of the problem.

  • Categories are in float values

  • Categories 2, 8, 14 to 16 are higher compared with the others.

  • Categories are in float values

  • Categories 14 to 17 are higher

  • Higher count might represent the urban area indicates more population

  • Most buyers have one year living in the city

  • Remaining categories are uniform distribution

Now let us plot using two variables for analysis

# bivariate analysis
occupation_plot = df.pivot_table(index='Occupation', values='Purchase', aggfunc=np.mean)
occupation_plot.plot(kind='bar', figsize=(13, 7))
plt.title("Occupation and Purchase Analysis")
  • np.mean will display mean of the purchase based on occupation

  • np.sum will display a sum of the purchase based on occupation

  • Based on the labels, we can observe all the categories being purchased in an average manner.

  • Recommended plot graph for presentation

age_plot = df.pivot_table(index='Age', values='Purchase', aggfunc=np.mean)
age_plot.plot(kind='bar', figsize=(13, 7))
plt.title("Age and Purchase Analysis")
  • Age and Purchase graph also has a uniform distribution.

gender_plot = df.pivot_table(index='Gender', values='Purchase', aggfunc=np.mean)
gender_plot.plot(kind='bar', figsize=(13, 7))
plt.title("Gender and Purchase Analysis")
  • Uniform distribution but with a little difference

Preprocessing the dataset

We must check first for null values in the data

# check for null values
  • Null values are present in Product_Category_2 and Product_Category_3

  • Null values must be filled for easier processing

Now we fill the Null values in the dataset

df['Product_Category_2'] = df['Product_Category_2'].fillna(-2.0).astype("float32")
df['Product_Category_3'] = df['Product_Category_3'].fillna(-2.0).astype("float32")
  • Null values filled with a negative value to not affect the results.

  • The value filled must be of same data type of the attribute.

Let us double check the null values


Now we must convert the categorical attributes to numerical using a dictionary

# encoding values using dict
gender_dict = {'F':0, 'M':1}
df['Gender'] = df['Gender'].apply(lambda x: gender_dict[x])
  • 'F' now converted to numerical zero (0), same for 'M' to one (1)

Label encoding is to convert the categorical column into the numerical column a lot quicker

# to improve the metric use one hot encoding
# label encoding
cols = ['Age', 'City_Category', 'Stay_In_Current_City_Years']
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
for col in cols:
    df[col] = le.fit_transform(df[col])