Title : “Customer Churn Prediction & Retention Analysis”¶
BUSINESS PROBLEM¶
1.Companies are facing high customer churn, which leads to revenue loss and reduced growth.¶
2.It is difficult for businesses to identify which customers are likely to stop using their services.¶
3.Customer churn increases the cost of acquiring new customers and impacts profitability.¶
4.There is a need for a predictive system to analyze customer behavior and detect churn risk.¶
5.This project helps organizations take proactive actions to retain valuable customers.¶
Target Column¶
Churn (or your dataset column name, e.g., Exited, Attrition, etc.)
In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.metrics import f1_score, classification_report
from imblearn.over_sampling import SMOTE
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Input,Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.regularizers import l1_l2
from tensorflow.keras.metrics import Recall
import optuna
C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages\tqdm\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
In [2]:
df=pd.read_csv(r"C:\Users\MEENAKSHI\Downloads\customer_churn_1M.csv")
In [3]:
df
Out[3]:
| customer_id | signup_date | age | gender | annual_income | education | marital_status | dependents | tenure | contract | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | churn | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CUST0000000001 | 2022-12-12 12:53:58.199463 | 43 | Female | 55085.25 | college | married | 1 | 2 | two_year | ... | 1 | 1 | 9.0 | 0.0 | 0 | 0 | 109.63 | 16 | NaN | 0 |
| 1 | CUST0000000002 | 2022-01-13 12:53:58.199973 | 18 | Male | 60786.11 | master | married | 1 | 22 | one_year | ... | 0 | 1 | 7.0 | 0.0 | 3 | 1 | 63.25 | 134 | 585.0 | 0 |
| 2 | CUST0000000003 | 2023-09-04 12:53:58.199985 | 38 | Female | 73184.32 | high_school | widowed | 0 | 3 | two_year | ... | 1 | 0 | 6.0 | 1.0 | 1 | 0 | 47.77 | 11 | 632.0 | 0 |
| 3 | CUST0000000004 | 2022-06-27 12:53:58.199992 | 44 | Male | 40923.78 | high_school | married | 1 | 6 | two_year | ... | 0 | 1 | 5.0 | 2.0 | 2 | 1 | 50.82 | 6 | 569.0 | 0 |
| 4 | CUST0000000005 | 2022-12-08 12:53:58.199999 | 45 | Female | 36400.94 | bachelor | single | 0 | 9 | two_year | ... | 0 | 1 | 8.0 | 1.0 | 1 | 0 | 16.74 | 18 | 657.0 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 999995 | CUST0000999996 | 2025-02-03 12:54:09.482412 | 25 | Male | 21309.78 | college | single | 4 | 5 | one_year | ... | 1 | 1 | 2.0 | 1.0 | 2 | 0 | 7.12 | 14 | 688.0 | 0 |
| 999996 | CUST0000999997 | 2024-09-08 12:54:09.482417 | 22 | Female | 164236.89 | college | married | 1 | 11 | one_year | ... | 0 | 0 | 5.0 | 0.0 | 3 | 0 | 0.00 | 1 | 653.0 | 0 |
| 999997 | CUST0000999998 | 2021-09-13 12:54:09.482423 | 44 | Female | 34258.27 | college | divorced | 1 | 12 | one_year | ... | 0 | 1 | 6.0 | 0.0 | 0 | 0 | 22.43 | 139 | 669.0 | 0 |
| 999998 | CUST0000999999 | 2025-08-30 12:54:09.482428 | 65 | Male | 38687.93 | high_school | single | 0 | 24 | one_year | ... | 1 | 1 | 5.0 | 0.0 | 0 | 0 | 0.00 | 17 | 843.0 | 0 |
| 999999 | CUST0001000000 | 2023-02-14 12:54:09.482434 | 31 | Male | 23617.51 | bachelor | single | 1 | 3 | one_year | ... | 1 | 1 | 7.0 | 0.0 | 1 | 1 | NaN | 85 | 683.0 | 0 |
1000000 rows × 32 columns
In [4]:
df=df.head(100000)
In [5]:
df
Out[5]:
| customer_id | signup_date | age | gender | annual_income | education | marital_status | dependents | tenure | contract | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | churn | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CUST0000000001 | 2022-12-12 12:53:58.199463 | 43 | Female | 55085.25 | college | married | 1 | 2 | two_year | ... | 1 | 1 | 9.0 | 0.0 | 0 | 0 | 109.63 | 16 | NaN | 0 |
| 1 | CUST0000000002 | 2022-01-13 12:53:58.199973 | 18 | Male | 60786.11 | master | married | 1 | 22 | one_year | ... | 0 | 1 | 7.0 | 0.0 | 3 | 1 | 63.25 | 134 | 585.0 | 0 |
| 2 | CUST0000000003 | 2023-09-04 12:53:58.199985 | 38 | Female | 73184.32 | high_school | widowed | 0 | 3 | two_year | ... | 1 | 0 | 6.0 | 1.0 | 1 | 0 | 47.77 | 11 | 632.0 | 0 |
| 3 | CUST0000000004 | 2022-06-27 12:53:58.199992 | 44 | Male | 40923.78 | high_school | married | 1 | 6 | two_year | ... | 0 | 1 | 5.0 | 2.0 | 2 | 1 | 50.82 | 6 | 569.0 | 0 |
| 4 | CUST0000000005 | 2022-12-08 12:53:58.199999 | 45 | Female | 36400.94 | bachelor | single | 0 | 9 | two_year | ... | 0 | 1 | 8.0 | 1.0 | 1 | 0 | 16.74 | 18 | 657.0 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 99995 | CUST0000099996 | 2022-11-07 12:53:58.787477 | 45 | Female | 91253.34 | high_school | married | 3 | 3 | two_year | ... | 1 | 1 | 2.0 | 1.0 | 5 | 2 | 0.00 | 1 | 506.0 | 0 |
| 99996 | CUST0000099997 | 2024-02-18 12:53:58.787482 | 59 | Male | 37801.22 | high_school | married | 1 | 17 | one_year | ... | 1 | 0 | 7.0 | 0.0 | 2 | 0 | 38.36 | 134 | 593.0 | 0 |
| 99997 | CUST0000099998 | 2022-09-15 12:53:58.787488 | 34 | Male | 20000.00 | master | widowed | 0 | 38 | two_year | ... | 1 | 1 | 6.0 | 0.0 | 0 | 0 | 28.63 | 17 | 750.0 | 0 |
| 99998 | CUST0000099999 | 2024-03-12 12:53:58.787493 | 42 | Male | 32374.80 | college | single | 0 | 16 | one_year | ... | 0 | 1 | 3.0 | 0.0 | 1 | 1 | 65.06 | 116 | 668.0 | 0 |
| 99999 | CUST0000100000 | 2024-02-08 12:53:58.787499 | 21 | Female | 64778.76 | high_school | divorced | 4 | 2 | one_year | ... | 0 | 1 | 3.0 | 0.0 | 1 | 0 | 20.18 | 116 | 701.0 | 0 |
100000 rows × 32 columns
In [6]:
print(df.shape)
print("-"*25)
print(df.info())
print("-"*50)
print(df.isnull().sum())
(100000, 32) ------------------------- <class 'pandas.DataFrame'> RangeIndex: 100000 entries, 0 to 99999 Data columns (total 32 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 customer_id 100000 non-null str 1 signup_date 100000 non-null str 2 age 100000 non-null int64 3 gender 100000 non-null str 4 annual_income 97033 non-null float64 5 education 100000 non-null str 6 marital_status 100000 non-null str 7 dependents 100000 non-null int64 8 tenure 100000 non-null int64 9 contract 100000 non-null str 10 payment_method 100000 non-null str 11 paperless_billing 100000 non-null str 12 senior_citizen 100000 non-null int64 13 monthlycharges 100000 non-null float64 14 totalcharges 100000 non-null float64 15 num_services 100000 non-null int64 16 has_phone_service 100000 non-null int64 17 has_internet_service 100000 non-null int64 18 has_online_security 100000 non-null int64 19 has_online_backup 100000 non-null int64 20 has_device_protection 100000 non-null int64 21 has_tech_support 100000 non-null int64 22 has_streaming_tv 100000 non-null int64 23 has_streaming_movies 100000 non-null int64 24 customer_satisfaction 97989 non-null float64 25 num_complaints 97011 non-null float64 26 num_service_calls 100000 non-null int64 27 late_payments 100000 non-null int64 28 avg_monthly_gb 94880 non-null float64 29 days_since_last_interaction 100000 non-null int64 30 credit_score 95845 non-null float64 31 churn 100000 non-null int64 dtypes: float64(7), int64(17), str(8) memory usage: 24.4 MB None -------------------------------------------------- customer_id 0 signup_date 0 age 0 gender 0 annual_income 2967 education 0 marital_status 0 dependents 0 tenure 0 contract 0 payment_method 0 paperless_billing 0 senior_citizen 0 monthlycharges 0 totalcharges 0 num_services 0 has_phone_service 0 has_internet_service 0 has_online_security 0 has_online_backup 0 has_device_protection 0 has_tech_support 0 has_streaming_tv 0 has_streaming_movies 0 customer_satisfaction 2011 num_complaints 2989 num_service_calls 0 late_payments 0 avg_monthly_gb 5120 days_since_last_interaction 0 credit_score 4155 churn 0 dtype: int64
In [7]:
sns.countplot(x=df['churn'])
plt.show()
In [9]:
df['gender'] = df['gender'].astype('object')
df['contract'] = df['contract'].astype('object')
df['payment_method'] = df['payment_method'].astype('object')
In [10]:
df.info()
<class 'pandas.DataFrame'> RangeIndex: 100000 entries, 0 to 99999 Data columns (total 32 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 customer_id 100000 non-null str 1 signup_date 100000 non-null str 2 age 100000 non-null int64 3 gender 100000 non-null object 4 annual_income 97033 non-null float64 5 education 100000 non-null str 6 marital_status 100000 non-null str 7 dependents 100000 non-null int64 8 tenure 100000 non-null int64 9 contract 100000 non-null object 10 payment_method 100000 non-null object 11 paperless_billing 100000 non-null str 12 senior_citizen 100000 non-null int64 13 monthlycharges 100000 non-null float64 14 totalcharges 100000 non-null float64 15 num_services 100000 non-null int64 16 has_phone_service 100000 non-null int64 17 has_internet_service 100000 non-null int64 18 has_online_security 100000 non-null int64 19 has_online_backup 100000 non-null int64 20 has_device_protection 100000 non-null int64 21 has_tech_support 100000 non-null int64 22 has_streaming_tv 100000 non-null int64 23 has_streaming_movies 100000 non-null int64 24 customer_satisfaction 97989 non-null float64 25 num_complaints 97011 non-null float64 26 num_service_calls 100000 non-null int64 27 late_payments 100000 non-null int64 28 avg_monthly_gb 94880 non-null float64 29 days_since_last_interaction 100000 non-null int64 30 credit_score 95845 non-null float64 31 churn 100000 non-null int64 dtypes: float64(7), int64(17), object(3), str(5) memory usage: 24.4+ MB
In [11]:
df.describe()
Out[11]:
| age | annual_income | dependents | tenure | senior_citizen | monthlycharges | totalcharges | num_services | has_phone_service | has_internet_service | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | churn | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| count | 100000.000000 | 97033.000000 | 100000.000000 | 100000.000000 | 100000.000000 | 100000.000000 | 100000.000000 | 100000.000000 | 100000.000000 | 100000.000000 | ... | 100000.00000 | 100000.00000 | 97989.000000 | 97011.000000 | 100000.00000 | 100000.000000 | 94880.000000 | 100000.00000 | 95845.000000 | 100000.000000 |
| mean | 44.756430 | 58738.940294 | 0.802160 | 22.465210 | 0.199300 | 86.378509 | 1842.001322 | 2.563430 | 0.769950 | 0.850510 | ... | 0.60180 | 0.54966 | 6.158957 | 0.703446 | 1.76577 | 0.402130 | 38.986787 | 44.34508 | 679.025364 | 0.099880 |
| std | 14.488547 | 37114.879300 | 0.893816 | 20.045198 | 0.399476 | 27.060082 | 1797.946037 | 1.411509 | 0.420867 | 0.356573 | ... | 0.48953 | 0.49753 | 2.328982 | 0.837808 | 1.48782 | 0.634402 | 43.924345 | 44.83704 | 87.605996 | 0.299841 |
| min | 18.000000 | 20000.000000 | 0.000000 | 1.000000 | 0.000000 | 20.000000 | 20.750000 | 1.000000 | 0.000000 | 0.000000 | ... | 0.00000 | 0.00000 | 1.000000 | 0.000000 | 0.00000 | 0.000000 | 0.000000 | 1.00000 | 300.000000 | 0.000000 |
| 25% | 34.000000 | 32649.470000 | 0.000000 | 7.000000 | 0.000000 | 70.530000 | 493.947500 | 1.000000 | 1.000000 | 1.000000 | ... | 0.00000 | 0.00000 | 4.000000 | 0.000000 | 1.00000 | 0.000000 | 12.890000 | 12.00000 | 620.000000 | 0.000000 |
| 50% | 45.000000 | 48799.610000 | 1.000000 | 16.000000 | 0.000000 | 85.490000 | 1256.550000 | 2.000000 | 1.000000 | 1.000000 | ... | 1.00000 | 1.00000 | 7.000000 | 1.000000 | 1.00000 | 0.000000 | 27.690000 | 30.00000 | 680.000000 | 0.000000 |
| 75% | 55.000000 | 73269.250000 | 1.000000 | 33.000000 | 0.000000 | 100.620000 | 2620.090000 | 3.000000 | 1.000000 | 1.000000 | ... | 1.00000 | 1.00000 | 8.000000 | 1.000000 | 3.00000 | 1.000000 | 50.820000 | 61.00000 | 741.000000 | 0.000000 |
| max | 90.000000 | 250000.000000 | 5.000000 | 72.000000 | 1.000000 | 853.190579 | 12668.100000 | 6.000000 | 1.000000 | 1.000000 | ... | 1.00000 | 1.00000 | 9.000000 | 6.000000 | 12.00000 | 5.000000 | 551.240470 | 365.00000 | 850.000000 | 1.000000 |
8 rows × 24 columns
In [12]:
df.describe(include=object)
C:\Users\MEENAKSHI\AppData\Local\Temp\ipykernel_4052\3998025828.py:1: Pandas4Warning: For backward compatibility, 'str' dtypes are included by select_dtypes when 'object' dtype is specified. This behavior is deprecated and will be removed in a future version. Explicitly pass 'str' to `include` to select them, or to `exclude` to remove them and silence this warning. See https://pandas.pydata.org/docs/user_guide/migration-3-strings.html#string-migration-select-dtypes for details on how to write code that works with pandas 2 and 3. df.describe(include=object)
Out[12]:
| customer_id | signup_date | gender | education | marital_status | contract | payment_method | paperless_billing | |
|---|---|---|---|---|---|---|---|---|
| count | 100000 | 100000 | 100000 | 100000 | 100000 | 100000 | 100000 | 100000 |
| unique | 100000 | 100000 | 3 | 5 | 4 | 3 | 4 | 2 |
| top | CUST0000000001 | 2022-12-12 12:53:58.199463 | Female | bachelor | married | one_year | credit_card | Yes |
| freq | 1 | 1 | 49129 | 30313 | 45122 | 55316 | 34894 | 74805 |
In [13]:
df.head()
Out[13]:
| customer_id | signup_date | age | gender | annual_income | education | marital_status | dependents | tenure | contract | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | churn | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CUST0000000001 | 2022-12-12 12:53:58.199463 | 43 | Female | 55085.25 | college | married | 1 | 2 | two_year | ... | 1 | 1 | 9.0 | 0.0 | 0 | 0 | 109.63 | 16 | NaN | 0 |
| 1 | CUST0000000002 | 2022-01-13 12:53:58.199973 | 18 | Male | 60786.11 | master | married | 1 | 22 | one_year | ... | 0 | 1 | 7.0 | 0.0 | 3 | 1 | 63.25 | 134 | 585.0 | 0 |
| 2 | CUST0000000003 | 2023-09-04 12:53:58.199985 | 38 | Female | 73184.32 | high_school | widowed | 0 | 3 | two_year | ... | 1 | 0 | 6.0 | 1.0 | 1 | 0 | 47.77 | 11 | 632.0 | 0 |
| 3 | CUST0000000004 | 2022-06-27 12:53:58.199992 | 44 | Male | 40923.78 | high_school | married | 1 | 6 | two_year | ... | 0 | 1 | 5.0 | 2.0 | 2 | 1 | 50.82 | 6 | 569.0 | 0 |
| 4 | CUST0000000005 | 2022-12-08 12:53:58.199999 | 45 | Female | 36400.94 | bachelor | single | 0 | 9 | two_year | ... | 0 | 1 | 8.0 | 1.0 | 1 | 0 | 16.74 | 18 | 657.0 | 0 |
5 rows × 32 columns
In [15]:
df_equal = df['monthlycharges'] == df["totalcharges"]
df_equal.value_counts()
Out[15]:
False 99999 True 1 Name: count, dtype: int64
In [17]:
df_false = df[df['totalcharges'] != df['monthlycharges']]
df_false['churn'].value_counts()
Out[17]:
churn 0 90011 1 9988 Name: count, dtype: int64
In [19]:
df.groupby('payment_method')['churn'].value_counts()
Out[19]:
payment_method churn
bank_transfer 0 22626
1 2529
credit_card 0 31484
1 3410
electronic_check 0 22356
1 2567
mailed_check 0 13546
1 1482
Name: count, dtype: int64
In [21]:
df.groupby('contract')['churn'].value_counts()
Out[21]:
contract churn
month_to_month 0 1491
1 514
one_year 0 48324
1 6992
two_year 0 40197
1 2482
Name: count, dtype: int64
In [22]:
df.head()
Out[22]:
| customer_id | signup_date | age | gender | annual_income | education | marital_status | dependents | tenure | contract | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | churn | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CUST0000000001 | 2022-12-12 12:53:58.199463 | 43 | Female | 55085.25 | college | married | 1 | 2 | two_year | ... | 1 | 1 | 9.0 | 0.0 | 0 | 0 | 109.63 | 16 | NaN | 0 |
| 1 | CUST0000000002 | 2022-01-13 12:53:58.199973 | 18 | Male | 60786.11 | master | married | 1 | 22 | one_year | ... | 0 | 1 | 7.0 | 0.0 | 3 | 1 | 63.25 | 134 | 585.0 | 0 |
| 2 | CUST0000000003 | 2023-09-04 12:53:58.199985 | 38 | Female | 73184.32 | high_school | widowed | 0 | 3 | two_year | ... | 1 | 0 | 6.0 | 1.0 | 1 | 0 | 47.77 | 11 | 632.0 | 0 |
| 3 | CUST0000000004 | 2022-06-27 12:53:58.199992 | 44 | Male | 40923.78 | high_school | married | 1 | 6 | two_year | ... | 0 | 1 | 5.0 | 2.0 | 2 | 1 | 50.82 | 6 | 569.0 | 0 |
| 4 | CUST0000000005 | 2022-12-08 12:53:58.199999 | 45 | Female | 36400.94 | bachelor | single | 0 | 9 | two_year | ... | 0 | 1 | 8.0 | 1.0 | 1 | 0 | 16.74 | 18 | 657.0 | 0 |
5 rows × 32 columns
In [25]:
df['signup_date'] = pd.to_datetime(df['signup_date'])
df['customer_age_days'] = (pd.Timestamp.today() - df['signup_date']).dt.days
df.drop(columns=['signup_date'], inplace=True)
In [26]:
from sklearn.preprocessing import StandardScaler,OneHotEncoder,LabelEncoder,OrdinalEncoder
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
In [27]:
x=df.drop('churn',axis=1)
y=df['churn']
In [28]:
x
Out[28]:
| customer_id | age | gender | annual_income | education | marital_status | dependents | tenure | contract | payment_method | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | customer_age_days | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CUST0000000001 | 43 | Female | 55085.25 | college | married | 1 | 2 | two_year | electronic_check | ... | 1 | 1 | 9.0 | 0.0 | 0 | 0 | 109.63 | 16 | NaN | 1209 |
| 1 | CUST0000000002 | 18 | Male | 60786.11 | master | married | 1 | 22 | one_year | bank_transfer | ... | 0 | 1 | 7.0 | 0.0 | 3 | 1 | 63.25 | 134 | 585.0 | 1542 |
| 2 | CUST0000000003 | 38 | Female | 73184.32 | high_school | widowed | 0 | 3 | two_year | credit_card | ... | 1 | 0 | 6.0 | 1.0 | 1 | 0 | 47.77 | 11 | 632.0 | 943 |
| 3 | CUST0000000004 | 44 | Male | 40923.78 | high_school | married | 1 | 6 | two_year | bank_transfer | ... | 0 | 1 | 5.0 | 2.0 | 2 | 1 | 50.82 | 6 | 569.0 | 1377 |
| 4 | CUST0000000005 | 45 | Female | 36400.94 | bachelor | single | 0 | 9 | two_year | credit_card | ... | 0 | 1 | 8.0 | 1.0 | 1 | 0 | 16.74 | 18 | 657.0 | 1213 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 99995 | CUST0000099996 | 45 | Female | 91253.34 | high_school | married | 3 | 3 | two_year | electronic_check | ... | 1 | 1 | 2.0 | 1.0 | 5 | 2 | 0.00 | 1 | 506.0 | 1244 |
| 99996 | CUST0000099997 | 59 | Male | 37801.22 | high_school | married | 1 | 17 | one_year | electronic_check | ... | 1 | 0 | 7.0 | 0.0 | 2 | 0 | 38.36 | 134 | 593.0 | 776 |
| 99997 | CUST0000099998 | 34 | Male | 20000.00 | master | widowed | 0 | 38 | two_year | mailed_check | ... | 1 | 1 | 6.0 | 0.0 | 0 | 0 | 28.63 | 17 | 750.0 | 1297 |
| 99998 | CUST0000099999 | 42 | Male | 32374.80 | college | single | 0 | 16 | one_year | mailed_check | ... | 0 | 1 | 3.0 | 0.0 | 1 | 1 | 65.06 | 116 | 668.0 | 753 |
| 99999 | CUST0000100000 | 21 | Female | 64778.76 | high_school | divorced | 4 | 2 | one_year | bank_transfer | ... | 0 | 1 | 3.0 | 0.0 | 1 | 0 | 20.18 | 116 | 701.0 | 786 |
100000 rows × 31 columns
In [29]:
xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.3,random_state=21)
In [30]:
num_cols = [
'age',
'annual_income',
'dependents',
'tenure',
'monthlycharges',
'totalcharges',
'customer_satisfaction',
'num_complaints',
'num_service_calls',
'late_payments',
'avg_monthly_gb',
'days_since_last_interaction',
'credit_score',
'customer_age_days'
]
In [31]:
cat_cols = [
'gender',
'education',
'marital_status',
'contract',
'payment_method',
'paperless_billing',
'senior_citizen',
'has_phone_service',
'has_internet_service',
'has_online_security',
'has_online_backup',
'has_device_protection',
'has_tech_support',
'has_streaming_tv',
'has_streaming_movies'
]
In [33]:
preprocessor=ColumnTransformer([('Encoding',OneHotEncoder(drop='first',handle_unknown='ignore'),cat_cols),
('Scaling',StandardScaler(),num_cols)],remainder='drop')
In [34]:
preprocessor
Out[34]:
ColumnTransformer(transformers=[('Encoding',
OneHotEncoder(drop='first',
handle_unknown='ignore'),
['gender', 'education', 'marital_status',
'contract', 'payment_method',
'paperless_billing', 'senior_citizen',
'has_phone_service', 'has_internet_service',
'has_online_security', 'has_online_backup',
'has_device_protection', 'has_tech_support',
'has_streaming_tv', 'has_streaming_movies']),
('Scaling', StandardScaler(),
['age', 'annual_income', 'dependents',
'tenure', 'monthlycharges', 'totalcharges',
'customer_satisfaction', 'num_complaints',
'num_service_calls', 'late_payments',
'avg_monthly_gb',
'days_since_last_interaction', 'credit_score',
'customer_age_days'])])In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
['gender', 'education', 'marital_status', 'contract', 'payment_method', 'paperless_billing', 'senior_citizen', 'has_phone_service', 'has_internet_service', 'has_online_security', 'has_online_backup', 'has_device_protection', 'has_tech_support', 'has_streaming_tv', 'has_streaming_movies']
Parameters
['age', 'annual_income', 'dependents', 'tenure', 'monthlycharges', 'totalcharges', 'customer_satisfaction', 'num_complaints', 'num_service_calls', 'late_payments', 'avg_monthly_gb', 'days_since_last_interaction', 'credit_score', 'customer_age_days']
Parameters
In [35]:
X_train=preprocessor.fit_transform(xtrain)
X_test=preprocessor.transform(xtest)
In [36]:
preprocessor.get_feature_names_out()
Out[36]:
array(['Encoding__gender_Male', 'Encoding__gender_Other',
'Encoding__education_college', 'Encoding__education_high_school',
'Encoding__education_master', 'Encoding__education_phd',
'Encoding__marital_status_married',
'Encoding__marital_status_single',
'Encoding__marital_status_widowed', 'Encoding__contract_one_year',
'Encoding__contract_two_year',
'Encoding__payment_method_credit_card',
'Encoding__payment_method_electronic_check',
'Encoding__payment_method_mailed_check',
'Encoding__paperless_billing_Yes', 'Encoding__senior_citizen_1',
'Encoding__has_phone_service_1',
'Encoding__has_internet_service_1',
'Encoding__has_online_security_1', 'Encoding__has_online_backup_1',
'Encoding__has_device_protection_1',
'Encoding__has_tech_support_1', 'Encoding__has_streaming_tv_1',
'Encoding__has_streaming_movies_1', 'Scaling__age',
'Scaling__annual_income', 'Scaling__dependents', 'Scaling__tenure',
'Scaling__monthlycharges', 'Scaling__totalcharges',
'Scaling__customer_satisfaction', 'Scaling__num_complaints',
'Scaling__num_service_calls', 'Scaling__late_payments',
'Scaling__avg_monthly_gb', 'Scaling__days_since_last_interaction',
'Scaling__credit_score', 'Scaling__customer_age_days'],
dtype=object)
In [37]:
X_train.shape,X_test.shape,ytrain.shape,ytest.shape
Out[37]:
((70000, 38), (30000, 38), (70000,), (30000,))
Building the Basics Architecture¶
In [38]:
model=Sequential()
model.add(Input(shape=(X_train.shape[1],)))
model.add(Dense(units=64,activation='relu'))
model.add(Dense(units=32,activation='relu'))
model.add(Dense(units=1,activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
WARNING:tensorflow:TensorFlow GPU support is not available on native Windows for TensorFlow >= 2.11. Even if CUDA/cuDNN are installed, GPU will not be used. Please use WSL2 or the TensorFlow-DirectML plugin.
In [39]:
model.fit(X_train, ytrain,epochs=25,batch_size=256,validation_data=(X_test, ytest))
Epoch 1/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 3s 5ms/step - accuracy: 0.8994 - loss: 0.4856 - val_accuracy: 0.8979 - val_loss: 0.3448 Epoch 2/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3257 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 3/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 4/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3297 Epoch 5/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 6/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3297 Epoch 7/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3297 Epoch 8/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3298 Epoch 9/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 10/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 11/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3297 Epoch 12/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 13/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3301 Epoch 14/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 15/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3297 Epoch 16/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 17/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 18/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 19/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3299 Epoch 20/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 21/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3297 Epoch 22/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 23/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296 Epoch 24/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3298 Epoch 25/25 274/274 ━━━━━━━━━━━━━━━━━━━━ 1s 4ms/step - accuracy: 0.9011 - loss: 0.3228 - val_accuracy: 0.8979 - val_loss: 0.3296
Out[39]:
<keras.src.callbacks.history.History at 0x2d89f332330>
In [40]:
import numpy as np
ypred=np.where(model.predict(X_test)>0.5,1,0)
ypred
938/938 ━━━━━━━━━━━━━━━━━━━━ 2s 2ms/step
Out[40]:
array([[0],
[0],
[0],
...,
[0],
[0],
[0]], shape=(30000, 1))
In [41]:
from sklearn.metrics import accuracy_score,classification_report
print('accuracy',accuracy_score(ytest,ypred))
accuracy 0.8979333333333334
In [42]:
print(classification_report(ytest,ypred))
precision recall f1-score support
0 0.90 1.00 0.95 26938
1 0.00 0.00 0.00 3062
accuracy 0.90 30000
macro avg 0.45 0.50 0.47 30000
weighted avg 0.81 0.90 0.85 30000
C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages\sklearn\metrics\_classification.py:1833: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])
C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages\sklearn\metrics\_classification.py:1833: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])
C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages\sklearn\metrics\_classification.py:1833: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])
In [43]:
sns.lineplot(x=model.history.epoch,y=model.history.history['accuracy'],label='training accuracy')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_accuracy'],label='val_accuracy')
plt.xlabel('Epochs')
plt.ylabel('accuracy')
plt.title('Training and validation Accuracy')
plt.show()
sns.lineplot(x=model.history.epoch,y=model.history.history['loss'],label='training loss')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_loss'],label='val_loss')
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.title('Training and validation loss ')
Out[43]:
Text(0.5, 1.0, 'Training and validation loss ')
Solving the Class Imbalance Issue¶
In [47]:
from sklearn.impute import SimpleImputer
from imblearn.over_sampling import SMOTE
# handle missing values
imputer = SimpleImputer(strategy='median')
X_train = imputer.fit_transform(X_train)
X_test = imputer.transform(X_test)
# apply SMOTE
smote = SMOTE(random_state=42, k_neighbors=1)
X_train_resample, y_train_resample = smote.fit_resample(X_train,ytrain)
In [48]:
X_train_resample.shape
Out[48]:
(126148, 38)
In [49]:
print(ytrain.value_counts())
print(y_train_resample.value_counts())
churn 0 63074 1 6926 Name: count, dtype: int64 churn 0 63074 1 63074 Name: count, dtype: int64
ReBuilding the Model¶
In [50]:
model=Sequential()
model.add(Input(shape=(X_train_resample.shape[1],)))
model.add(Dense(units=128,activation='relu'))
model.add(Dense(units=64,activation='relu'))
model.add(Dense(units=32,activation='relu'))
model.add(Dense(units=1,activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
In [51]:
model.fit(X_train_resample,y_train_resample,epochs=25,batch_size=256,validation_data=(X_test,ytest))
Epoch 1/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 4s 4ms/step - accuracy: 0.6652 - loss: 0.6085 - val_accuracy: 0.7174 - val_loss: 0.5419 Epoch 2/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.7525 - loss: 0.5114 - val_accuracy: 0.6744 - val_loss: 0.6124 Epoch 3/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8104 - loss: 0.4177 - val_accuracy: 0.7690 - val_loss: 0.5018 Epoch 4/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8396 - loss: 0.3635 - val_accuracy: 0.7148 - val_loss: 0.5950 Epoch 5/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8569 - loss: 0.3302 - val_accuracy: 0.7898 - val_loss: 0.5055 Epoch 6/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 5ms/step - accuracy: 0.8674 - loss: 0.3095 - val_accuracy: 0.7413 - val_loss: 0.5708 Epoch 7/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8743 - loss: 0.2941 - val_accuracy: 0.8608 - val_loss: 0.4402 Epoch 8/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 5ms/step - accuracy: 0.8812 - loss: 0.2799 - val_accuracy: 0.7891 - val_loss: 0.5268 Epoch 9/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8876 - loss: 0.2672 - val_accuracy: 0.8205 - val_loss: 0.4907 Epoch 10/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8911 - loss: 0.2591 - val_accuracy: 0.7711 - val_loss: 0.5611 Epoch 11/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8948 - loss: 0.2511 - val_accuracy: 0.7841 - val_loss: 0.5476 Epoch 12/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.8985 - loss: 0.2438 - val_accuracy: 0.7942 - val_loss: 0.5364 Epoch 13/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9019 - loss: 0.2360 - val_accuracy: 0.8430 - val_loss: 0.4915 Epoch 14/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9033 - loss: 0.2326 - val_accuracy: 0.8199 - val_loss: 0.5136 Epoch 15/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9071 - loss: 0.2257 - val_accuracy: 0.8323 - val_loss: 0.5065 Epoch 16/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9079 - loss: 0.2234 - val_accuracy: 0.8323 - val_loss: 0.5029 Epoch 17/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9101 - loss: 0.2178 - val_accuracy: 0.8220 - val_loss: 0.5152 Epoch 18/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9130 - loss: 0.2115 - val_accuracy: 0.8494 - val_loss: 0.4953 Epoch 19/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9136 - loss: 0.2098 - val_accuracy: 0.8292 - val_loss: 0.5192 Epoch 20/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9166 - loss: 0.2049 - val_accuracy: 0.8308 - val_loss: 0.5078 Epoch 21/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9177 - loss: 0.2014 - val_accuracy: 0.8254 - val_loss: 0.5315 Epoch 22/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9197 - loss: 0.1964 - val_accuracy: 0.8263 - val_loss: 0.5252 Epoch 23/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9200 - loss: 0.1945 - val_accuracy: 0.8349 - val_loss: 0.5342 Epoch 24/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9214 - loss: 0.1922 - val_accuracy: 0.7848 - val_loss: 0.5954 Epoch 25/25 493/493 ━━━━━━━━━━━━━━━━━━━━ 2s 4ms/step - accuracy: 0.9233 - loss: 0.1902 - val_accuracy: 0.8102 - val_loss: 0.5671
Out[51]:
<keras.src.callbacks.history.History at 0x2d8a5ebf350>
In [52]:
sns.lineplot(x=model.history.epoch,y=model.history.history['loss'],label='Train loss')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_loss'],label='val loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
sns.lineplot(x=model.history.epoch,y=model.history.history['accuracy'],label='accuracy')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_accuracy'],label='val accuracy')
plt.xlabel('Epoch')
plt.ylabel('accuracy')
plt.legend()
plt.show()
In [53]:
ypred=np.where(model.predict(X_test)>0.5,1,0)
print(classification_report(ytest,ypred))
938/938 ━━━━━━━━━━━━━━━━━━━━ 2s 2ms/step precision recall f1-score support 0 0.90 0.88 0.89 26938 1 0.14 0.17 0.16 3062 accuracy 0.81 30000 macro avg 0.52 0.53 0.53 30000 weighted avg 0.83 0.81 0.82 30000
In [54]:
from sklearn.metrics import f1_score
print('accuracy_score',f1_score(ytest,ypred))
accuracy_score 0.15721687638786083
Reducing the overfitting issue with Dropout and Batch Normalization and regulaizer¶
In [55]:
from tensorflow.keras.layers import Dropout, BatchNormalization
from tensorflow.keras.regularizers import L1,L2
from tensorflow.keras.initializers import HeNormal
l1=L1(l1=0.01)
model = Sequential()
model.add(Input(shape=(X_train.shape[1],)))
model.add(Dense(64, activation='relu',kernel_regularizer=l1,kernel_initializer=HeNormal()))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(32, activation='relu',kernel_regularizer=l1,kernel_initializer=HeNormal()))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(16, activation='relu',kernel_regularizer=l1,kernel_initializer=HeNormal()))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
In [56]:
model.fit(X_train_resample, y_train_resample, epochs=15,batch_size=512, validation_split=0.2)
Epoch 1/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 5s 8ms/step - accuracy: 0.5685 - loss: 5.9438 - val_accuracy: 0.2688 - val_loss: 3.3154 Epoch 2/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 2s 6ms/step - accuracy: 0.6202 - loss: 1.9668 - val_accuracy: 0.0000e+00 - val_loss: 1.3078 Epoch 3/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 7ms/step - accuracy: 0.6486 - loss: 0.8508 - val_accuracy: 0.0000e+00 - val_loss: 1.0416 Epoch 4/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6600 - loss: 0.6707 - val_accuracy: 0.0000e+00 - val_loss: 1.0624 Epoch 5/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6662 - loss: 0.6419 - val_accuracy: 0.0880 - val_loss: 0.9318 Epoch 6/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6671 - loss: 0.6424 - val_accuracy: 0.1581 - val_loss: 0.9726 Epoch 7/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6687 - loss: 0.6422 - val_accuracy: 0.4174 - val_loss: 0.9351 Epoch 8/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6697 - loss: 0.6392 - val_accuracy: 0.2256 - val_loss: 1.0326 Epoch 9/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6706 - loss: 0.6359 - val_accuracy: 0.4595 - val_loss: 0.8759 Epoch 10/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6719 - loss: 0.6343 - val_accuracy: 0.4239 - val_loss: 0.8633 Epoch 11/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6731 - loss: 0.6334 - val_accuracy: 0.4226 - val_loss: 0.8580 Epoch 12/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6753 - loss: 0.6326 - val_accuracy: 0.3136 - val_loss: 0.9154 Epoch 13/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6749 - loss: 0.6328 - val_accuracy: 0.6062 - val_loss: 0.7712 Epoch 14/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6743 - loss: 0.6313 - val_accuracy: 0.4716 - val_loss: 0.8558 Epoch 15/15 198/198 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.6742 - loss: 0.6335 - val_accuracy: 0.5352 - val_loss: 0.7994
Out[56]:
<keras.src.callbacks.history.History at 0x2d8a635e5d0>
In [57]:
ypred=np.where(model.predict(X_test)>0.5,1,0)
print(classification_report(ytest,ypred))
938/938 ━━━━━━━━━━━━━━━━━━━━ 2s 2ms/step precision recall f1-score support 0 0.92 0.81 0.86 26938 1 0.18 0.36 0.24 3062 accuracy 0.77 30000 macro avg 0.55 0.58 0.55 30000 weighted avg 0.84 0.77 0.80 30000
In [58]:
print('f1 score',f1_score(ytest,ypred))
f1 score 0.23778962253888827
In [59]:
sns.lineplot(x=model.history.epoch,y=model.history.history['loss'],label='Train loss')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_loss'],label='test loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
sns.lineplot(x=model.history.epoch,y=model.history.history['accuracy'],label='accuracy')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_accuracy'],label='val accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
Out[59]:
<matplotlib.legend.Legend at 0x2d8a6531850>
In [60]:
1e-4,1e-2
Out[60]:
(0.0001, 0.01)
In [61]:
from tensorflow.keras.regularizers import L1
from tensorflow.keras.optimizers import Adam,RMSprop
def objective(trail):
n_layers=trail.suggest_int('n_layers',1,6)
lr=trail.suggest_float('lr',1e-4,1e-2,log=True)
drop_out=trail.suggest_float('drop out',0.3,0.5)
activation=trail.suggest_categorical('activation',['tanh','relu'])
optimizer=trail.suggest_categorical('optimizer',['adam','rmsprop'])
l1=trail.suggest_float('l1',1e-4,1e-2,log=True)
l2=trail.suggest_float('l2',1e-4,1e-2,log=True)
model=Sequential()
model.add(Input(shape=(X_train_resample.shape[1],)))
for i in range(n_layers):
units=trail.suggest_int(f'units{i}',16,128)
model.add(Dense(units,activation=activation,kernel_regularizer=L1(l1=l1)))
model.add(Dropout(drop_out))
model.add(BatchNormalization())
model.add(Dense(1,activation='sigmoid'))
if optimizer=='adam':
optimizer=Adam(learning_rate=lr)
else:
optimizer=RMSprop(learning_rate=lr)
model.compile(optimizer=optimizer,loss='binary_crossentropy',metrics=['accuracy',Recall(name='recall')])
early_stopping=EarlyStopping(monitor='val_recall',min_delta=0.01,patience=3,restore_best_weights=True)
history=model.fit(X_train_resample,y_train_resample,epochs=25,callbacks=[early_stopping],validation_data=(X_test,ytest))
best_recall = np.max(history.history['val_recall'])
return best_recall
In [62]:
study=optuna.create_study(direction='maximize')
study.optimize(objective,n_trials=10)
[I 2026-04-05 11:20:56,171] A new study created in memory with name: no-name-023f79e0-e6bb-41df-8a79-04b32b4ad885
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 16s 3ms/step - accuracy: 0.6036 - loss: 0.7097 - recall: 0.6103 - val_accuracy: 0.5917 - val_loss: 0.6883 - val_recall: 0.6381 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 13s 3ms/step - accuracy: 0.6256 - loss: 0.6707 - recall: 0.6406 - val_accuracy: 0.6043 - val_loss: 0.6746 - val_recall: 0.6323 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 13s 3ms/step - accuracy: 0.6323 - loss: 0.6594 - recall: 0.6526 - val_accuracy: 0.6181 - val_loss: 0.6531 - val_recall: 0.6097 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 13s 3ms/step - accuracy: 0.6336 - loss: 0.6537 - recall: 0.6560 - val_accuracy: 0.6105 - val_loss: 0.6574 - val_recall: 0.6316
[I 2026-04-05 11:21:51,758] Trial 0 finished with value: 0.6381450295448303 and parameters: {'n_layers': 1, 'lr': 0.00024925812364811164, 'drop out': 0.363533862352017, 'activation': 'tanh', 'optimizer': 'adam', 'l1': 0.00010373387484084169, 'l2': 0.0002429505503255903, 'units0': 83}. Best is trial 0 with value: 0.6381450295448303.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 18s 4ms/step - accuracy: 0.6109 - loss: 1.2098 - recall: 0.6662 - val_accuracy: 0.5495 - val_loss: 0.7834 - val_recall: 0.6773 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 15s 4ms/step - accuracy: 0.6494 - loss: 0.7077 - recall: 0.7121 - val_accuracy: 0.5793 - val_loss: 0.7066 - val_recall: 0.6391 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 16s 4ms/step - accuracy: 0.6667 - loss: 0.6678 - recall: 0.7098 - val_accuracy: 0.7026 - val_loss: 0.6100 - val_recall: 0.4442 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 16s 4ms/step - accuracy: 0.6774 - loss: 0.6543 - recall: 0.7069 - val_accuracy: 0.6367 - val_loss: 0.6768 - val_recall: 0.5578
[I 2026-04-05 11:22:56,987] Trial 1 finished with value: 0.6773350834846497 and parameters: {'n_layers': 2, 'lr': 0.0004381173111144612, 'drop out': 0.4373836783342483, 'activation': 'relu', 'optimizer': 'adam', 'l1': 0.0010358748790941761, 'l2': 0.0003685645936554366, 'units0': 122, 'units1': 80}. Best is trial 1 with value: 0.6773350834846497.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 32s 6ms/step - accuracy: 0.5851 - loss: 1.6024 - recall: 0.5878 - val_accuracy: 0.4850 - val_loss: 1.0540 - val_recall: 0.7590 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.5965 - loss: 0.9462 - recall: 0.6011 - val_accuracy: 0.5868 - val_loss: 0.8741 - val_recall: 0.6528 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 26s 7ms/step - accuracy: 0.5996 - loss: 0.9177 - recall: 0.6006 - val_accuracy: 0.5527 - val_loss: 0.9498 - val_recall: 0.6878 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 26s 7ms/step - accuracy: 0.5997 - loss: 0.8960 - recall: 0.6049 - val_accuracy: 0.6081 - val_loss: 0.8363 - val_recall: 0.6231
[I 2026-04-05 11:24:45,953] Trial 2 finished with value: 0.7589810490608215 and parameters: {'n_layers': 6, 'lr': 0.0014162404070855164, 'drop out': 0.4922530311811385, 'activation': 'tanh', 'optimizer': 'adam', 'l1': 0.004314335519470455, 'l2': 0.00036402310121456775, 'units0': 50, 'units1': 99, 'units2': 43, 'units3': 35, 'units4': 63, 'units5': 124}. Best is trial 2 with value: 0.7589810490608215.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 26s 6ms/step - accuracy: 0.6163 - loss: 0.8131 - recall: 0.6466 - val_accuracy: 0.5422 - val_loss: 0.7377 - val_recall: 0.6992 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 21s 5ms/step - accuracy: 0.6284 - loss: 0.6936 - recall: 0.6729 - val_accuracy: 0.5748 - val_loss: 0.6932 - val_recall: 0.6705 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 21s 5ms/step - accuracy: 0.6288 - loss: 0.6864 - recall: 0.6737 - val_accuracy: 0.5531 - val_loss: 0.7431 - val_recall: 0.6914 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 21s 5ms/step - accuracy: 0.6292 - loss: 0.6819 - recall: 0.6771 - val_accuracy: 0.6510 - val_loss: 0.6255 - val_recall: 0.5699
[I 2026-04-05 11:26:16,876] Trial 3 finished with value: 0.6992161870002747 and parameters: {'n_layers': 4, 'lr': 0.0015827442326291272, 'drop out': 0.39536245727410485, 'activation': 'tanh', 'optimizer': 'rmsprop', 'l1': 0.00023382491917646312, 'l2': 0.000248258653177642, 'units0': 103, 'units1': 89, 'units2': 36, 'units3': 125}. Best is trial 2 with value: 0.7589810490608215.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 19s 4ms/step - accuracy: 0.5964 - loss: 0.9385 - recall: 0.7142 - val_accuracy: 0.5219 - val_loss: 0.8886 - val_recall: 0.6884 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 17s 4ms/step - accuracy: 0.5970 - loss: 0.8734 - recall: 0.7308 - val_accuracy: 0.3625 - val_loss: 0.9466 - val_recall: 0.8651 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 17s 4ms/step - accuracy: 0.5923 - loss: 0.8657 - recall: 0.7570 - val_accuracy: 0.5154 - val_loss: 0.8588 - val_recall: 0.7234 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 17s 4ms/step - accuracy: 0.6000 - loss: 0.8676 - recall: 0.7598 - val_accuracy: 0.4731 - val_loss: 0.8771 - val_recall: 0.7802 Epoch 5/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 17s 4ms/step - accuracy: 0.5941 - loss: 0.8650 - recall: 0.7807 - val_accuracy: 0.4144 - val_loss: 0.9028 - val_recall: 0.8396
[I 2026-04-05 11:27:43,410] Trial 4 finished with value: 0.8651208281517029 and parameters: {'n_layers': 2, 'lr': 0.008085390304850648, 'drop out': 0.3653085271714668, 'activation': 'relu', 'optimizer': 'rmsprop', 'l1': 0.00415227046537162, 'l2': 0.00013441909953509446, 'units0': 74, 'units1': 104}. Best is trial 4 with value: 0.8651208281517029.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 31s 6ms/step - accuracy: 0.6134 - loss: 0.7526 - recall: 0.6760 - val_accuracy: 0.5859 - val_loss: 0.6791 - val_recall: 0.6453 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6235 - loss: 0.7000 - recall: 0.7036 - val_accuracy: 0.5107 - val_loss: 0.7156 - val_recall: 0.7306 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6254 - loss: 0.6912 - recall: 0.7054 - val_accuracy: 0.5649 - val_loss: 0.7024 - val_recall: 0.6799 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6252 - loss: 0.6874 - recall: 0.6975 - val_accuracy: 0.5334 - val_loss: 0.6611 - val_recall: 0.7185 Epoch 5/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 41s 6ms/step - accuracy: 0.6250 - loss: 0.6842 - recall: 0.7010 - val_accuracy: 0.4759 - val_loss: 0.7575 - val_recall: 0.7822 Epoch 6/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6260 - loss: 0.6822 - recall: 0.7013 - val_accuracy: 0.5772 - val_loss: 0.6733 - val_recall: 0.6604 Epoch 7/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6252 - loss: 0.6813 - recall: 0.7068 - val_accuracy: 0.5039 - val_loss: 0.6771 - val_recall: 0.7502 Epoch 8/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 41s 6ms/step - accuracy: 0.6247 - loss: 0.6802 - recall: 0.7036 - val_accuracy: 0.5515 - val_loss: 0.7147 - val_recall: 0.6927
[I 2026-04-05 11:31:41,006] Trial 5 finished with value: 0.7821685075759888 and parameters: {'n_layers': 6, 'lr': 0.0038268662535708192, 'drop out': 0.335647100842247, 'activation': 'tanh', 'optimizer': 'rmsprop', 'l1': 0.00013170991383602967, 'l2': 0.005564931052846427, 'units0': 54, 'units1': 21, 'units2': 92, 'units3': 122, 'units4': 22, 'units5': 100}. Best is trial 4 with value: 0.8651208281517029.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 26s 6ms/step - accuracy: 0.5997 - loss: 0.8856 - recall: 0.6833 - val_accuracy: 0.5287 - val_loss: 0.7308 - val_recall: 0.7129 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 22s 6ms/step - accuracy: 0.6239 - loss: 0.7193 - recall: 0.7135 - val_accuracy: 0.5015 - val_loss: 0.7338 - val_recall: 0.7394 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 22s 5ms/step - accuracy: 0.6279 - loss: 0.7071 - recall: 0.7251 - val_accuracy: 0.5818 - val_loss: 0.7195 - val_recall: 0.6336 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 22s 5ms/step - accuracy: 0.6300 - loss: 0.7005 - recall: 0.7237 - val_accuracy: 0.5129 - val_loss: 0.6991 - val_recall: 0.7299 Epoch 5/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 21s 5ms/step - accuracy: 0.6279 - loss: 0.6993 - recall: 0.7276 - val_accuracy: 0.5239 - val_loss: 0.6987 - val_recall: 0.7159
[I 2026-04-05 11:33:33,929] Trial 6 finished with value: 0.7393860220909119 and parameters: {'n_layers': 5, 'lr': 0.002081596252972431, 'drop out': 0.4213452877869199, 'activation': 'relu', 'optimizer': 'rmsprop', 'l1': 0.0008040497184532041, 'l2': 0.0002716227211312773, 'units0': 57, 'units1': 20, 'units2': 108, 'units3': 27, 'units4': 75}. Best is trial 4 with value: 0.8651208281517029.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 31s 7ms/step - accuracy: 0.6068 - loss: 0.9156 - recall: 0.6362 - val_accuracy: 0.6047 - val_loss: 0.7566 - val_recall: 0.6385 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6198 - loss: 0.7775 - recall: 0.6601 - val_accuracy: 0.6155 - val_loss: 0.7272 - val_recall: 0.5996 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6191 - loss: 0.7627 - recall: 0.6645 - val_accuracy: 0.5146 - val_loss: 0.7976 - val_recall: 0.7384 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 41s 6ms/step - accuracy: 0.6183 - loss: 0.7519 - recall: 0.6712 - val_accuracy: 0.6099 - val_loss: 0.7040 - val_recall: 0.6280 Epoch 5/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6209 - loss: 0.7441 - recall: 0.6755 - val_accuracy: 0.5392 - val_loss: 0.7870 - val_recall: 0.7084 Epoch 6/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6206 - loss: 0.7415 - recall: 0.6753 - val_accuracy: 0.5296 - val_loss: 0.7653 - val_recall: 0.7211
[I 2026-04-05 11:36:27,463] Trial 7 finished with value: 0.738406240940094 and parameters: {'n_layers': 6, 'lr': 0.0025523251058889728, 'drop out': 0.49467415327021397, 'activation': 'tanh', 'optimizer': 'rmsprop', 'l1': 0.0003383020237624977, 'l2': 0.00028907373286359624, 'units0': 113, 'units1': 120, 'units2': 51, 'units3': 54, 'units4': 77, 'units5': 36}. Best is trial 4 with value: 0.8651208281517029.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 16s 4ms/step - accuracy: 0.5834 - loss: 0.7522 - recall: 0.6093 - val_accuracy: 0.5712 - val_loss: 0.6979 - val_recall: 0.6587 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 14s 4ms/step - accuracy: 0.6244 - loss: 0.6794 - recall: 0.6958 - val_accuracy: 0.5732 - val_loss: 0.6667 - val_recall: 0.6675 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 14s 4ms/step - accuracy: 0.6321 - loss: 0.6616 - recall: 0.7042 - val_accuracy: 0.5738 - val_loss: 0.6577 - val_recall: 0.6796 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 14s 4ms/step - accuracy: 0.6386 - loss: 0.6511 - recall: 0.7185 - val_accuracy: 0.5908 - val_loss: 0.6410 - val_recall: 0.6568 Epoch 5/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 15s 4ms/step - accuracy: 0.6418 - loss: 0.6471 - recall: 0.7287 - val_accuracy: 0.5956 - val_loss: 0.6396 - val_recall: 0.6434 Epoch 6/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 16s 4ms/step - accuracy: 0.6434 - loss: 0.6452 - recall: 0.7243 - val_accuracy: 0.5781 - val_loss: 0.6480 - val_recall: 0.6633
[I 2026-04-05 11:37:56,714] Trial 8 finished with value: 0.679621160030365 and parameters: {'n_layers': 1, 'lr': 0.00030812463713808503, 'drop out': 0.4705437629445469, 'activation': 'relu', 'optimizer': 'rmsprop', 'l1': 0.0005681617234272564, 'l2': 0.0013106299727863337, 'units0': 22}. Best is trial 4 with value: 0.8651208281517029.
Epoch 1/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 31s 6ms/step - accuracy: 0.5125 - loss: 1.0011 - recall: 0.5150 - val_accuracy: 0.5862 - val_loss: 0.9006 - val_recall: 0.6094 Epoch 2/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 24s 6ms/step - accuracy: 0.5843 - loss: 0.8598 - recall: 0.5914 - val_accuracy: 0.5863 - val_loss: 0.8078 - val_recall: 0.6378 Epoch 3/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 25s 6ms/step - accuracy: 0.6178 - loss: 0.7590 - recall: 0.6512 - val_accuracy: 0.5704 - val_loss: 0.7348 - val_recall: 0.6620 Epoch 4/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 24s 6ms/step - accuracy: 0.6241 - loss: 0.7102 - recall: 0.6695 - val_accuracy: 0.5723 - val_loss: 0.7035 - val_recall: 0.6653 Epoch 5/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 24s 6ms/step - accuracy: 0.6265 - loss: 0.6889 - recall: 0.6705 - val_accuracy: 0.5845 - val_loss: 0.6794 - val_recall: 0.6538 Epoch 6/25 3943/3943 ━━━━━━━━━━━━━━━━━━━━ 24s 6ms/step - accuracy: 0.6286 - loss: 0.6774 - recall: 0.6649 - val_accuracy: 0.5927 - val_loss: 0.6715 - val_recall: 0.6466
[I 2026-04-05 11:40:28,775] Trial 9 finished with value: 0.6652514934539795 and parameters: {'n_layers': 6, 'lr': 0.000239658152155267, 'drop out': 0.44944526045578465, 'activation': 'tanh', 'optimizer': 'rmsprop', 'l1': 0.00021095707371031295, 'l2': 0.002675051230064157, 'units0': 20, 'units1': 42, 'units2': 16, 'units3': 31, 'units4': 89, 'units5': 80}. Best is trial 4 with value: 0.8651208281517029.
In [63]:
print("Best Recall:", study.best_value)
print("Best Parameters:", study.best_params)
Best Recall: 0.8651208281517029
Best Parameters: {'n_layers': 2, 'lr': 0.008085390304850648, 'drop out': 0.3653085271714668, 'activation': 'relu', 'optimizer': 'rmsprop', 'l1': 0.00415227046537162, 'l2': 0.00013441909953509446, 'units0': 74, 'units1': 104}
In [64]:
from tensorflow.keras.optimizers import Adam,RMSprop
best_params = study.best_params
n_layers = best_params['n_layers']
lr = best_params['lr']
dropout = best_params['drop out']
l1 = best_params['l1']
l2 = best_params['l2']
optimizer_name = best_params['optimizer']
activation = best_params['activation']
if optimizer_name == 'rmsprop':
optimizer = RMSprop(learning_rate=lr)
else:
optimizer = Adam(learning_rate=lr)
model = Sequential()
model.add(Input(shape=(X_train_resample.shape[1],)))
for i in range(n_layers):
units = best_params[f'units{i}']
model.add(Dense(units,activation=activation,kernel_regularizer=l1_l2(l1=l1, l2=l2)))
model.add(Dropout(dropout))
model.add(BatchNormalization())
early_stopping=EarlyStopping(monitor='val_recall',patience=6,restore_best_weights=True,min_delta=0.01)
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer=optimizer,
loss='binary_crossentropy',
metrics=['accuracy',Recall(name='recall')])
history = model.fit( X_train_resample, y_train_resample, batch_size=64, epochs=10,callbacks=[early_stopping],validation_data=(X_test, ytest))
Epoch 1/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 11s 4ms/step - accuracy: 0.6027 - loss: 0.9458 - recall: 0.7148 - val_accuracy: 0.3765 - val_loss: 0.9528 - val_recall: 0.8658 Epoch 2/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.6055 - loss: 0.8641 - recall: 0.7625 - val_accuracy: 0.4076 - val_loss: 0.9094 - val_recall: 0.8165 Epoch 3/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.6069 - loss: 0.8625 - recall: 0.7737 - val_accuracy: 0.4669 - val_loss: 0.9042 - val_recall: 0.7652 Epoch 4/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.6079 - loss: 0.8637 - recall: 0.7571 - val_accuracy: 0.4824 - val_loss: 0.8781 - val_recall: 0.7737 Epoch 5/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.6083 - loss: 0.8646 - recall: 0.7534 - val_accuracy: 0.7697 - val_loss: 0.7262 - val_recall: 0.3625 Epoch 6/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 9s 4ms/step - accuracy: 0.6062 - loss: 0.8610 - recall: 0.7738 - val_accuracy: 0.6365 - val_loss: 0.8085 - val_recall: 0.5467 Epoch 7/10 1972/1972 ━━━━━━━━━━━━━━━━━━━━ 8s 4ms/step - accuracy: 0.6074 - loss: 0.8607 - recall: 0.7634 - val_accuracy: 0.5422 - val_loss: 0.8304 - val_recall: 0.6969
In [65]:
model.summary()
Model: "sequential_13"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩ │ dense_60 (Dense) │ (None, 74) │ 2,886 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ dropout_42 (Dropout) │ (None, 74) │ 0 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ batch_normalization_42 │ (None, 74) │ 296 │ │ (BatchNormalization) │ │ │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ dense_61 (Dense) │ (None, 104) │ 7,800 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ dropout_43 (Dropout) │ (None, 104) │ 0 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ batch_normalization_43 │ (None, 104) │ 416 │ │ (BatchNormalization) │ │ │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ dense_62 (Dense) │ (None, 1) │ 105 │ └──────────────────────────────────────┴─────────────────────────────┴─────────────────┘
Total params: 22,652 (88.49 KB)
Trainable params: 11,147 (43.54 KB)
Non-trainable params: 356 (1.39 KB)
Optimizer params: 11,149 (43.55 KB)
In [66]:
y_prob = model.predict(X_test)
threshold = 0.5
y_pred = (y_prob > threshold).astype(int)
938/938 ━━━━━━━━━━━━━━━━━━━━ 2s 2ms/step
In [67]:
from sklearn.metrics import recall_score
print(recall_score(ytest,y_pred))
0.8657740039190072
In [68]:
sns.lineplot(x=model.history.epoch,y=model.history.history['recall'],label='recall')
sns.lineplot(x=model.history.epoch,y=model.history.history['val_recall'],label='val recall')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
Out[68]:
<matplotlib.legend.Legend at 0x2d8bc6a16d0>
In [70]:
import pickle
with open(r"C:\ANN Project Work\preprocessor.pkl",'wb')as f:
pickle.dump(preprocessor,f)
In [71]:
model.save(r"C:\ANN Project Work\ann_model.keras")
In [72]:
import sklearn
print(sklearn.__version__)
1.8.0
In [73]:
import tensorflow
print(tensorflow.__version__)
2.21.0
In [74]:
np.__version__
Out[74]:
'2.4.3'
In [75]:
!python --version
Python 3.12.13
In [76]:
pd.__version__
Out[76]:
'3.0.1'
In [77]:
import imblearn
imblearn.__version__
Out[77]:
'0.14.1'
In [79]:
pip install streamlit
Collecting streamlit Downloading streamlit-1.56.0-py3-none-any.whl.metadata (9.8 kB) Collecting altair!=5.4.0,!=5.4.1,<7,>=4.0 (from streamlit) Downloading altair-6.0.0-py3-none-any.whl.metadata (11 kB) Collecting blinker<2,>=1.5.0 (from streamlit) Downloading blinker-1.9.0-py3-none-any.whl.metadata (1.6 kB) Collecting cachetools<8,>=5.5 (from streamlit) Downloading cachetools-7.0.5-py3-none-any.whl.metadata (5.6 kB) Collecting click<9,>=7.0 (from streamlit) Downloading click-8.3.2-py3-none-any.whl.metadata (2.6 kB) Collecting gitpython!=3.1.19,<4,>=3.0.7 (from streamlit) Downloading gitpython-3.1.46-py3-none-any.whl.metadata (13 kB) Requirement already satisfied: numpy<3,>=1.23 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (2.4.3) Requirement already satisfied: packaging>=20 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (25.0) Requirement already satisfied: pandas<4,>=1.4.0 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (3.0.1) Requirement already satisfied: pillow<13,>=7.1.0 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (12.1.1) Collecting pydeck<1,>=0.8.0b4 (from streamlit) Downloading pydeck-0.9.1-py2.py3-none-any.whl.metadata (4.1 kB) Requirement already satisfied: protobuf<8,>=3.20 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (7.34.1) Collecting pyarrow>=7.0 (from streamlit) Downloading pyarrow-23.0.1-cp312-cp312-win_amd64.whl.metadata (3.1 kB) Requirement already satisfied: requests<3,>=2.27 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (2.32.5) Collecting tenacity<10,>=8.1.0 (from streamlit) Downloading tenacity-9.1.4-py3-none-any.whl.metadata (1.2 kB) Collecting toml<2,>=0.10.1 (from streamlit) Downloading toml-0.10.2-py2.py3-none-any.whl.metadata (7.1 kB) Requirement already satisfied: tornado!=6.5.0,<7,>=6.0.3 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (6.5.5) Requirement already satisfied: typing-extensions<5,>=4.10.0 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from streamlit) (4.15.0) Collecting watchdog<7,>=2.1.5 (from streamlit) Downloading watchdog-6.0.0-py3-none-win_amd64.whl.metadata (44 kB) Requirement already satisfied: jinja2 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (3.1.6) Requirement already satisfied: jsonschema>=3.0 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (4.25.1) Collecting narwhals>=1.27.1 (from altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) Downloading narwhals-2.18.1-py3-none-any.whl.metadata (14 kB) Requirement already satisfied: colorama in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from click<9,>=7.0->streamlit) (0.4.6) Collecting gitdb<5,>=4.0.1 (from gitpython!=3.1.19,<4,>=3.0.7->streamlit) Downloading gitdb-4.0.12-py3-none-any.whl.metadata (1.2 kB) Collecting smmap<6,>=3.0.1 (from gitdb<5,>=4.0.1->gitpython!=3.1.19,<4,>=3.0.7->streamlit) Downloading smmap-5.0.3-py3-none-any.whl.metadata (4.6 kB) Requirement already satisfied: python-dateutil>=2.8.2 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from pandas<4,>=1.4.0->streamlit) (2.9.0.post0) Requirement already satisfied: tzdata in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from pandas<4,>=1.4.0->streamlit) (2025.3) Requirement already satisfied: charset_normalizer<4,>=2 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from requests<3,>=2.27->streamlit) (3.4.4) Requirement already satisfied: idna<4,>=2.5 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from requests<3,>=2.27->streamlit) (3.11) Requirement already satisfied: urllib3<3,>=1.21.1 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from requests<3,>=2.27->streamlit) (2.6.3) Requirement already satisfied: certifi>=2017.4.17 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from requests<3,>=2.27->streamlit) (2026.1.4) Requirement already satisfied: MarkupSafe>=2.0 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from jinja2->altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (3.0.2) Requirement already satisfied: attrs>=22.2.0 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from jsonschema>=3.0->altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (25.4.0) Requirement already satisfied: jsonschema-specifications>=2023.03.6 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from jsonschema>=3.0->altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (2025.9.1) Requirement already satisfied: referencing>=0.28.4 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from jsonschema>=3.0->altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (0.37.0) Requirement already satisfied: rpds-py>=0.7.1 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from jsonschema>=3.0->altair!=5.4.0,!=5.4.1,<7,>=4.0->streamlit) (0.28.0) Requirement already satisfied: six>=1.5 in C:\Users\MEENAKSHI\.conda\envs\Meenu\Lib\site-packages (from python-dateutil>=2.8.2->pandas<4,>=1.4.0->streamlit) (1.17.0) Downloading streamlit-1.56.0-py3-none-any.whl (9.1 MB) ---------------------------------------- 0.0/9.1 MB ? eta -:--:-- ---------------------------------------- 0.0/9.1 MB ? eta -:--:-- - -------------------------------------- 0.3/9.1 MB ? eta -:--:-- -- ------------------------------------- 0.5/9.1 MB 1.1 MB/s eta 0:00:08 --- ------------------------------------ 0.8/9.1 MB 905.5 kB/s eta 0:00:10 ---- ----------------------------------- 1.0/9.1 MB 967.3 kB/s eta 0:00:09 ---- ----------------------------------- 1.0/9.1 MB 967.3 kB/s eta 0:00:09 ----- ---------------------------------- 1.3/9.1 MB 1.0 MB/s eta 0:00:08 ------ --------------------------------- 1.6/9.1 MB 986.2 kB/s eta 0:00:08 -------- ------------------------------- 1.8/9.1 MB 1.0 MB/s eta 0:00:08 --------- ------------------------------ 2.1/9.1 MB 1.0 MB/s eta 0:00:07 ---------- ----------------------------- 2.4/9.1 MB 1.1 MB/s eta 0:00:07 ----------- ---------------------------- 2.6/9.1 MB 1.1 MB/s eta 0:00:06 ------------ --------------------------- 2.9/9.1 MB 1.1 MB/s eta 0:00:06 ------------- -------------------------- 3.1/9.1 MB 1.1 MB/s eta 0:00:06 ------------- -------------------------- 3.1/9.1 MB 1.1 MB/s eta 0:00:06 --------------- ------------------------ 3.4/9.1 MB 1.0 MB/s eta 0:00:06 --------------- ------------------------ 3.4/9.1 MB 1.0 MB/s eta 0:00:06 ---------------- ----------------------- 3.7/9.1 MB 995.9 kB/s eta 0:00:06 ----------------- ---------------------- 3.9/9.1 MB 1.0 MB/s eta 0:00:05 ------------------- -------------------- 4.5/9.1 MB 1.1 MB/s eta 0:00:05 -------------------- ------------------- 4.7/9.1 MB 1.1 MB/s eta 0:00:05 ---------------------- ----------------- 5.0/9.1 MB 1.1 MB/s eta 0:00:04 ----------------------- ---------------- 5.2/9.1 MB 1.1 MB/s eta 0:00:04 ------------------------- -------------- 5.8/9.1 MB 1.2 MB/s eta 0:00:03 -------------------------- ------------- 6.0/9.1 MB 1.2 MB/s eta 0:00:03 --------------------------- ------------ 6.3/9.1 MB 1.2 MB/s eta 0:00:03 ---------------------------- ----------- 6.6/9.1 MB 1.2 MB/s eta 0:00:03 ------------------------------ --------- 6.8/9.1 MB 1.2 MB/s eta 0:00:02 ------------------------------- -------- 7.1/9.1 MB 1.2 MB/s eta 0:00:02 -------------------------------- ------- 7.3/9.1 MB 1.2 MB/s eta 0:00:02 --------------------------------- ------ 7.6/9.1 MB 1.2 MB/s eta 0:00:02 ---------------------------------- ----- 7.9/9.1 MB 1.2 MB/s eta 0:00:01 ----------------------------------- ---- 8.1/9.1 MB 1.2 MB/s eta 0:00:01 ------------------------------------- -- 8.4/9.1 MB 1.2 MB/s eta 0:00:01 -------------------------------------- - 8.7/9.1 MB 1.2 MB/s eta 0:00:01 -------------------------------------- - 8.7/9.1 MB 1.2 MB/s eta 0:00:01 --------------------------------------- 8.9/9.1 MB 1.2 MB/s eta 0:00:01 ---------------------------------------- 9.1/9.1 MB 1.1 MB/s 0:00:07 Downloading altair-6.0.0-py3-none-any.whl (795 kB) ---------------------------------------- 0.0/795.4 kB ? eta -:--:-- ---------------------------------------- 0.0/795.4 kB ? eta -:--:-- ------------- -------------------------- 262.1/795.4 kB ? eta -:--:-- --------------------------------------- 786.4/795.4 kB 1.5 MB/s eta 0:00:01 ---------------------------------------- 795.4/795.4 kB 1.2 MB/s 0:00:00 Downloading blinker-1.9.0-py3-none-any.whl (8.5 kB) Downloading cachetools-7.0.5-py3-none-any.whl (13 kB) Downloading click-8.3.2-py3-none-any.whl (108 kB) Downloading gitpython-3.1.46-py3-none-any.whl (208 kB) Downloading gitdb-4.0.12-py3-none-any.whl (62 kB) Downloading pydeck-0.9.1-py2.py3-none-any.whl (6.9 MB) ---------------------------------------- 0.0/6.9 MB ? eta -:--:-- ---------------------------------------- 0.0/6.9 MB ? eta -:--:-- - -------------------------------------- 0.3/6.9 MB ? eta -:--:-- - -------------------------------------- 0.3/6.9 MB ? eta -:--:-- --- ------------------------------------ 0.5/6.9 MB 699.0 kB/s eta 0:00:10 ------ --------------------------------- 1.0/6.9 MB 1.0 MB/s eta 0:00:06 ------- -------------------------------- 1.3/6.9 MB 1.2 MB/s eta 0:00:05 --------- ------------------------------ 1.6/6.9 MB 1.1 MB/s eta 0:00:05 ---------- ----------------------------- 1.8/6.9 MB 1.2 MB/s eta 0:00:05 ------------ --------------------------- 2.1/6.9 MB 1.3 MB/s eta 0:00:04 --------------- ------------------------ 2.6/6.9 MB 1.3 MB/s eta 0:00:04 ---------------- ----------------------- 2.9/6.9 MB 1.4 MB/s eta 0:00:03 ------------------ --------------------- 3.1/6.9 MB 1.4 MB/s eta 0:00:03 ------------------- -------------------- 3.4/6.9 MB 1.4 MB/s eta 0:00:03 ---------------------- ----------------- 3.9/6.9 MB 1.4 MB/s eta 0:00:03 ------------------------ --------------- 4.2/6.9 MB 1.4 MB/s eta 0:00:02 ------------------------- -------------- 4.5/6.9 MB 1.4 MB/s eta 0:00:02 --------------------------- ------------ 4.7/6.9 MB 1.4 MB/s eta 0:00:02 ------------------------------ --------- 5.2/6.9 MB 1.4 MB/s eta 0:00:02 ------------------------------- -------- 5.5/6.9 MB 1.4 MB/s eta 0:00:01 --------------------------------- ------ 5.8/6.9 MB 1.4 MB/s eta 0:00:01 ---------------------------------- ----- 6.0/6.9 MB 1.5 MB/s eta 0:00:01 ------------------------------------- -- 6.6/6.9 MB 1.5 MB/s eta 0:00:01 --------------------------------------- 6.8/6.9 MB 1.5 MB/s eta 0:00:01 ---------------------------------------- 6.9/6.9 MB 1.4 MB/s 0:00:04 Downloading smmap-5.0.3-py3-none-any.whl (24 kB) Downloading tenacity-9.1.4-py3-none-any.whl (28 kB) Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB) Downloading watchdog-6.0.0-py3-none-win_amd64.whl (79 kB) Downloading narwhals-2.18.1-py3-none-any.whl (444 kB) Downloading pyarrow-23.0.1-cp312-cp312-win_amd64.whl (27.6 MB) ---------------------------------------- 0.0/27.6 MB ? eta -:--:-- ---------------------------------------- 0.3/27.6 MB ? eta -:--:-- ---------------------------------------- 0.3/27.6 MB ? eta -:--:-- - -------------------------------------- 0.8/27.6 MB 1.5 MB/s eta 0:00:19 - -------------------------------------- 1.0/27.6 MB 1.3 MB/s eta 0:00:21 - -------------------------------------- 1.3/27.6 MB 1.4 MB/s eta 0:00:19 -- ------------------------------------- 1.6/27.6 MB 1.4 MB/s eta 0:00:19 --- ------------------------------------ 2.1/27.6 MB 1.5 MB/s eta 0:00:18 --- ------------------------------------ 2.4/27.6 MB 1.4 MB/s eta 0:00:18 --- ------------------------------------ 2.4/27.6 MB 1.4 MB/s eta 0:00:18 ---- ----------------------------------- 2.9/27.6 MB 1.4 MB/s eta 0:00:18 ---- ----------------------------------- 3.1/27.6 MB 1.4 MB/s eta 0:00:18 ---- ----------------------------------- 3.4/27.6 MB 1.4 MB/s eta 0:00:17 ----- ---------------------------------- 3.7/27.6 MB 1.4 MB/s eta 0:00:17 ------ --------------------------------- 4.2/27.6 MB 1.4 MB/s eta 0:00:17 ------ --------------------------------- 4.5/27.6 MB 1.4 MB/s eta 0:00:17 ------ --------------------------------- 4.7/27.6 MB 1.4 MB/s eta 0:00:16 ------- -------------------------------- 5.2/27.6 MB 1.5 MB/s eta 0:00:16 ------- -------------------------------- 5.5/27.6 MB 1.5 MB/s eta 0:00:16 -------- ------------------------------- 5.8/27.6 MB 1.5 MB/s eta 0:00:15 -------- ------------------------------- 6.0/27.6 MB 1.5 MB/s eta 0:00:15 --------- ------------------------------ 6.6/27.6 MB 1.5 MB/s eta 0:00:14 --------- ------------------------------ 6.8/27.6 MB 1.5 MB/s eta 0:00:14 ---------- ----------------------------- 7.3/27.6 MB 1.5 MB/s eta 0:00:14 ----------- ---------------------------- 7.6/27.6 MB 1.6 MB/s eta 0:00:13 ----------- ---------------------------- 8.1/27.6 MB 1.6 MB/s eta 0:00:13 ------------ --------------------------- 8.4/27.6 MB 1.6 MB/s eta 0:00:13 ------------ --------------------------- 8.9/27.6 MB 1.6 MB/s eta 0:00:12 ------------- -------------------------- 9.2/27.6 MB 1.6 MB/s eta 0:00:12 ------------- -------------------------- 9.4/27.6 MB 1.6 MB/s eta 0:00:12 -------------- ------------------------- 10.0/27.6 MB 1.6 MB/s eta 0:00:11 -------------- ------------------------- 10.2/27.6 MB 1.6 MB/s eta 0:00:11 --------------- ------------------------ 10.7/27.6 MB 1.6 MB/s eta 0:00:11 ---------------- ----------------------- 11.3/27.6 MB 1.6 MB/s eta 0:00:10 ---------------- ----------------------- 11.5/27.6 MB 1.7 MB/s eta 0:00:10 ----------------- ---------------------- 11.8/27.6 MB 1.7 MB/s eta 0:00:10 ----------------- ---------------------- 12.3/27.6 MB 1.7 MB/s eta 0:00:10 ------------------ --------------------- 12.8/27.6 MB 1.7 MB/s eta 0:00:09 ------------------ --------------------- 13.1/27.6 MB 1.7 MB/s eta 0:00:09 ------------------- -------------------- 13.6/27.6 MB 1.7 MB/s eta 0:00:09 -------------------- ------------------- 14.2/27.6 MB 1.7 MB/s eta 0:00:08 -------------------- ------------------- 14.4/27.6 MB 1.7 MB/s eta 0:00:08 --------------------- ------------------ 14.9/27.6 MB 1.7 MB/s eta 0:00:08 ---------------------- ----------------- 15.2/27.6 MB 1.7 MB/s eta 0:00:08 ---------------------- ----------------- 15.7/27.6 MB 1.7 MB/s eta 0:00:07 ----------------------- ---------------- 16.0/27.6 MB 1.7 MB/s eta 0:00:07 ----------------------- ---------------- 16.5/27.6 MB 1.7 MB/s eta 0:00:07 ------------------------ --------------- 16.8/27.6 MB 1.7 MB/s eta 0:00:07 ------------------------ --------------- 17.0/27.6 MB 1.7 MB/s eta 0:00:07 ------------------------- -------------- 17.6/27.6 MB 1.7 MB/s eta 0:00:06 ------------------------- -------------- 17.8/27.6 MB 1.7 MB/s eta 0:00:06 -------------------------- ------------- 18.4/27.6 MB 1.7 MB/s eta 0:00:06 -------------------------- ------------- 18.6/27.6 MB 1.7 MB/s eta 0:00:06 --------------------------- ------------ 19.1/27.6 MB 1.7 MB/s eta 0:00:05 ---------------------------- ----------- 19.4/27.6 MB 1.7 MB/s eta 0:00:05 ---------------------------- ----------- 19.9/27.6 MB 1.8 MB/s eta 0:00:05 ----------------------------- ---------- 20.4/27.6 MB 1.8 MB/s eta 0:00:05 ----------------------------- ---------- 20.7/27.6 MB 1.8 MB/s eta 0:00:04 ------------------------------ --------- 21.2/27.6 MB 1.8 MB/s eta 0:00:04 ------------------------------- -------- 21.8/27.6 MB 1.8 MB/s eta 0:00:04 ------------------------------- -------- 22.0/27.6 MB 1.8 MB/s eta 0:00:04 -------------------------------- ------- 22.5/27.6 MB 1.8 MB/s eta 0:00:03 --------------------------------- ------ 22.8/27.6 MB 1.8 MB/s eta 0:00:03 --------------------------------- ------ 23.3/27.6 MB 1.8 MB/s eta 0:00:03 ---------------------------------- ----- 23.9/27.6 MB 1.8 MB/s eta 0:00:03 ---------------------------------- ----- 24.1/27.6 MB 1.8 MB/s eta 0:00:02 ----------------------------------- ---- 24.6/27.6 MB 1.8 MB/s eta 0:00:02 ------------------------------------ --- 24.9/27.6 MB 1.8 MB/s eta 0:00:02 ------------------------------------ --- 25.4/27.6 MB 1.8 MB/s eta 0:00:02 ------------------------------------- -- 25.7/27.6 MB 1.8 MB/s eta 0:00:02 ------------------------------------- -- 26.2/27.6 MB 1.8 MB/s eta 0:00:01 -------------------------------------- - 26.5/27.6 MB 1.8 MB/s eta 0:00:01 --------------------------------------- 27.0/27.6 MB 1.8 MB/s eta 0:00:01 --------------------------------------- 27.5/27.6 MB 1.8 MB/s eta 0:00:01 ---------------------------------------- 27.6/27.6 MB 1.8 MB/s 0:00:15 Installing collected packages: watchdog, toml, tenacity, smmap, pyarrow, narwhals, click, cachetools, blinker, pydeck, gitdb, gitpython, altair, streamlit ---------------------------------------- 0/14 [watchdog] ----- ---------------------------------- 2/14 [tenacity] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] ----------- ---------------------------- 4/14 [pyarrow] -------------- ------------------------- 5/14 [narwhals] -------------- ------------------------- 5/14 [narwhals] -------------- ------------------------- 5/14 [narwhals] -------------- ------------------------- 5/14 [narwhals] -------------- ------------------------- 5/14 [narwhals] -------------- ------------------------- 5/14 [narwhals] -------------- ------------------------- 5/14 [narwhals] ----------------- ---------------------- 6/14 [click] ----------------- ---------------------- 6/14 [click] ------------------------- -------------- 9/14 [pydeck] ------------------------- -------------- 9/14 [pydeck] ------------------------- -------------- 9/14 [pydeck] ---------------------------- ----------- 10/14 [gitdb] ------------------------------- -------- 11/14 [gitpython] ------------------------------- -------- 11/14 [gitpython] ---------------------------------- ----- 12/14 [altair] ---------------------------------- ----- 12/14 [altair] ---------------------------------- ----- 12/14 [altair] ---------------------------------- ----- 12/14 [altair] ---------------------------------- ----- 12/14 [altair] ---------------------------------- ----- 12/14 [altair] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ------------------------------------- -- 13/14 [streamlit] ---------------------------------------- 14/14 [streamlit] Successfully installed altair-6.0.0 blinker-1.9.0 cachetools-7.0.5 click-8.3.2 gitdb-4.0.12 gitpython-3.1.46 narwhals-2.18.1 pyarrow-23.0.1 pydeck-0.9.1 smmap-5.0.3 streamlit-1.56.0 tenacity-9.1.4 toml-0.10.2 watchdog-6.0.0 Note: you may need to restart the kernel to use updated packages.
In [80]:
import streamlit
streamlit.__version__
Out[80]:
'1.56.0'
In [81]:
x
Out[81]:
| customer_id | age | gender | annual_income | education | marital_status | dependents | tenure | contract | payment_method | ... | has_streaming_tv | has_streaming_movies | customer_satisfaction | num_complaints | num_service_calls | late_payments | avg_monthly_gb | days_since_last_interaction | credit_score | customer_age_days | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | CUST0000000001 | 43 | Female | 55085.25 | college | married | 1 | 2 | two_year | electronic_check | ... | 1 | 1 | 9.0 | 0.0 | 0 | 0 | 109.63 | 16 | NaN | 1209 |
| 1 | CUST0000000002 | 18 | Male | 60786.11 | master | married | 1 | 22 | one_year | bank_transfer | ... | 0 | 1 | 7.0 | 0.0 | 3 | 1 | 63.25 | 134 | 585.0 | 1542 |
| 2 | CUST0000000003 | 38 | Female | 73184.32 | high_school | widowed | 0 | 3 | two_year | credit_card | ... | 1 | 0 | 6.0 | 1.0 | 1 | 0 | 47.77 | 11 | 632.0 | 943 |
| 3 | CUST0000000004 | 44 | Male | 40923.78 | high_school | married | 1 | 6 | two_year | bank_transfer | ... | 0 | 1 | 5.0 | 2.0 | 2 | 1 | 50.82 | 6 | 569.0 | 1377 |
| 4 | CUST0000000005 | 45 | Female | 36400.94 | bachelor | single | 0 | 9 | two_year | credit_card | ... | 0 | 1 | 8.0 | 1.0 | 1 | 0 | 16.74 | 18 | 657.0 | 1213 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 99995 | CUST0000099996 | 45 | Female | 91253.34 | high_school | married | 3 | 3 | two_year | electronic_check | ... | 1 | 1 | 2.0 | 1.0 | 5 | 2 | 0.00 | 1 | 506.0 | 1244 |
| 99996 | CUST0000099997 | 59 | Male | 37801.22 | high_school | married | 1 | 17 | one_year | electronic_check | ... | 1 | 0 | 7.0 | 0.0 | 2 | 0 | 38.36 | 134 | 593.0 | 776 |
| 99997 | CUST0000099998 | 34 | Male | 20000.00 | master | widowed | 0 | 38 | two_year | mailed_check | ... | 1 | 1 | 6.0 | 0.0 | 0 | 0 | 28.63 | 17 | 750.0 | 1297 |
| 99998 | CUST0000099999 | 42 | Male | 32374.80 | college | single | 0 | 16 | one_year | mailed_check | ... | 0 | 1 | 3.0 | 0.0 | 1 | 1 | 65.06 | 116 | 668.0 | 753 |
| 99999 | CUST0000100000 | 21 | Female | 64778.76 | high_school | divorced | 4 | 2 | one_year | bank_transfer | ... | 0 | 1 | 3.0 | 0.0 | 1 | 0 | 20.18 | 116 | 701.0 | 786 |
100000 rows × 31 columns
In [82]:
x.info()
<class 'pandas.DataFrame'> RangeIndex: 100000 entries, 0 to 99999 Data columns (total 31 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 customer_id 100000 non-null str 1 age 100000 non-null int64 2 gender 100000 non-null object 3 annual_income 97033 non-null float64 4 education 100000 non-null str 5 marital_status 100000 non-null str 6 dependents 100000 non-null int64 7 tenure 100000 non-null int64 8 contract 100000 non-null object 9 payment_method 100000 non-null object 10 paperless_billing 100000 non-null str 11 senior_citizen 100000 non-null int64 12 monthlycharges 100000 non-null float64 13 totalcharges 100000 non-null float64 14 num_services 100000 non-null int64 15 has_phone_service 100000 non-null int64 16 has_internet_service 100000 non-null int64 17 has_online_security 100000 non-null int64 18 has_online_backup 100000 non-null int64 19 has_device_protection 100000 non-null int64 20 has_tech_support 100000 non-null int64 21 has_streaming_tv 100000 non-null int64 22 has_streaming_movies 100000 non-null int64 23 customer_satisfaction 97989 non-null float64 24 num_complaints 97011 non-null float64 25 num_service_calls 100000 non-null int64 26 late_payments 100000 non-null int64 27 avg_monthly_gb 94880 non-null float64 28 days_since_last_interaction 100000 non-null int64 29 credit_score 95845 non-null float64 30 customer_age_days 100000 non-null int64 dtypes: float64(7), int64(17), object(3), str(4) memory usage: 23.7+ MB
In [ ]: