Spaces:
Build error
Build error
# -*- 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 | |
"""### **DATA PREP**""" | |
import pandas as pd | |
# # Specify the correct file paths for your data files | |
# test = pd.read_csv('/content/drive/MyDrive/datasets capstone/test.csv') | |
# y_train = pd.read_csv("/content/drive/MyDrive/datasets capstone/y_train.csv") | |
# X_train =pd.read_csv('/content/drive/MyDrive/datasets capstone/X_train.csv') | |
# #X_test = pd.read_csv("/content/test.csv") | |
path = "/content/drive/MyDrive/Capstone Project /" | |
train = pd.read_csv(path + 'Train.csv') | |
# 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.head(1) | |
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["ZONE1"].fillna(0, inplace=True) | |
# train["ZONE2"].fillna(0, inplace=True) | |
# train["MRG"].fillna(method='ffill', inplace=True) | |
train["REGULARITY"].fillna(train["REGULARITY"].mean(), inplace=True) | |
#train["TOP_PACK"].fillna(method='ffill', 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**""" | |
# train.head(1) | |
"""Select target and features""" | |
y = train['CHURN'] | |
x = train.drop(columns='CHURN', axis=1) | |
# y.head(3) | |
# x.head(2) | |
from sklearn.model_selection import train_test_split | |
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]) | |
#X_train.head(3) | |
"""### ENCODE CATEGORICAL COLS WITH NUMERICAL VALUES WITH MANY N_UNIQUE( ) VALS | |
""" | |
!pip install category_encoders | |
# import category_encoders as ce | |
# encoder_ = ce.SumEncoder(cols=['TOP_PACK']) | |
# encoder.fit(x, y) | |
# X_train = encoder.transform(X_train) | |
# X_val = encoder.transform(X_val) | |
# X_test = encoder.transform(X_test) | |
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 | |
# 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) | |
y_pred | |
"""Since our model is working correctly , Inspect the X_test features , to be used as the user input to interact with the model""" | |
X_test.head() | |
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)] | |
"""Check if the function will work""" | |
predict(1,2,3,4,5,6,7,8,9,1,1,1,1) | |
variable_definitions | |
X_test['FREQ_TOP_PACK'].min() , X_test['FREQ_TOP_PACK'].max() | |
import gradio as gr | |
#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) | |
import gradio as gr | |
# 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") | |