Commit 43413f9a authored by Shivanthi Fernando's avatar Shivanthi Fernando

Modifications in customer retention

parent fe01bf90
This diff is collapsed.
from django import forms from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.forms import DateInput from django.forms import DateInput
from . import models from . import models
...@@ -33,8 +34,8 @@ class MyForm5(forms.Form): ...@@ -33,8 +34,8 @@ class MyForm5(forms.Form):
class MyForm2(forms.Form): class MyForm2(forms.Form):
UserName = forms.CharField(label='User Name') UserName = forms.CharField(label='User Name', widget=forms.TextInput(attrs={'class': 'input_field'}))
Password = forms.CharField(label='Password', widget=forms.PasswordInput) Password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'input_field'}))
MODE_CHOICES2 = [ MODE_CHOICES2 = [
...@@ -59,4 +60,6 @@ class MyForm3(forms.Form): ...@@ -59,4 +60,6 @@ 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}))
...@@ -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
...@@ -20,17 +20,17 @@ ...@@ -20,17 +20,17 @@
</head> </head>
<style> <style>
body body
{ {
background-image:url('{% static 'image/vehicle_service.jpg'%}'); background-image:url('{% static 'image/vehicle_service.jpg'%}');
background-repeat:no-repeat; background-repeat:no-repeat;
background-size:100%; background-size:100%;
} }
.login_form .login_form
{ {
width: 400px; width: 400px;
height: 400px; height: 450px;
background: #CFD8DC; background: #CFD8DC;
color: #000; color: #000;
top: 50%; top: 50%;
...@@ -39,37 +39,58 @@ background-size:100%; ...@@ -39,37 +39,58 @@ background-size:100%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
box-sizing: border-box; box-sizing: border-box;
border-radius: 25px; border-radius: 25px;
} }
.login_text .login_text
{ {
margin-top: 75px; margin-top: 75px;
text-align: center; text-align: center;
margin-bottom: 30px; margin-bottom: 30px;
font-weight: bold; font-weight: bold;
color: #02111f; color: #02111f;
} }
.logo .logo
{ {
height: 150px; height: 150px;
width: 150px; width: 150px;
position: absolute; position: absolute;
top: -20%; top: -20%;
left: calc(42% - 42px); left: calc(42% - 42px);
} }
.login_btn .login_btn
{ {
margin-left: 12%; margin-left: 12%;
margin-right:12%; margin-right:12%;
margin-top: 7%; margin-top: 5%;
background: #02111f; background: #02111f;
color: #fff; color: #fff;
width: 300px; width: 300px;
border-radius: 25px; border-radius: 25px;
text-align: center; text-align: center;
} }
.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;
}
.table td
{
vertical-align: initial;
border-top: 0px;
}
</style> </style>
......
...@@ -37,20 +37,22 @@ ...@@ -37,20 +37,22 @@
<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> 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>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
...@@ -61,13 +63,16 @@ ...@@ -61,13 +63,16 @@
<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>
</tr> </tr>
{% endfor %} {% endfor %}
{% endif %} {% endif %}
......
{% extends 'Admin/Sidebar2.html' %} {% extends 'Admin/Sidebar2.html' %}
{% block content %} {% block content %}
{% load widget_tweaks %} {% load widget_tweaks %}
{%load static%} {% load static%}
<head> <head>
<!-- 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">
{% if messages %} {% if messages %}
<ul class="messages">
<ul class="messages">
{% for message in messages %} {% for message in messages %}
<li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li> <li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endif %}
{% endif %}
<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> <div class="container">
<input type="submit" value="PREDICT" class="btn btn--radius-2" style="background: #02111f;"/> <div class="row mt-5 mb-3">
<div class="col text-center">
<input type="submit" value="PREDICT" class="btn w-50" style="background: #02111f; border-radius: 50px;"/>
</form> <br><div class="text-right"> </div>
<input name="b_print" type="button" class="btn btn-print" onClick="printdiv('div_print');" value=" Print " style="background: #02111f;"> </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>
<script language="javascript"> <script language="javascript">
function printdiv(printpage) { function printdiv(printpage) {
......
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