Sales Prediction

Sales Prediction

Objective:

A sale is a transaction between two or more parties in which goods or services are exchanged for money or other assets. In the financial markets, a sale is an agreement between a buyer and seller involving the price of a security and its delivery for agreed-upon compensation.

Sales prediction means predicting how much of a product people will buy based on factors such as the amount you spend to advertise your product, the segment of people you advertise for, or the platform you are advertising on about your product.

Typically, a product’s sales are primarily dependent on how much you spend on advertising it, as the more people your product reaches, the more sales will increase as long as the quality of your product is good.

The goal of this challenge is to build a machine learning model to predict the Sales of a products.

Dataset:

The dataset used in this model is publicly available and free to use.

Attribute Information:

  1. TV

  2. Radio

  3. Newspaper

  4. 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/YAJENDRA/Documents/final notebooks/Sales Prediction/data/advertising.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()

png

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.

Why we drop column?

By analysing the first five rows we found that there is no 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 200 rows and 4 columns
df['Sales'].value_counts()
11.9    5  
16.7    5  
20.7    4  
11.0    3  
11.3    3  
       ..  
13.4    1  
24.2    1  
8.1     1  
5.5     1  
25.5    1  
Name: Sales, Length: 121, dtype: int64

The df.value_counts() method counts the number of types of values a particular column contains.

df.shape
(200, 4)

The df.shape method shows the shape of the dataset.

df.info()
<class 'pandas.core.frame.DataFrame'>  
RangeIndex: 200 entries, 0 to 199  
Data columns (total 4 columns):  
 #   Column     Non-Null Count  Dtype    
---  ------     --------------  -----    
 0   TV         200 non-null    float64  
 1   Radio      200 non-null    float64  
 2   Newspaper  200 non-null    float64  
 3   Sales      200 non-null    float64  
dtypes: float64(4)  
memory usage: 6.4 KB

The df.info() method prints information about a DataFrame including the index dtype and columns, non-null values and memory usage.

df.iloc[1]
TV           44.5  
Radio        39.3  
Newspaper    45.1  
Sales        10.4  
Name: 1, dtype: float64

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  0  
There names are as follows:  []
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  0  
There names are as follows:  []
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  4  
There name are as follow:  ['TV', 'Radio', 'Newspaper', '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 200 rows and 4 columns

Step 2 Insights: -

  1. There are 4 columns that are of float type.

  2. The categorical columns are 0.

  3. The number of numerical column is 0. 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.

df.describe()

png

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.

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()
TV           85.854236  
Radio        14.846809  
Newspaper    21.778621  
Sales         5.283892  
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_df

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()
TV           7370.949893  
Radio         220.427743  
Newspaper     474.308326  
Sales          27.919517  
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_df

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 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()
TV           147.0425  
Radio         23.2640  
Newspaper     30.5540  
Sales         15.1305  
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_df

Median

df.median()
TV           149.75  
Radio         22.90  
Newspaper     25.75  
Sales         16.00  
dtype: float64

Null and Nan values

  1. 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()
TV           0  
Radio        0  
Newspaper    0  
Sales        0  
dtype: int64

As we notice that there are no null values in our dataset.

  1. 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()
TV           0  
Radio        0  
Newspaper    0  
Sales        0  
dtype: int64
df.dropna(inplace=True)

The way to remove null and nan values is to use the method “df.dropna(inplace=True)”.

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()

png

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 0x206e8c33cd0>

png

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['Sales'].skew()
-0.07373923537186912

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()

png

corr

png

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 = ['TV','Radio','Newspaper','Sales']
for value in features:  
    sns.catplot(data=df,x=value,kind="box")

png

png

png

png

sns.catplot(data=df, x='Sales', kind='box')
<seaborn.axisgrid.FacetGrid at 0x2068b91b1d0>

png

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:

  1. 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.

  2. Split dataset into train and test dataset.

  3. 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 = 'Sales'  

# 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'>  
RangeIndex: 200 entries, 0 to 199  
Data columns (total 3 columns):  
 #   Column     Non-Null Count  Dtype    
---  ------     --------------  -----    
 0   TV         200 non-null    float64  
 1   Radio      200 non-null    float64  
 2   Newspaper  200 non-null    float64  
dtypes: float64(3)  
memory usage: 4.8 KB
y
0      22.1  
1      10.4  
2      12.0  
3      16.5  
4      17.9  
       ...   
195     7.6  
196    14.0  
197    14.8  
198    25.5  
199    18.4  
Name: Sales, Length: 200, dtype: float64
# Check the shape of X and y variable  
X.shape, y.shape
((200, 3), (200,))
# Reshape the y variable   
y = y.values.reshape(-1,1)
# Again check the shape of X and y variable  
X.shape, y.shape
((200, 3), (200, 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
((160, 3), (40, 3), (160, 1), (40, 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

  1. Linear Regression

  2. Lasso Regression

  3. 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

#Using Linear Regression   
from sklearn.linear_model import LinearRegression  

model = LinearRegression()  
model.fit(X_train, y_train)  
model.score(X_test, y_test)
0.9059011844150826
#Accuracy check of trainig data  
from sklearn.metrics import r2_score  
#Get R2 score  
model.score(X_train, y_train)
0.9001416005862131
#Accuracy of test data  
model.score(X_test, y_test)
0.9059011844150826
# Getting kfold values  
lg_scores = -1 * cross_val_score(model,   
                                 X_train,   
                                 y_train,   
                                 cv=cv,   
                                 scoring='neg_root_mean_squared_error')  
lg_scores
array([1.93883543, 1.73707326, 1.78736643, 2.43294748, 1.3375628 ,  
       1.75476907, 1.6382903 , 1.24382621, 1.58531158, 1.12699827])
# Mean of the train kfold scores  
lg_score_train = np.mean(lg_scores)  
lg_score_train
1.6582980835211838

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.

  1. Confusion Matrix 2)Classification Report 3)Accuracy Score 4)Precision Score 5)Recall Score 6)F1 Score

Confusion Matrix

A confusion matrix presents a table layout of the different outcomes of the prediction and results of a classification problem and helps visualize its outcomes. It plots a table of all the predicted and actual values of a classifier.

confusion-matrix.jpeg

This diagram helps in understanding the concept of confusion matrix.

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.

# Evaluating the classifier  
# printing every score of the classifier  
# scoring in anything  
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 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: 90.59011844150827

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)

In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

Lasso

Lasso(alpha=0.1)

#Accuracy check for training data  
clf.score(X_train,y_train)
0.9001396346012004
y_predicted1 = clf.predict(X_test)
#Accuracy check of test data  
lg = r2_score(y_test,y_predicted1)*100  
lg
90.58505279101615
#Get kfold values  
Nn_scores = -1 * cross_val_score(clf,   
                                    X_train,   
                                    y_train,   
                                    cv=cv,   
                                    scoring='neg_root_mean_squared_error')  
Nn_scores
array([1.93946071, 1.73210719, 1.78368532, 2.43034057, 1.33870839,  
       1.75361599, 1.63882073, 1.2454729 , 1.58751173, 1.13008202])
# Mean of the train kfold scores  
Nn_score_train = np.mean(Nn_scores)  
Nn_score_train
1.657980555829809
print("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: 90.59011844150827

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)

In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

RandomForestRegressor

RandomForestRegressor(max_depth=2, random_state=0)

#Accuracy check of trainig data  
#Get R2 score  
regr.score(X_train, y_train)
0.8724134371345867
# Get kfold values  
Dta_scores = -1 * cross_val_score(regr,   
                                    X_train,   
                                    y_train,   
                                    cv=cv,   
                                    scoring='neg_root_mean_squared_error')  
Dta_scores
array([1.64618212, 1.31919565, 2.88192937, 2.51014474, 2.23766691,  
       2.19488313, 2.04460424, 2.21278946, 1.80797889, 2.1921633 ])
# Mean of the train kfold scores  
Dta_score_train = np.mean(Dta_scores)  
Dta_score_train
2.104753782165855

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 89.4779090046208

Insight

cal_metric=pd.DataFrame([rg,lg,r_acc],columns=["Sales"])  
cal_metric.index=['Linear Regression',  
                  'Lasso Regression','Random forest Regressor']  
cal_metric

png

  • As you can see with our Linear Regression Model(98.59%) 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_PredictionLinear_Regresssion.pkl', 'wb'))  
pickle.dump(clf , open('Sales_PredictionLasso_Regresssion.pkl', 'wb'))  
pickle.dump(regr , open('Sales_PredictionRandom_forest_Regressor.pkl', 'wb'))
import pickle  

def model_prediction(features):  

    pickled_model = pickle.load(open('Sales_PredictionLinear_Regresssion.pkl', 'rb'))  
    Sales = str(list(pickled_model.predict(features)))  

    return str(f'The Sale is {Sales}')

We can test our model by giving our own parameters or features to predict.

TV = 200.5  
Radio = 35.3  
Newspaper = 68.4
model_prediction([[TV,Radio,Newspaper]])
'The Sale is [array([19.50323314])]'

Conclusion

After observing the problem statement we have build an efficient model to get the Sales. The accuracy for the prediction is 90.59 and it signifies the accurate prediction of the Sales.

Checkout whole project codehere(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 LinkedInVijendra Singh LinkedInYajendra Prajapati LinkedInYouTube ChannelInstagram PageHiDevs LinkedInProject Youtube LinkStreamlit Application Link