ellyothim's picture
Update app.py
515a7e5
raw
history blame
8.56 kB
# -*- coding: utf-8 -*-
"""Capstone Gradio App Embedding.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zsT_lHGVHzG29XSb4tMF3UdA6glyWnRx
"""
# from google.colab import drive
# drive.mount('/content/drive')
#!pip install gradio
#!pip install category_encoders
"""### **DATA PREP**"""
import pandas as pd
import numpy as np
import gradio as gr
from sklearn.model_selection import train_test_split
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, confusion_matrix, recall_score, precision_recall_curve, f1_score
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.preprocessing import LabelEncoder
import gdown
#train = pd.read_csv('https://drive.google.com/file/d/1U1ic5GE42_cxs8VvuOx7EDaHqtA0oEFC/view?usp=sharing.csv')
#https://drive.google.com/file/d/1U1ic5GE42_cxs8VvuOx7EDaHqtA0oEFC/view?usp=sharing
file_id = '1U1ic5GE42_cxs8VvuOx7EDaHqtA0oEFC'
# Define the URL to download the file
url = f'https://drive.google.com/uc?id={file_id}'
# Download the file and name it 'train.csv'
output_file = 'train.csv'
gdown.download(url, output_file, quiet=False)
# Read the CSV file with Pandas
train = pd.read_csv(output_file)
# use lambda function to remove \t make our model more robst
train = train.applymap(lambda x: x.replace("\t" , '' ) if isinstance (x , str) else x)
# " " , " "
train = train.applymap(lambda x: x.replace(" " , ' ' ) if isinstance (x , str) else x)
# drop what we don't need
train.drop(columns=['MRG', 'user_id', 'ZONE1', 'ZONE2', 'TOP_PACK'], inplace=True)
train["REGION"].fillna(method='ffill', inplace=True)
train["TENURE"].fillna(method='ffill', inplace=True)
train["MONTANT"].fillna(train["MONTANT"].median(), inplace=True)
train["FREQUENCE_RECH"].fillna(0, inplace=True)
train["REVENUE"].fillna(train["REVENUE"].median(), inplace=True)
train["ARPU_SEGMENT"].fillna(0, inplace=True)
train["FREQUENCE"].fillna(0, inplace=True)
train["DATA_VOLUME"].fillna(0, inplace=True)
train["ON_NET"].fillna(0, inplace=True)
train["ORANGE"].fillna(0, inplace=True)
train["TIGO"].fillna(0, inplace=True)
train["REGULARITY"].fillna(train["REGULARITY"].mean(), inplace=True)
train["FREQ_TOP_PACK"].fillna(train["FREQ_TOP_PACK"].mean(), inplace=True)
train['TENURE'] = train['TENURE'].str.replace('D 3-6 month', '1', regex=True)
train['TENURE'] = train['TENURE'].str.replace('E 6-9 month', '2', regex=True)
train['TENURE'] = train['TENURE'].str.replace('F 9-12 month', '3', regex=True)
train['TENURE'] = train['TENURE'].str.replace('J 21-24 month', '4', regex=True)
train['TENURE'] = train['TENURE'].str.replace('G 12-15 month', '5', regex=True)
train['TENURE'] = train['TENURE'].str.replace('H 15-18 month', '6', regex=True)
train['TENURE'] = train['TENURE'].str.replace('I 18-21 month', '7', regex=True)
train['TENURE'] = train['TENURE'].str.replace('K > 24 month', '8', regex=True)
# train['TENURE'].value_counts()
# Define a dictionary to map values
region_mapping = {
'DAKAR': '1',
'THIES': '2',
'SAINT-LOUIS': '3',
'LOUGA': '4',
'KAOLACK': '5',
'DIOURBEL': '6',
'TAMBACOUNDA': '7',
'KAFFRINE': '8',
'KOLDA': '9',
'FATICK': '10',
'ZIGUINCHOR': '11',
'SEDHIOU': '12',
'KEDOUGOU': '13',
'MATAM' : '14'
}
# Use the replace method to map values
train['REGION'] = train['REGION'].replace(region_mapping)
# Look at the new value_counts
# print(train['REGION'].value_counts())
"""## **FITTING AND TRAINING**"""
"""Select target and features"""
y = train['CHURN']
x = train.drop(columns='CHURN', axis=1)
X_train, X_test, y_train, y_test = train_test_split(x,y,test_size = 0.5,random_state=45 )# , stratify=y)
#Further split X_train and y_train into train and validation sets
X_train,X_val,y_train,y_val = train_test_split(X_train,y_train,test_size = 0.3, random_state=1 )#, stratify=y)
"""### SCALE NUMERICAL COLUMNS"""
num_cols = ['MONTANT', 'FREQUENCE_RECH', 'REVENUE', 'ARPU_SEGMENT', 'FREQUENCE',
'DATA_VOLUME', 'ON_NET', 'ORANGE', 'TIGO',
'REGULARITY', 'FREQ_TOP_PACK']
scaler = StandardScaler()
X_train[num_cols] = scaler.fit_transform(X_train[num_cols])
X_val[num_cols] = scaler.fit_transform(X_val[num_cols])
# Create an instance
model = ExtraTreesRegressor(
n_estimators=100, # Number of trees in the forest
max_depth=10, # Maximum depth of the tree
random_state=42 # Random seed for reproducibility
)
# Train the model
MODEL = model.fit(X_train, y_train)
"""## **Check if our model is working**"""
y_pred = MODEL.predict(X_test)
def classifier_1(result):
if result > 0.9:
return "Customer will churn"
else:
return "Customer will not churn"
def predict(REGION,TENURE , MONTANT , FREQUENCE_RECH, REVENUE , ARPU_SEGMENT ,FREQUENCE , DATA_VOLUME , ON_NET, ORANGE , TIGO, REGULARITY ,FREQ_TOP_PACK):
input_array = np.array([[REGION,TENURE , MONTANT , FREQUENCE_RECH, REVENUE , ARPU_SEGMENT ,FREQUENCE , DATA_VOLUME , ON_NET, ORANGE , TIGO, REGULARITY ,FREQ_TOP_PACK]])
pred = MODEL.predict(input_array)
output = classifier_1 (pred[0])
if output == "Customer will churn":
return [(0, output)]
else :
return [(1, output)]
#tenure = tenure_dropdown
REGION = gr.inputs.Slider(minimum=1, maximum=13, label='Location of each client')
TENURE = gr.inputs.Slider(minimum=1, maximum=8, label="Duration in network")
MONTANT = gr.inputs.Slider(minimum=22, maximum=470000, label="Top up amount")
FREQUENCE_RECH = gr.inputs.Slider(minimum=1, maximum=131, label="income frequency")
REVENUE = gr.inputs.Slider(minimum=1, maximum=532177, label="ARPU_SEGMENT")
ARPU_SEGMENT = gr.inputs.Slider(minimum=1, maximum= 177392, label="FREQUENCE")
FREQUENCE = gr.inputs.Slider(minimum=1, maximum=91, label="DATA_VOLUME")
DATA_VOLUME =gr.inputs.Slider(minimum=0, maximum=1702309, label="ON_NET")
ON_NET = gr.inputs.Slider(minimum=0, maximum=36687, label="ORANGE")
ORANGE = gr.inputs.Slider(minimum=0, maximum= 6721, label="TIGO")
TIGO = gr.inputs.Slider(minimum=0, maximum=4174, label="ZONE1")
REGULARITY = gr.inputs.Slider(minimum=1, maximum=62, label="ZONE2")
FREQ_TOP_PACK = gr.inputs.Slider(minimum=1, maximum= 592, label="REGULARITY")
op = gr.outputs.HighlightedText(color_map={"Customer will churn":"pink", "Customer will not churn":"yellow"})
gr.Interface(predict , inputs = [REGION,TENURE, MONTANT , FREQUENCE_RECH, REVENUE , ARPU_SEGMENT ,FREQUENCE , DATA_VOLUME , ON_NET, ORANGE ,TIGO, REGULARITY ,FREQ_TOP_PACK], outputs=op,
live = True).launch(debug=True)
# Input sliders
# REGION = gr.inputs.Slider(minimum=1, maximum=13, label='Location of each client')
# TENURE = gr.inputs.Slider(minimum=1, maximum=8, label="Duration in network")
# MONTANT = gr.inputs.Slider(minimum=22, maximum=470000, label="Top-up amount")
# FREQUENCE_RECH = gr.inputs.Slider(minimum=1, maximum=131, label="Income frequency")
# REVENUE = gr.inputs.Slider(minimum=1, maximum=532177, label="ARPU_SEGMENT")
# ARPU_SEGMENT = gr.inputs.Slider(minimum=1, maximum=177392, label="FREQUENCE")
# FREQUENCE = gr.inputs.Slider(minimum=1, maximum=91, label="DATA_VOLUME")
# DATA_VOLUME = gr.inputs.Slider(minimum=0, maximum=1702309, label="ON_NET")
# ON_NET = gr.inputs.Slider(minimum=0, maximum=36687, label="ORANGE")
# ORANGE = gr.inputs.Slider(minimum=0, maximum=6721, label="TIGO")
# TIGO = gr.inputs.Slider(minimum=0, maximum=4174, label="ZONE1")
# REGULARITY = gr.inputs.Slider(minimum=1, maximum=62, label="ZONE2")
# FREQ_TOP_PACK = gr.inputs.Slider(minimum=1, maximum=592, label="REGULARITY")
# # Output configuration
# op = gr.outputs.HighlightedText(color_map={"Customer will churn": "pink", "Customer will not churn": "yellow"})
# # Create and launch the interface
# gr.Interface(predict, inputs=[REGION, TENURE, MONTANT, FREQUENCE_RECH, REVENUE, ARPU_SEGMENT, FREQUENCE,
# DATA_VOLUME, ON_NET, ORANGE, TIGO, REGULARITY, FREQ_TOP_PACK], outputs=op,
# live=False).launch(debug=False)
# # Map numerical values to labels
# tenure_labels = {
# 0: "3-6 months",
# 1: "6-9 months",
# 2: "9-12 months",
# 3: "12-15 months",
# 4: "15-18 months",
# 5: "18-21 months",
# 6: "21-24 months",
# 7: "> 24 months"
# }
# # Reverse the mapping for predictions
# tenure_values = {v: k for k, v in tenure_labels.items()}
# # Create a dropdown menu with labels
# tenure_dropdown = gr.inputs.Dropdown(list(tenure_labels.values()), label="TENURE")