Video Game Sales Prediction
Objective:
A video game, also known as a computer game, is an electronic game that can be interacted with using an input device, such as a controller, keyboard, or joystick. Video games can be used for entertainment and relaxation, but they can also be used for competitions and for computer learning. However, the benefits of videogames include improved powers of concentration, creativity, memory, languages and teamwork. Videogames can make it easier to learn educational contents and develop cognitive skills.
The goal of this challenge is to build a machine learning model to predict the sales of video game.
Dataset:
The dataset used in this model is publicly available and free to use.
Attribute Information:
- Rank
- Name
- Platform
- Year
- Genre
- Publisher
- NA_Sales
- EU_Sales
- JP_Sales
- Other_Sales
- Global_Sales
Step 1: Import all the required libraries
- Pandas : In computer programming, pandas is a software library written for the Python programming language for data manipulation and analysis and storing in a proper way. In particular, it offers data structures and operations for manipulating numerical tables and time series
- Sklearn : Scikit-learn (formerly scikits.learn) is a free software machine learning library for the Python programming language. It features various classification, regression and clustering algorithms including support vector machines, random forests, gradient boosting, k-means and DBSCAN, and is designed to interoperate with the Python numerical and scientific libraries NumPy and SciPy. The library is built upon the SciPy (Scientific Python) that must be installed before you can use scikit-learn.
- Pickle : Python pickle module is used for serializing and de-serializing a Python object structure. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.
- Seaborn : Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
- Matplotlib : Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.
#Loading libraries
import pandas as pd
import seaborn as sns
import pickle
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
from sklearn.linear_model import LinearRegression, Ridge, RidgeCV, Lasso, LassoCV
from sklearn.model_selection import KFold, cross_val_score, train_test_split
import warnings
warnings.filterwarnings('ignore')
Step 2 : Read dataset and basic details of dataset
Goal:- In this step we are going to read the dataset, view the dataset and analysis the basic details like total number of rows and columns, what are the column data types and see to need to create new column or not.
In this stage we are going to read our problem dataset and have a look on it.
#loading the dataset
try:
df = pd.read_csv('C:/Users/Sakshi Rohida/Desktop/deepak sir ML projects/Video_game_sales_prediction/data/Video game sales.csv') #Path for the file
print('Data read done successfully...')
except (FileNotFoundError, IOError):
print("Wrong file or file path")Data read done successfully...# To view the content inside the dataset we can use the head() method that returns a specified number of rows, string from the top.
# The head() method returns the first 5 rows if a number is not specified.
df.head()
Step3: Data Preprocessing
Why need of Data Preprocessing?
Preprocessing data is an important step for data analysis. The following are some benefits of preprocessing data:
- It improves accuracy and reliability. Preprocessing data removes missing or inconsistent data values resulting from human or computer error, which can improve the accuracy and quality of a dataset, making it more reliable.
- It makes data consistent. When collecting data, it’s possible to have data duplicates, and discarding them during preprocessing can ensure the data values for analysis are consistent, which helps produce accurate results.
- It increases the data’s algorithm readability. Preprocessing enhances the data’s quality and makes it easier for machine learning algorithms to read, use, and interpret it.
df = df.drop(['Name'], axis =1)
Why we drop column?
By analysing the first five rows we found that there is a column we need to drop that column that is not required in the dataset for prediction.
# count the total number of rows and columns.
print ('The train data has {0} rows and {1} columns'.format(df.shape[0],df.shape[1]))The train data has 16598 rows and 10 columnsdf['Global_Sales'].value_counts()0.02 1071
0.03 811
0.04 645
0.05 632
0.01 618
...
5.01 1
5.05 1
5.07 1
5.11 1
3.16 1
Name: Global_Sales, Length: 623, dtype: int64
The df.value_counts() method counts the number of types of values a particular column contains.
df.shape(16598, 10)
The df.shape method shows the shape of the dataset.
df.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 16598 entries, 0 to 16597
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Rank 16598 non-null int64
1 Platform 16598 non-null object
2 Year 16327 non-null float64
3 Genre 16598 non-null object
4 Publisher 16540 non-null object
5 NA_Sales 16598 non-null float64
6 EU_Sales 16598 non-null float64
7 JP_Sales 16598 non-null float64
8 Other_Sales 16598 non-null float64
9 Global_Sales 16598 non-null float64
dtypes: float64(6), int64(1), object(3)
memory usage: 1.3+ MB
The df.info() method prints information about a DataFrame including the index dtype and columns, non-null values and memory usage.
df.iloc[1]Rank 2
Platform NES
Year 1985.0
Genre Platform
Publisher Nintendo
NA_Sales 29.08
EU_Sales 3.58
JP_Sales 6.81
Other_Sales 0.77
Global_Sales 40.24
Name: 1, dtype: object
df.iloc[ ] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. The iloc property gets, or sets, the value(s) of the specified indexes.
Data Type Check for every column
Why data type check is required?
Data type check helps us with understanding what type of variables our dataset contains. It helps us with identifying whether to keep that variable or not. If the dataset contains contiguous data, then only float and integer type variables will be beneficial and if we have to classify any value then categorical variables will be beneficial.
objects_cols = ['object']
objects_lst = list(df.select_dtypes(include=objects_cols).columns)print("Total number of categorical columns are ", len(objects_lst))
print("There names are as follows: ", objects_lst)Total number of categorical columns are 3
There names are as follows: ['Platform', 'Genre', 'Publisher']int64_cols = ['int64']
int64_lst = list(df.select_dtypes(include=int64_cols).columns)print("Total number of numerical columns are ", len(int64_lst))
print("There names are as follows: ", int64_lst)Total number of numerical columns are 1
There names are as follows: ['Rank']float64_cols = ['float64']
float64_lst = list(df.select_dtypes(include=float64_cols).columns)print("Total number of float64 columns are ", len(float64_lst))
print("There name are as follow: ", float64_lst)Total number of float64 columns are 6
There name are as follow: ['Year', 'NA_Sales', 'EU_Sales', 'JP_Sales', 'Other_Sales', 'Global_Sales']#count the total number of rows and columns.
print ('The new dataset has {0} rows and {1} columns'.format(df.shape[0],df.shape[1]))The new dataset has 16598 rows and 10 columns
Step 2 Insights: -
- There are 6 columns that are of float type.
- The categorical columns are 3.
- The number of numerical column is 1. After this step we have to calculate various evaluation parameters which will help us in cleaning and analysing the data more accurately.
Step 3: Descriptive Analysis
Goal/Purpose: Finding the data distribution of the features. Visualization helps to understand data and also to explain the data to another person.
Things we are going to do in this step:
- Mean
- Median
- Mode
- Standard Deviation
- Variance
- Null Values
- NaN Values
- Min value
- Max value
- Count Value
- Quatilers
- Correlation
- Skewness
df.describe()
The df.describe() method returns description of the data in the DataFrame. If the DataFrame contains numerical data, the description contains these information for each column: count — The number of not-empty values. mean — The average (mean) value.
Measure the variability of data of the dataset
Variability describes how far apart data points lie from each other and from the center of a distribution.
1. Standard Deviation
The standard deviation is the average amount of variability in your dataset.
It tells you, on average, how far each data point lies from the mean. The larger the standard deviation, the more variable the data set is and if zero variance then there is no variability in the dataset that means there no use of that dataset.
So, it helps in understanding the measurements when the data is distributed. The more the data is distributed, the greater will be the standard deviation of that data.Here, you as an individual can determine which company is beneficial in long term. But, if you didn’t know the SD you would have choosen a wrong compnay for you.
df.std()Rank 4791.853933
Year 5.828981
NA_Sales 0.816683
EU_Sales 0.505351
JP_Sales 0.309291
Other_Sales 0.188588
Global_Sales 1.555028
dtype: float64
We can also understand the standard deviation using the below function.
def std_cal(df,float64_lst):
cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0
for value in float64_lst:
rs = round(df[value].std(),6)
if rs > 0:
normal_value = normal_value + 1
elif rs == 0:
zero_value = zero_value + 1
std_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)
return std_total_dfstd_cal(df, float64_lst)
int64_cols = ['int64']
int64_lst = list(df.select_dtypes(include=int64_cols).columns)
std_cal(df,int64_lst)
zero_value -> is the zero variance and when then there is no variability in the dataset that means there no use of that dataset.
2. Variance
The variance is the average of squared deviations from the mean. A deviation from the mean is how far a score lies from the mean.
Variance is the square of the standard deviation. This means that the units of variance are much larger than those of a typical value of a data set.
Why do we used Variance ?
By Squairng the number we get non-negative computation i.e. Disperson cannot be negative. The presence of variance is very important in your dataset because this will allow the model to learn about the different patterns hidden in the data
df.var()Rank 2.296186e+07
Year 3.397702e+01
NA_Sales 6.669712e-01
EU_Sales 2.553799e-01
JP_Sales 9.566070e-02
Other_Sales 3.556559e-02
Global_Sales 2.418112e+00
dtype: float64
We can also understand the Variance using the below function.
zero_cols = []
def var_cal(df,float64_lst):
cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0
for value in float64_lst:
rs = round(df[value].var(),6)
if rs > 0:
normal_value = normal_value + 1
elif rs == 0:
zero_value = zero_value + 1
zero_cols.append(value)
var_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)
return var_total_dfvar_cal(df, float64_lst)
var_cal(df, int64_lst)
zero_value -> Zero variance means that there is no difference in the data values, which means that they are all the same.
Measure central tendency
A measure of central tendency is a single value that attempts to describe a set of data by identifying the central position within that set of data. As such, measures of central tendency are sometimes called measures of central location. They are also classed as summary statistics.
Mean — The average value. Median — The mid point value. Mode — The most common value.
1. Mean
The mean is the arithmetic average, and it is probably the measure of central tendency that you are most familiar.
Why do we calculate mean?
The mean is used to summarize a data set. It is a measure of the center of a data set.
df.mean()Rank 8300.605254
Year 2006.406443
NA_Sales 0.264667
EU_Sales 0.146652
JP_Sales 0.077782
Other_Sales 0.048063
Global_Sales 0.537441
dtype: float64
We can also understand the mean using the below function.
def mean_cal(df,int64_lst):
cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0
for value in int64_lst:
rs = round(df[value].mean(),6)
if rs > 0:
normal_value = normal_value + 1
elif rs == 0:
zero_value = zero_value + 1
mean_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)
return mean_total_dfmean_cal(df, int64_lst)
mean_cal(df,float64_lst)
zero_value -> that the mean of a paticular column is zero, which isn’t usefull in anyway and need to be drop.
2.Median
The median is the middle value. It is the value that splits the dataset in half.The median of a dataset is the value that, assuming the dataset is ordered from smallest to largest, falls in the middle. If there are an even number of values in a dataset, the middle two values are the median.
Why do we calculate median ?
By comparing the median to the mean, you can get an idea of the distribution of a dataset. When the mean and the median are the same, the dataset is more or less evenly distributed from the lowest to highest values.The median will depict that the patient below median is Malignent and above that are Benign.
df.median()Rank 8300.50
Year 2007.00
NA_Sales 0.08
EU_Sales 0.02
JP_Sales 0.00
Other_Sales 0.01
Global_Sales 0.17
dtype: float64
We can also understand the median using the below function.
def median_cal(df,int64_lst):
cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0
for value in float64_lst:
rs = round(df[value].mean(),6)
if rs > 0:
normal_value = normal_value + 1
elif rs == 0:
zero_value = zero_value + 1
median_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)
return median_total_dfmedian_cal(df, float64_lst)
zero_value -> that the median of a paticular column is zero which isn’t usefull in anyway and need to be drop.
3. Mode
The mode is the value that occurs the most frequently in your data set. On a bar chart, the mode is the highest bar. If the data have multiple values that are tied for occurring the most frequently, you have a multimodal distribution. If no value repeats, the data do not have a mode.
Why do we calculate mode ?
The mode can be used to summarize categorical variables, while the mean and median can be calculated only for numeric variables. This is the main advantage of the mode as a measure of central tendency. It’s also useful for discrete variables and for continuous variables when they are expressed as intervals.
df.mode()
def mode_cal(df,int64_lst):
cols = ['normal_value', 'zero_value', 'string_value']
zero_value = 0
normal_value = 0
string_value = 0
for value in float64_lst:
rs = df[value].mode()[0]
if isinstance(rs, str):
string_value = string_value + 1
else:
if rs > 0:
normal_value = normal_value + 1
elif rs == 0:
zero_value = zero_value + 1
mode_total_df = pd.DataFrame([[normal_value, zero_value, string_value]], columns=cols)
return mode_total_dfmode_cal(df, list(df.columns))
zero_value -> that the mode of a paticular column is zero which isn’t usefull in anyway and need to be drop.
Null and Nan values
- Null Values
A null value in a relational database is used when the value in a column is unknown or missing. A null is neither an empty string (for character or datetime data types) nor a zero value (for numeric data types).
df.isnull().sum()Rank 0
Platform 0
Year 271
Genre 0
Publisher 58
NA_Sales 0
EU_Sales 0
JP_Sales 0
Other_Sales 0
Global_Sales 0
dtype: int64
As we notice that there are no null values in our dataset.
- Nan Values
NaN, standing for Not a Number, is a member of a numeric data type that can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic.
df.isna().sum()Rank 0
Platform 0
Year 271
Genre 0
Publisher 58
NA_Sales 0
EU_Sales 0
JP_Sales 0
Other_Sales 0
Global_Sales 0
dtype: int64df.dropna(inplace=True)
The way to remove null and nan values is to use the method “df.dropna(inplace=True)”.
Count of unique occurences of every value in all categorical value
for value in objects_lst:
print(f"{value:{10}} {df[value].value_counts()}")Platform DS 2131
PS2 2127
PS3 1304
Wii 1290
X360 1234
PSP 1197
PS 1189
PC 938
XB 803
GBA 786
GC 542
3DS 499
PSV 410
PS4 336
N64 316
SNES 239
XOne 213
SAT 173
WiiU 143
2600 116
NES 98
GB 97
DC 52
GEN 27
NG 12
SCD 6
WS 6
3DO 3
TG16 2
GG 1
PCFX 1
Name: Platform, dtype: int64
Genre Action 3251
Sports 2304
Misc 1686
Role-Playing 1470
Shooter 1282
Adventure 1274
Racing 1225
Platform 875
Simulation 848
Fighting 836
Strategy 670
Puzzle 570
Name: Genre, dtype: int64
Publisher Electronic Arts 1339
Activision 966
Namco Bandai Games 928
Ubisoft 918
Konami Digital Entertainment 823
...
Detn8 Games 1
Pow 1
Navarre Corp 1
MediaQuest 1
UIG Entertainment 1
Name: Publisher, Length: 576, dtype: int64
- Categorical data are variables that contain label values rather than numeric values.The number of possible values is often limited to a fixed set.
- Use Label Encoder to label the categorical data. Label Encoder is the part of SciKit Learn library in Python and used to convert categorical data, or text data, into numbers, which our predictive models can better understand.
Label Encoding refers to converting the labels into a numeric form so as to convert them into the machine-readable form. Machine learning algorithms can then decide in a better way how those labels must be operated. It is an important pre-processing step for the structured dataset in supervised learning.
#Before Encoding
df['Platform']
df['Genre']
df['Publisher']0 Nintendo
1 Nintendo
2 Nintendo
3 Nintendo
4 Nintendo
...
16593 Kemco
16594 Infogrames
16595 Activision
16596 7G//AMES
16597 Wanadoo
Name: Publisher, Length: 16291, dtype: objectdf.head()
#Encoding categorical data values
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df.Platform = le.fit_transform(df.Platform)
df.Genre = le.fit_transform(df.Genre)
df.Publisher = le.fit_transform(df.Publisher)#After encoding or converting categorical col values into numbers
df['Platform'].unique()array([26, 11, 5, 4, 28, 17, 16, 23, 6, 2, 18, 10, 15, 29, 13, 0, 19,
30, 7, 27, 8, 3, 20, 21, 22, 25, 12, 24, 1, 9, 14])df['Genre'].unique()array([10, 4, 6, 7, 5, 3, 8, 9, 0, 2, 1, 11])df['Publisher'].unique()array([359, 323, 493, 455, 21, 524, 66, 138, 445, 465, 53, 6, 85,
177, 275, 457, 464, 288, 540, 547, 527, 137, 426, 543, 144, 347,
385, 214, 487, 164, 17, 292, 126, 296, 91, 424, 281, 40, 325,
253, 120, 10, 343, 521, 391, 308, 237, 499, 532, 13, 330, 241,
528, 462, 531, 23, 63, 109, 378, 425, 537, 219, 198, 199, 550,
206, 101, 224, 94, 430, 55, 485, 12, 565, 18, 459, 4, 419,
348, 160, 30, 71, 460, 303, 372, 564, 413, 88, 142, 472, 97,
434, 490, 27, 176, 322, 400, 450, 511, 441, 273, 182, 508, 299,
191, 334, 398, 84, 495, 104, 436, 414, 574, 420, 525, 443, 246,
341, 87, 463, 2, 58, 223, 367, 314, 365, 67, 513, 461, 256,
362, 277, 415, 233, 506, 170, 432, 318, 305, 227, 433, 456, 526,
193, 552, 61, 381, 515, 279, 232, 491, 263, 122, 146, 557, 238,
481, 83, 44, 186, 324, 255, 36, 553, 22, 383, 422, 556, 184,
544, 368, 501, 148, 60, 272, 304, 503, 213, 133, 489, 500, 337,
444, 399, 294, 315, 269, 225, 57, 116, 139, 70, 254, 9, 492,
311, 140, 467, 566, 258, 121, 353, 77, 228, 407, 222, 19, 468,
379, 62, 189, 355, 470, 93, 80, 295, 301, 265, 358, 546, 35,
39, 403, 438, 211, 165, 361, 357, 286, 99, 112, 218, 338, 382,
240, 285, 345, 59, 43, 476, 207, 437, 346, 166, 555, 530, 536,
123, 34, 366, 75, 156, 11, 81, 328, 257, 446, 374, 342, 50,
203, 26, 98, 105, 293, 448, 317, 423, 363, 484, 567, 162, 51,
440, 262, 230, 392, 52, 100, 401, 522, 231, 402, 150, 24, 171,
386, 72, 183, 111, 56, 409, 351, 539, 38, 479, 551, 480, 534,
113, 131, 310, 535, 504, 181, 78, 20, 190, 153, 234, 478, 458,
37, 390, 221, 128, 516, 469, 558, 435, 69, 215, 451, 200, 172,
502, 520, 129, 117, 291, 110, 169, 439, 74, 427, 517, 336, 483,
370, 28, 344, 118, 507, 179, 115, 371, 188, 554, 449, 529, 408,
488, 209, 7, 86, 82, 321, 380, 387, 320, 185, 64, 519, 145,
49, 247, 48, 573, 235, 394, 152, 575, 106, 204, 210, 217, 360,
376, 447, 333, 326, 16, 159, 196, 287, 548, 114, 31, 340, 316,
251, 475, 141, 151, 509, 197, 136, 54, 41, 187, 510, 32, 212,
570, 312, 163, 429, 239, 103, 0, 205, 384, 242, 46, 47, 135,
562, 395, 208, 201, 125, 102, 264, 549, 278, 14, 90, 42, 149,
298, 412, 393, 1, 505, 497, 533, 332, 514, 496, 560, 410, 349,
313, 306, 95, 335, 406, 431, 473, 327, 404, 290, 276, 158, 5,
280, 29, 107, 89, 452, 541, 243, 454, 154, 563, 229, 252, 3,
289, 267, 259, 373, 297, 157, 411, 307, 65, 168, 130, 572, 68,
220, 266, 15, 512, 216, 261, 108, 260, 416, 474, 568, 486, 143,
155, 245, 173, 477, 274, 369, 356, 571, 79, 518, 471, 8, 174,
561, 134, 283, 167, 282, 388, 270, 175, 202, 271, 250, 329, 124,
73, 178, 559, 405, 538, 569, 352, 92, 417, 396, 127, 300, 161,
236, 268, 25, 498, 180, 331, 119, 442, 226, 428, 195, 542, 33,
339, 194, 545, 482, 453, 284, 302, 418, 319, 309, 354, 192, 248,
76, 466, 132, 147, 350, 45, 397, 364, 389, 377, 375, 96, 249,
494, 244, 421, 523])
Skewness
Skewness is a measure of the asymmetry of a distribution. A distribution is asymmetrical when its left and right side are not mirror images. A distribution can have right (or positive), left (or negative), or zero skewness
Why do we calculate Skewness ?
Skewness gives the direction of the outliers if it is right-skewed, most of the outliers are present on the right side of the distribution while if it is left-skewed, most of the outliers will present on the left side of the distribution
Below is the function to calculate skewness.
def right_nor_left(df, int64_lst):
temp_skewness = ['column', 'skewness_value', 'skewness (+ve or -ve)']
temp_skewness_values = []
temp_total = ["positive (+ve) skewed", "normal distrbution" , "negative (-ve) skewed"]
positive = 0
negative = 0
normal = 0
for value in float64_lst:
rs = round(df[value].skew(),4)
if rs > 0:
temp_skewness_values.append([value,rs , "positive (+ve) skewed"])
positive = positive + 1
elif rs == 0:
temp_skewness_values.append([value,rs,"normal distrbution"])
normal = normal + 1
elif rs < 0:
temp_skewness_values.append([value,rs, "negative (-ve) skewed"])
negative = negative + 1
skewness_df = pd.DataFrame(temp_skewness_values, columns=temp_skewness)
skewness_total_df = pd.DataFrame([[positive, normal, negative]], columns=temp_total)
return skewness_df, skewness_total_dffloat64_cols = ['float64']
float64_lst_col = list(df.select_dtypes(include=float64_cols).columns)
skew_df,skew_total_df = right_nor_left(df, float64_lst_col)skew_df
skew_total_df
df['NA_Sales_up'] = np.sqrt(df['NA_Sales'])
df['NA_Sales_up'].skew()2.697691120976752df['EU_Sales_up'] = np.sqrt(df['EU_Sales'])
df['EU_Sales_up'].skew()2.8990578581953526df['JP_Sales_up'] = np.sqrt(df['JP_Sales'])
df['JP_Sales_up'].skew()3.2235480784405754df['Other_Sales_up'] = np.sqrt(df['Other_Sales'])
df['Other_Sales_up'].skew()3.2883178617407784df['Global_Sales_up'] = np.sqrt(df['Global_Sales'])
df['Global_Sales_up'].skew()3.319948592507605
Hence, the skewness is transformed.
Now, Drop the extra columns.
df = df.drop(['NA_Sales','EU_Sales','JP_Sales','Other_Sales','Global_Sales'],axis = 1)
Step 3 Insights: -
With the statistical analysis we have found that the data have a lot of skewness in them all the columns are positively skewed with mostly zero variance.
Statistical analysis is little difficult to understand at one glance so to make it more understandable we will perform visulatization on the data which will help us to understand the process easily.
Why we are calculating all these metrics?
Mean / Median /Mode/ Variance /Standard Deviation are all very basic but very important concept of statistics used in data science. Almost all the machine learning algorithm uses these concepts in data preprocessing steps. These concepts are part of descriptive statistics where we basically used to describe and understand the data for features in Machine learning
Step 4: Data Exploration
Goal/Purpose:
Graphs we are going to develop in this step:
1. Histogram
A histogram is a bar graph-like representation of data that buckets a range of classes into columns along the horizontal x-axis.The vertical y-axis represents the number count or percentage of occurrences in the data for each column
# Distribution in attributes
%matplotlib inline
import matplotlib.pyplot as plt
df.hist(bins=50, figsize=(10,10))
plt.show()
Histogram Insight: -
Histogram helps in identifying the following:
- View the shape of your data set’s distribution to look for outliers or other significant data points.
- Determine whether something significant has boccurred from one time period to another.
Why Histogram?
It is used to illustrate the major features of the distribution of the data in a convenient form. It is also useful when dealing with large data sets (greater than 100 observations). It can help detect any unusual observations (outliers) or any gaps in the data.
From the above graphical representation we can identify that the highest bar represents the outliers which is above the maximum range.
We can also identify that the values are moving on the right side, which determines positive and the centered values determines normal skewness.
2. Distplot
A Distplot or distribution plot, depicts the variation in the data distribution. Seaborn Distplot represents the overall distribution of continuous data variables. The Seaborn module along with the Matplotlib module is used to depict the distplot with different variations in it
num = [f for f in df.columns if df.dtypes[f] != 'object']
nd = pd.melt(df, value_vars = num)
n1 = sns.FacetGrid (nd, col='variable', col_wrap=4, sharex=False, sharey = False)
n1 = n1.map(sns.distplot, 'value')
n1<seaborn.axisgrid.FacetGrid at 0x211f98c67f0>
Why Distplot?
Skewness is demonstrated on a bell curve when data points are not distributed symmetrically to the left and right sides of the median on a bell curve. If the bell curve is shifted to the left or the right, it is said to be skewed.
We can observe that the bell curve is shifted to left we indicates positive skewness.As all the column are positively skewed we don’t need to do scaling.
Let’s proceed and check the distribution of the target variable.
#+ve skewed
df['Global_Sales_up'].skew()3.319948592507605
The target variable is positively skewed.A normally distributed (or close to normal) target variable helps in better modeling the relationship between target and independent variables.
3. Heatmap
A heatmap (or heat map) is a graphical representation of data where values are depicted by color.Heatmaps make it easy to visualize complex data and understand it at a glance
Correlation — A positive correlation is a relationship between two variables in which both variables move in the same direction. Therefore, when one variable increases as the other variable increases, or one variable decreases while the other decreases.
Correlation can have a value:
- 1 is a perfect positive correlation
- 0 is no correlation (the values don’t seem linked at all)
- -1 is a perfect negative correlation
#correlation plot
sns.set(rc = {'figure.figsize':(7,7)})
corr = df.corr().abs()
sns.heatmap(corr,annot=True)
plt.show()
corr
Heatmap insights: -
As we know, it is recommended to avoid correlated features in your dataset. Indeed, a group of highly correlated features will not bring additional information (or just very few), but will increase the complexity of the algorithm, hence increasing the risk of errors.
Why Heatmap?
Heatmaps are used to show relationships between two variables, one plotted on each axis. By observing how cell colors change across each axis, you can observe if there are any patterns in value for one or both variables.
4. Boxplot
A boxplot is a standardized way of displaying the distribution of data based on a five number summary (“minimum”, first quartile [Q1], median, third quartile [Q3] and “maximum”).
Basically, to find the outlier in a dataset/column.
features = ['Rank','NA_Sales_up','EU_Sales_up','JP_Sales_up','Other_Sales_up']for value in features:
sns.catplot(data=df,x=value,kind="box")
sns.catplot(data=df, x='Global_Sales_up', kind='box')<seaborn.axisgrid.FacetGrid at 0x211fb80ee80>
The dark points are known as Outliers. Outliers are those data points that are significantly different from the rest of the dataset. They are often abnormal observations that skew the data distribution, and arise due to inconsistent data entry, or erroneous observations.
Boxplot Insights: -
- Sometimes outliers may be an error in the data and should be removed. In this case these points are correct readings yet they are different from the other points that they appear to be incorrect.
- The best way to decide wether to remove them or not is to train models with and without these data points and compare their validation accuracy.
- So we will keep it unchanged as it won’t affect our model.
Here, we can see that most of the variables possess outlier values. It would take us days if we start treating these outlier values one by one. Hence, for now we’ll leave them as is and let our algorithm deal with them. As we know, tree-based algorithms are usually robust to outliers.
Why Boxplot?
Box plots are used to show distributions of numeric data values, especially when you want to compare them between multiple groups. They are built to provide high-level information at a glance, offering general information about a group of data’s symmetry, skew, variance, and outliers.
In the next step we will divide our cleaned data into training data and testing data.
Step 2: Data Preparation
Goal:-
Tasks we are going to in this step:
- Now we will spearate the target variable and feature columns in two different dataframe and will check the shape of the dataset for validation purpose.
- Split dataset into train and test dataset.
- Scaling on train dataset.
1. Now we spearate the target variable and feature columns in two different dataframe and will check the shape of the dataset for validation purpose.
# Separate target and feature column in X and y variable
target = 'Global_Sales_up'
# X will be the features
X = df.drop(target,axis=1)
#y will be the target variable
y = df[target]X.info()<class 'pandas.core.frame.DataFrame'>
Int64Index: 16291 entries, 0 to 16597
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Rank 16291 non-null int64
1 Platform 16291 non-null int32
2 Year 16291 non-null float64
3 Genre 16291 non-null int32
4 Publisher 16291 non-null int32
5 NA_Sales_up 16291 non-null float64
6 EU_Sales_up 16291 non-null float64
7 JP_Sales_up 16291 non-null float64
8 Other_Sales_up 16291 non-null float64
dtypes: float64(5), int32(3), int64(1)
memory usage: 1.1 MBy0 9.096153
1 6.343501
2 5.984981
3 5.744563
4 5.600893
...
16593 0.100000
16594 0.100000
16595 0.100000
16596 0.100000
16597 0.100000
Name: Global_Sales_up, Length: 16291, dtype: float64# Check the shape of X and y variable
X.shape, y.shape((16291, 9), (16291,))# Reshape the y variable
y = y.values.reshape(-1,1)# Again check the shape of X and y variable
X.shape, y.shape((16291, 9), (16291, 1))
2. Spliting the dataset in training and testing data.
Here we are spliting our dataset into 80/20 percentage where 80% dataset goes into the training part and 20% goes into testing part.
# Split the X and y into X_train, X_test, y_train, y_test variables with 80-20% split.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Check shape of the splitted variables
X_train.shape, X_test.shape, y_train.shape, y_test.shape((13032, 9), (3259, 9), (13032, 1), (3259, 1))
Insights: -
Train test split technique is used to estimate the performance of machine learning algorithms which are used to make predictions on data not used to train the model.It is a fast and easy procedure to perform, the results of which allow you to compare the performance of machine learning algorithms for your predictive modeling problem. Although simple to use and interpret, there are times when the procedure should not be used, such as when you have a small dataset and situations where additional configuration is required, such as when it is used for classification and the dataset is not balanced.
In the next step we will train our model on the basis of our training and testing data.
Step 3: Model Training
Goal:
In this step we are going to train our dataset on different regression algorithms. As we know that our target variable is in continuous format so we have to apply regression algorithm.
Algorithms we are going to use in this step
- Linear Regression
- Lasso Regression
- Random Forest Regresser
K-fold cross validation is a procedure used to estimate the skill of the model on new data. There are common tactics that you can use to select the value of k for your dataset. There are commonly used variations on cross-validation, such as stratified and repeated, that are available in scikit-learn
# Define kfold with 10 split
cv = KFold(n_splits=10, shuffle=True, random_state=42)
The goal of cross-validation is to test the model’s ability to predict new data that was not used in estimating it, in order to flag problems like overfitting or selection bias and to give an insight on how the model will generalize to an independent dataset (i.e., an unknown dataset, for instance from a real problem).
1. Linear Regression
Linear regression attempts to model the relationship between two variables by fitting a linear equation to observed data. One variable is considered to be an explanatory variable, and the other is considered to be a dependent variable.
A linear regression line has an equation of the form Y = a + bX, where X is the explanatory variable and Y is the dependent variable. The slope of the line is b, and a is the intercept (the value of y when x = 0).
Train set cross-validation
df['Year'].unique()array([2006., 1985., 2008., 2009., 1996., 1989., 1984., 2005., 1999.,
2007., 2010., 2013., 2004., 1990., 1988., 2002., 2001., 2011.,
1998., 2015., 2012., 2014., 1992., 1997., 1993., 1994., 1982.,
2003., 1986., 2000., 1995., 2016., 1991., 1981., 1987., 1980.,
1983., 2020., 2017.])#Using Linear Regression
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
model.score(X_test, y_test)0.9808906601428069#Accuracy check of trainig data
from sklearn.metrics import r2_score
#Get R2 score
model.score(X_train, y_train)0.9791580121723247#Accuracy of test data
model.score(X_test, y_test)0.9808906601428069# Getting kfold values
lg_scores = -1 * cross_val_score(model,
X_train,
y_train,
cv=cv,
scoring='neg_root_mean_squared_error')
lg_scoresarray([0.07899147, 0.06370562, 0.06677959, 0.07843117, 0.06717177,
0.07228749, 0.07107973, 0.06460548, 0.05954757, 0.06828703])# Mean of the train kfold scores
lg_score_train = np.mean(lg_scores)
lg_score_train0.06908869163935243
Prediction
Now we will perform prediction on the dataset using Logistic Regression.
# Predict the values on X_test_scaled dataset
y_predicted = model.predict(X_test)
Various parameters are calculated for analysing the predictions.
- Confusion Matrix 2)Classification Report 3)Accuracy Score 4)Precision Score 5)Recall Score 6)F1 Score
Evaluating all kinds of evaluating parameters.
Classification Report :
A classification report is a performance evaluation metric in machine learning. It is used to show the precision, recall, F1 Score, and support of your trained classification model.
F1_score :
The F1 score is a machine learning metric that can be used in classification models.
Precision_score :
The precision is the ratio tp / (tp + fp) where tp is the number of true positives and fp the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The best value is 1 and the worst value is 0.
Recall_score :
Recall score is used to measure the model performance in terms of measuring the count of true positives in a correct manner out of all the actual positive values. Precision-Recall score is a useful measure of success of prediction when the classes are very imbalanced.
from sklearn.metrics import f1_score, accuracy_score, precision_score,recall_score
print("The model used is Linear Regression")
rg = r2_score(y_test,y_predicted)*100
print("\nThe accuracy is: {}".format(rg))The model used is Linear Regression
The accuracy is: 98.08906601428069
2. Lasso Regression
Lasso regression algorithm is defined as a regularization algorithm that assists in the elimination of irrelevant parameters, thus helping in the concentration of selection and regularizes the models.
#Using Lasso Regression
from sklearn import linear_model
clf = linear_model.Lasso(alpha=0.1)#looking for training data
clf.fit(X_train,y_train)Lasso(alpha=0.1)#Accuracy check for training data
clf.score(X_train,y_train)0.6540567411466873y_predicted1 = clf.predict(X_test)#Accuracy check of test data
lg = r2_score(y_test,y_predicted1)*100
lg59.0113833489547#Get kfold values
Nn_scores = -1 * cross_val_score(clf,
X_train,
y_train,
cv=cv,
scoring='neg_root_mean_squared_error')
Nn_scoresarray([0.32181162, 0.29853664, 0.26292661, 0.30639957, 0.28253538,
0.30256226, 0.25061801, 0.25256936, 0.26472919, 0.26035482])# Mean of the train kfold scores
Nn_score_train = np.mean(Nn_scores)
Nn_score_train0.28030434590762665print("The model used is Lasso Regression")
lg = r2_score(y_test,y_predicted)*100
print("\nThe accuracy is: {}".format(lg))The model used is Lasso Regression
The accuracy is: 98.08906601428069
3. Random Forest Regressor
A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting.
#Using Ridge Regression
from sklearn.ensemble import RandomForestRegressor
regr = RandomForestRegressor(max_depth=2, random_state=0)
regr.fit(X_train, y_train)RandomForestRegressor(max_depth=2, random_state=0)#Accuracy check of trainig data
#Get R2 score
regr.score(X_train, y_train)0.8816792781251908# Get kfold values
Dta_scores = -1 * cross_val_score(regr,
X_train,
y_train,
cv=cv,
scoring='neg_root_mean_squared_error')
Dta_scoresarray([0.18875755, 0.16382912, 0.14451193, 0.18233849, 0.16821322,
0.20104253, 0.14792705, 0.14191217, 0.16384599, 0.14169546])# Mean of the train kfold scores
Dta_score_train = np.mean(Dta_scores)
Dta_score_train0.16440735014012323
Prediction
# predict the values on X_test_scaled dataset
y_predicted = regr.predict(X_test)
Evaluating all kinds of evaluating parameters.
from sklearn.metrics import classification_report
from sklearn.metrics import f1_score, accuracy_score, precision_score,recall_score
from sklearn.metrics import confusion_matrix
print("The model used is Random forest Regressor")
r_acc = r2_score(y_test, y_predicted)*100
print("\nThe accuracy is {}".format(r_acc))The model used is Random forest Regressor
The accuracy is 84.25964124174094
Insight
cal_metric=pd.DataFrame([rg,lg,r_acc],columns=["Global_Sales_up"])
cal_metric.index=['Linear Regression',
'Lasso Regression','Random forest Regressor']
cal_metric
- As you can see with our Linear Regression Model(98.08%) we are getting a better result.
- So we gonna save our model with Linear Regression.
Step 4: Save Model
Goal:- In this step we are going to save our model in pickel format file.
import pickle
pickle.dump(model , open('Sales_Prediction_LinearRegresssion.pkl', 'wb'))
pickle.dump(clf , open('Sales_Prediction_LassoRegresssion.pkl', 'wb'))
pickle.dump(regr , open('Sales_Prediction_RandomforestRegressor.pkl', 'wb'))import pickle
def model_prediction(features):
pickled_model = pickle.load(open('Sales_Prediction_LinearRegresssion.pkl', 'rb'))
Global_Sales_up = str(list(pickled_model.predict(features)))
return str(f'The Sale is {Global_Sales_up}')
We can test our model by giving our own parameters or features to predict.
Rank = 5
Platform = 1996.0
Year = 1996.0
Genre = 7
Publisher = 359
NA_Sales_up = 3.357082
EU_Sales_up = 2.981610
JP_Sales_up = 3.196873
Other_Sales_up = 2.000000model_prediction([[Rank, Platform, Year, Genre, Publisher, NA_Sales_up, EU_Sales_up, JP_Sales_up, Other_Sales_up]])'The Sale is [array([5.64553011])]'
Conclusion
After observing the problem statement we have build an efficient model to get the globle sales. The accuracy for the prediction is 98.08% and it signifies the accurate prediction of the global sales.
Checkout whole project code here (github repo).
🚀 Unlock Your Dream Job with HiDevs Community!
🔍 Seeking the perfect job? HiDevs Community is your gateway to career success in the tech industry. Explore free expert courses, job-seeking support, and career transformation tips.
💼 We offer an upskill program in Gen AI, Data Science, Machine Learning, and assist startups in adopting Gen AI at minimal development costs.
🆓 Best of all, everything we offer is completely free! We are dedicated to helping society.
Book free of cost 1:1 mentorship on any topic of your choice — topmate
✨ We dedicate over 30 minutes to each applicant’s resume, LinkedIn profile, mock interview, and upskill program. If you’d like our guidance, check out our services here
💡 Join us now, and turbocharge your career!
Deepak Chawla LinkedIn
Vijendra Singh LinkedIn
Yajendra Prajapati LinkedIn
YouTube Channel
Instagram Page
HiDevs LinkedIn
Project Youtube Link