Commit 7c3b73c1 authored by Shivanthi Fernando's avatar Shivanthi Fernando

Merge branch 'customer_retention_changes' into 'master'

Changes in customer retention

See merge request !25
parents 663d183a e0d7e3da
This diff is collapsed.
...@@ -59,4 +59,4 @@ class MyForm3(forms.Form): ...@@ -59,4 +59,4 @@ class MyForm3(forms.Form):
#Customer Frequency #Customer Frequency
class MyForm(forms.Form): class MyForm(forms.Form):
customerid = forms.IntegerField(label='Enter Customer ID' ) customerid = forms.IntegerField(label='Customer ID', widget=forms.TextInput(attrs={'class': 'input_field', 'required': True}))
...@@ -292,7 +292,7 @@ def AdminLogin(request): ...@@ -292,7 +292,7 @@ def AdminLogin(request):
# Customer Data # Customer Data
def Customer_Data(request): def Customer_Data(request):
data = pd.read_csv('Data/CustomerDataset.csv') data = pd.read_csv('Data/CustomerDatasetNew_4.csv')
finalpt = data.head(500) finalpt = data.head(500)
json_records = finalpt.reset_index().to_json(orient='records') json_records = finalpt.reset_index().to_json(orient='records')
arr = [] arr = []
...@@ -305,22 +305,21 @@ def Customer_Frequency(request): ...@@ -305,22 +305,21 @@ def Customer_Frequency(request):
if request.method == 'POST': if request.method == 'POST':
myForm = MyForm(request.POST) myForm = MyForm(request.POST)
if myForm.is_valid(): if myForm.is_valid():
# Loading the data # Loading the data
df = pd.read_csv('Data/CustomerDataset.csv') df = pd.read_csv('Data/CustomerDatasetNew_4.csv')
# Drop the missing data in `df` # Drop the missing data in dataframe
df_data = df.dropna() df_data = df.dropna()
# Convert the date field, InvoiceDate to datetime object # Convert the date field, InvoiceDate to datetime object
df_data.InvoiceDate = pd.to_datetime(df_data.InvoiceDate) df_data.InvoiceDate = pd.to_datetime(df_data.InvoiceDate)
ctm_bhvr_dt = df_data[(df_data.InvoiceDate < pd.Timestamp(2021, 10, 8)) # dataset End date ctm_bhvr_dt = df_data[(df_data.InvoiceDate < pd.Timestamp(2021, 12, 1)) # dataset End date
& (df_data.InvoiceDate >= pd.Timestamp(2021, 2, 12))].reset_index( & (df_data.InvoiceDate >= pd.Timestamp(2021, 5, 1))].reset_index(
drop=True) # dataset start date drop=True) # dataset start date
ctm_next_quarter = df_data[(df_data.InvoiceDate < pd.Timestamp(2022, 4, 8)) # predict date Till ctm_next_quarter = df_data[(df_data.InvoiceDate < pd.Timestamp(2022, 3, 1)) # predict date Till
& (df_data.InvoiceDate >= pd.Timestamp(2021, 10, 8))].reset_index( & (df_data.InvoiceDate >= pd.Timestamp(2021, 12, 1))].reset_index(
drop=True) # dataset End date drop=True) # dataset End date
# Get the distinct customers in the dataframe ctm_bhvr_dt # Get the distinct customers in the dataframe ctm_bhvr_dt
...@@ -330,16 +329,14 @@ def Customer_Frequency(request): ...@@ -330,16 +329,14 @@ def Customer_Frequency(request):
ctm_dt.columns = ['CustomerID'] ctm_dt.columns = ['CustomerID']
# Create a dataframe with CustomerID and customers first purchase # Create a dataframe with CustomerID and customers first purchase
# date in the dataset ctm_next_quarter
ctm_1st_purchase_in_next_quarter = ctm_next_quarter.groupby('CustomerID').InvoiceDate.min().reset_index() ctm_1st_purchase_in_next_quarter = ctm_next_quarter.groupby('CustomerID').InvoiceDate.min().reset_index()
ctm_1st_purchase_in_next_quarter.columns = ['CustomerID', 'MinPurchaseDate'] ctm_1st_purchase_in_next_quarter.columns = ['CustomerID', 'MinPurchaseDate']
# Create a dataframe with CustomerID and customers last purchase # Create a dataframe with CustomerID and customers last purchase
# date in the dataset ctm_bhvr_dt
ctm_last_purchase_bhvr_dt = ctm_bhvr_dt.groupby('CustomerID').InvoiceDate.max().reset_index() ctm_last_purchase_bhvr_dt = ctm_bhvr_dt.groupby('CustomerID').InvoiceDate.max().reset_index()
ctm_last_purchase_bhvr_dt.columns = ['CustomerID', 'MaxPurchaseDate'] ctm_last_purchase_bhvr_dt.columns = ['CustomerID', 'MaxPurchaseDate']
# Merge two dataframes ctm_last_purchase_bhvr_dt and ctm_1st_purchase_in_next_quarter # Merge two dataframes
ctm_purchase_dates = pd.merge(ctm_last_purchase_bhvr_dt, ctm_1st_purchase_in_next_quarter, on='CustomerID', ctm_purchase_dates = pd.merge(ctm_last_purchase_bhvr_dt, ctm_1st_purchase_in_next_quarter, on='CustomerID',
how='left') how='left')
...@@ -350,12 +347,8 @@ def Customer_Frequency(request): ...@@ -350,12 +347,8 @@ def Customer_Frequency(request):
# Update the dataframe ctm_dt by merging it with the NextPurchaseDay column of the dataframe ctm_purchase_dates # Update the dataframe ctm_dt by merging it with the NextPurchaseDay column of the dataframe ctm_purchase_dates
ctm_dt = pd.merge(ctm_dt, ctm_purchase_dates[['CustomerID', 'NextPurchaseDay']], on='CustomerID', ctm_dt = pd.merge(ctm_dt, ctm_purchase_dates[['CustomerID', 'NextPurchaseDay']], on='CustomerID',
how='left') how='left')
# Fill all missing values in the dataset ctm_dt with the number 9999
ctm_dt = ctm_dt.fillna("Not Returning") ctm_dt = ctm_dt.fillna('Will not return')
newloaded = ctm_dt.head()
print("-----------------Next Purchase Day-----------------")
# print(newloaded)
# Feature Engineering # Feature Engineering
# Recency # Recency
...@@ -376,7 +369,7 @@ def Customer_Frequency(request): ...@@ -376,7 +369,7 @@ def Customer_Frequency(request):
Recency = ctm_dt.head() Recency = ctm_dt.head()
# Frequency # Frequency
# Get service booking counts for each user and create a dataframe with it # Get order counts for each user and create a dataframe with it
ctm_frequency = df_data.groupby('CustomerID').InvoiceDate.count().reset_index() ctm_frequency = df_data.groupby('CustomerID').InvoiceDate.count().reset_index()
ctm_frequency.columns = ['CustomerID', 'Frequency'] ctm_frequency.columns = ['CustomerID', 'Frequency']
...@@ -384,42 +377,49 @@ def Customer_Frequency(request): ...@@ -384,42 +377,49 @@ def Customer_Frequency(request):
ctm_dt = pd.merge(ctm_dt, ctm_frequency, on='CustomerID') ctm_dt = pd.merge(ctm_dt, ctm_frequency, on='CustomerID')
Frequency = ctm_dt.head() Frequency = ctm_dt.head()
print(Frequency) print(Frequency)
# print(ctm_dt) df_data['Revenue'] = df_data.ServicePrice
# Monetary Value/Revenue
# Create a new label, Revenue of each item bought # df_data['Revenue'] = df_data.UnitPrice * df_data.Quantity
# Get the revenue from each customer and sum them.
ctm_revenue = df_data.groupby('CustomerID').Revenue.sum() / df_data.groupby(
# customer value persontage 'CustomerID').InvoiceDate.count()
totalALlcustomervalue = ctm_revenue.sum()
singlecustoemrvalue = ctm_revenue
# print(Frequency)
# ML Section Start
df2 = pd.read_csv('Data/CustomerDataset.csv') pntge = (singlecustoemrvalue / totalALlcustomervalue) * 100
sss = pd.DataFrame(pntge, columns=['persontageImpact'])
xxx = sss.head()
print(xxx)
ctm_dt = pd.merge(ctm_dt, sss, on='CustomerID')
Frequency = ctm_dt.head()
df2 = pd.read_csv('Data/CustomerDatasetNew_4.csv')
ctm_dt = pd.merge(ctm_dt, df2, on='CustomerID') ctm_dt = pd.merge(ctm_dt, df2, on='CustomerID')
# Merge the dataframe ctm_revenue with ctm_dt df0 = pd.read_csv('Data/CustomerDatasetNew_4.csv')
# ctm_dt = pd.merge(ctm_dt, ctm_revenue, on='CustomerID') df0 = df0.groupby('CustomerID')[
# Monetary = ctm_dt.head() 'ServicePrice', 'ServiceQualityRating', 'ResponseTimeRating', 'CustomerServiceRating'].sum()
# print(Monetary) df0 = pd.merge(df0, Frequency, on='CustomerID')
print(df0)
x = df0[['ServicePrice', 'ServiceQualityRating', 'ResponseTimeRating', 'CustomerServiceRating']]
y = df0[['Frequency']]
# split dataset for train and test
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)
# user LinearRegression
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(x_train, y_train)
# Building Machine Learning Models
# get data of Entered Customer
customerid = myForm.cleaned_data['customerid'] customerid = myForm.cleaned_data['customerid']
dfz = ctm_dt[(ctm_dt["CustomerID"] == customerid) ] dfz = ctm_dt[(ctm_dt["CustomerID"] == customerid)]
Frequency = dfz.head(1) Frequency = dfz.head(1)
print(Frequency) print(Frequency)
df = Frequency df = Frequency
# data = data.to_html()
json_records = df.reset_index().to_json(orient='records') json_records = df.reset_index().to_json(orient='records')
arr = []
arr = json.loads(json_records) arr = json.loads(json_records)
a = 2
form = MyForm() form = MyForm()
context = { 'form': form, 'd': arr} context = {'form': form, 'd': arr}
return render(request, 'Admin/Customer_Frequency.html', context) return render(request, 'Admin/Customer_Frequency.html', context)
else: else:
......
No preview for this file type
...@@ -44,10 +44,14 @@ ...@@ -44,10 +44,14 @@
<th> Customer Name </th> <th> Customer Name </th>
<th> Mobile Number</th> <th> Mobile Number</th>
<th> NIC </th> <th> NIC </th>
<th> Distance (km)</th>
<th> Vehicle No</th> <th> Vehicle No</th>
<th> Vehicle Type</th> <th> Vehicle Type</th>
<th> Service ID </th> <th> Service ID </th>
<th> Service Price </th> <th> Service Price </th>
<th> Service Quality Rating</th>
<th> Response Time Rating</th>
<th> Customer Service Rating</th>
<th> Invoice No</th> <th> Invoice No</th>
<th> Invoice Date </th> <th> Invoice Date </th>
...@@ -61,10 +65,15 @@ ...@@ -61,10 +65,15 @@
<td>{{i.CustomerName}}</td> <td>{{i.CustomerName}}</td>
<td>{{i.MobileNumber}}</td> <td>{{i.MobileNumber}}</td>
<td>{{i.NIC}}</td> <td>{{i.NIC}}</td>
<td>{{i.Distance}}</td>
<td>{{i.VehicleNo}}</td> <td>{{i.VehicleNo}}</td>
<td>{{i.VehicleType}}</td> <td>{{i.VehicleType}}</td>
<td>{{i.ServiceID}}</td> <td>{{i.ServiceID}}</td>
<td>{{i.ServicePrice}}</td> <td>{{i.ServicePrice}}</td>
<td>{{i.ServiceQualityRating}}</td>
<td>{{i.ResponseTimeRating}}</td>
<td>{{i.CustomerServiceRating}}</td>
<td>{{i.InvoiceNo}}</td> <td>{{i.InvoiceNo}}</td>
<td>{{i.InvoiceDate}}</td> <td>{{i.InvoiceDate}}</td>
......
...@@ -2,15 +2,44 @@ ...@@ -2,15 +2,44 @@
{% block content %} {% block content %}
{% load widget_tweaks %} {% load widget_tweaks %}
{%load static%} {%load static%}
<head> <head xmlns="http://www.w3.org/1999/html">
<!-- Font special for pages--> <!-- Font special for pages-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
<!-- Main CSS--> <!-- Main CSS-->
<link href="{% static "css/main.css" %}"rel="stylesheet" media="all"> <link href="{% static "css/main.css" %}"rel="stylesheet" media="all">
<style>
.input_field {
width: 100%;
padding: 12px 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
.table th
{
padding-top: 3px;
vertical-align: initial;
border-top: 0px;
font-weight: bold;
}
.table td
{
vertical-align: initial;
border-top: 0px;
}
.card-5 .card-body
{
padding: 52px 85px;
padding-bottom: 0px;
}
</style>
</head> </head>
<div class=" > <div style="background-color: white;" class=" >
<div class="wrapper wrapper 0"> <div class="wrapper wrapper 0">
<div style="margin-left: 0px;" class="card card-5"> <div style="margin-left: 0px;" class="card card-5">
...@@ -25,70 +54,62 @@ ...@@ -25,70 +54,62 @@
<div class="card-heading"> <div class="card-heading">
<h2 class="title mt-3" style="color: #02111f;"> PREDICT CUSTOMER RETENTION </h2> <h2 class="title mt-3" style="color: #02111f;"> PREDICT CUSTOMER RETENTION </h2>
<h4 CLASS="title mt-3" style="color: #02111f;">BASED ON THE FACTORS AFFECTING FOR CUSTOMER SATISFACTION</h4>
</div> </div>
<div class="card-body"> <div class="card-body">
<form action="/Admin/Customer_Frequency/" method="post"> <form action="/Admin/Customer_Frequency/" method="post">
{% csrf_token %} {% csrf_token %}
<table class="table table-light"> {{form}}
{{form.as_table}}
</table>
<input type="submit" value="PREDICT" class="btn btn--radius-2" style="background: #02111f;"/>
<div class="container">
</form> <br><div class="text-right"> <div class="row mt-5 mb-3">
<input name="b_print" type="button" class="btn btn-print" onClick="printdiv('div_print');" value=" Print " style="background: #02111f;"> <div class="col text-center">
<input type="submit" value="PREDICT" class="btn w-50" style="background: #02111f; border-radius: 50px;"/>
</div>
</div> </div>
</div>
</form>
<br>
<div class="text-right"></div>
<br> <br>
</div> </div>
</div> </div>
</div> </div>
<div id="myDiv"> <div id="myDiv">
<div id="div_print"> <div id="div_print">
<div class="card card-body printableArea"> <div class="card card-body printableArea">
<div role="alert">
<div role="alert" >
<div class="container" style="overflow-x:auto;"> <div class="container" style="overflow-x:auto;">
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
<th> Customer ID </th> <th>Customer ID </th>
<th> Customer Name </th> <th>Customer Name </th>
<th> Vehicle Number </th> <th>Next Purchase In </th>
<th> Vehicle Type </th> <th>Purchased Frequency </th>
<th> Next Return In </th> <th>Impact on Profitability </th>
<th> Return Frequency </th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% if d %} {% if d %}
{% for i in d %} {% for i in d %}
<tr> <tr>
<td> {{i.CustomerID}} </td> <td>{{i.CustomerID}} </td>
<td> {{i.CustomerName}} </td> <td>{{i.CustomerName}} </td>
<td> {{i.VehicleNo}} </td> <td>{{i.NextPurchaseDay}} </td>
<td> {{i.VehicleType}} </td> <td>{{i.Frequency}} </td>
<td> {{i.NextPurchaseDay}} </td> <td>{{i.persontageImpact}} % </td>
<td>{{i.Frequency}}</td>
</tr> </tr>
{% endfor %} {% endfor %}
{% endif %} {% endif %}
</tbody> </tbody>
</table> </table>
</div> </div>
</div>
</div> </div>
</div>
</div></div></div> </div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment