-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestapp.py
More file actions
143 lines (120 loc) · 6.07 KB
/
testapp.py
File metadata and controls
143 lines (120 loc) · 6.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# Import libraries
import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import seaborn as sns
import joblib
# Load the model from disk
model = joblib.load(r"./notebook/model.sav")
# Import python scripts
from preprocessing import preprocess
def plot_histogram(data, column, color):
plt.figure(figsize=(8, 4))
plt.hist(data[column], bins=20, color=color, edgecolor='black')
plt.title(f'Distribution of {column}')
plt.xlabel(column)
plt.ylabel('Frequency')
return plt
def plot_pie_chart(data, column):
plt.figure(figsize=(8, 4))
data[column].value_counts().plot(kind='pie', autopct='%1.1f%%')
plt.title(f'Distribution of {column}')
plt.ylabel('')
return plt
def plot_correlation_heatmap(data):
plt.figure(figsize=(10, 6))
sns.heatmap(data.corr(), annot=True, fmt=".2f")
plt.title('Correlation Heatmap')
return plt
def main():
# Setting Application title and description
st.title('Telco Customer Churn Prediction App')
st.markdown("""
:dart: This Streamlit app is made to predict customer churn in a fictional telecommunication use case.
The application is functional for both online prediction and batch data prediction. \n
""")
image = Image.open('App.jpg')
st.sidebar.image(image)
# Application sidebar
add_selectbox = st.sidebar.selectbox(
"How would you like to predict?", ("Online", "Batch"))
if add_selectbox == "Online":
st.info("Input data below")
#Based on our optimal features selection
st.subheader("Demographic data")
seniorcitizen = st.selectbox('Senior Citizen:', ('Yes', 'No'))
dependents = st.selectbox('Dependent:', ('Yes', 'No'))
st.subheader("Payment data")
tenure = st.slider('Number of months the customer has stayed with the company', min_value=0, max_value=72, value=0)
contract = st.selectbox('Contract', ('Month-to-month', 'One year', 'Two year'))
paperlessbilling = st.selectbox('Paperless Billing', ('Yes', 'No'))
PaymentMethod = st.selectbox('PaymentMethod',('Electronic check', 'Mailed check', 'Bank transfer (automatic)','Credit card (automatic)'))
monthlycharges = st.number_input('The amount charged to the customer monthly', min_value=0, max_value=150, value=0)
totalcharges = st.number_input('The total amount charged to the customer',min_value=0, max_value=10000, value=0)
st.subheader("Services signed up for")
mutliplelines = st.selectbox("Does the customer have multiple lines",('Yes','No','No phone service'))
phoneservice = st.selectbox('Phone Service:', ('Yes', 'No'))
internetservice = st.selectbox("Does the customer have internet service", ('DSL', 'Fiber optic', 'No'))
onlinesecurity = st.selectbox("Does the customer have online security",('Yes','No','No internet service'))
onlinebackup = st.selectbox("Does the customer have online backup",('Yes','No','No internet service'))
techsupport = st.selectbox("Does the customer have technology support", ('Yes','No','No internet service'))
streamingtv = st.selectbox("Does the customer stream TV", ('Yes','No','No internet service'))
streamingmovies = st.selectbox("Does the customer stream movies", ('Yes','No','No internet service'))
data = {
'SeniorCitizen': seniorcitizen,
'Dependents': dependents,
'tenure':tenure,
'PhoneService': phoneservice,
'MultipleLines': mutliplelines,
'InternetService': internetservice,
'OnlineSecurity': onlinesecurity,
'OnlineBackup': onlinebackup,
'TechSupport': techsupport,
'StreamingTV': streamingtv,
'StreamingMovies': streamingmovies,
'Contract': contract,
'PaperlessBilling': paperlessbilling,
'PaymentMethod':PaymentMethod,
'MonthlyCharges': monthlycharges,
'TotalCharges': totalcharges
}
features_df = pd.DataFrame.from_dict([data])
st.markdown("<h3></h3>", unsafe_allow_html=True)
st.write('Overview of input is shown below')
st.markdown("<h3></h3>", unsafe_allow_html=True)
st.dataframe(features_df)
#Preprocess inputs
preprocess_df = preprocess(features_df, 'Online')
prediction = model.predict(preprocess_df)
if st.button('Predict'):
if prediction == 1:
st.warning('Yes, the customer will terminate the service.')
else:
st.success('No, the customer is happy with Telco Services.')
else:
# Batch prediction
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
st.write(data.head())
# Optional: Plotting the pie chart for Contract
if st.checkbox('Show Distribution of Contract Types'):
st.pyplot(plot_pie_chart(data, 'Contract'))
# Optional: Plotting correlation heatmap
if st.checkbox('Show Correlation Heatmap'):
st.pyplot(plot_correlation_heatmap(data))
#Preprocess inputs
preprocess_df = preprocess(data, "Batch")
if st.button('Predict'):
#Get batch prediction
prediction = model.predict(preprocess_df)
prediction_df = pd.DataFrame(prediction, columns=["Predictions"])
prediction_df = prediction_df.replace({1:'Yes, the customer will terminate the service.',
0:'No, the customer is happy with Telco Services.'})
st.markdown("<h3></h3>", unsafe_allow_html=True)
st.subheader('Prediction')
st.write(prediction_df)
if __name__ == '__main__':
main()