<jupyter_start><jupyter_text>Factors for customers leaving<jupyter_code>tenure_churn_no = df3[df3.Churn== 'No'].tenure
tenure_churn_yes = df3[df3.Churn== 'Yes'].tenure

plt.xlabel('Tenure (in months)')
plt.ylabel('Number of customers')
plt.title('Customer churn visualization based on tenure')
plt.hist([tenure_churn_yes,tenure_churn_no], color = ['green','red'],label = ['Leaving','Not leaving'])
plt.legend()
# Newer customers tend to leave
MonthlyCharges_churn_no = df3[df3.Churn== 'No'].MonthlyCharges
MonthlyCharges_churn_yes = df3[df3.Churn== 'Yes'].MonthlyCharges

plt.xlabel('Monthly Charges')
plt.ylabel('Number of customers')
plt.title('Customer churn visualization based on Monthly Charges')
plt.hist([MonthlyCharges_churn_yes,MonthlyCharges_churn_no], color = ['green','red'],label = ['Leaving','Not leaving'])
plt.legend()
# Mid to high end range customers tend to have a higher leaving rate
TotalCharges_churn_no = df3[df3.Churn== 'No'].TotalCharges
TotalCharges_churn_yes = df3[df3.Churn== 'Yes'].TotalCharges

plt.xlabel('Total Charges')
plt.ylabel('Number of customers')
plt.title('Customer churn visualization based on Total Charges')
plt.hist([TotalCharges_churn_yes,TotalCharges_churn_no], color = ['green','red'],label = ['Leaving','Not leaving'])
plt.legend()
# Higher the total charge, lower the leaving rate of customers
# Finding unique values for each columns
for column in df3.columns:
    print(f'{column} : {df3[column].unique()}')
# Replacing redundant values (eg- No internet service as No)
df3.replace('No internet service','No',inplace = True)
df3.replace('No phone service','No',inplace = True)
yes_no_cols = ['Partner','PaperlessBilling','PhoneService','Dependents','MultipleLines','OnlineSecurity',
               'OnlineBackup','DeviceProtection','TechSupport','StreamingTV','StreamingMovies','Churn']
for col in yes_no_cols:
    df3[col].replace('Yes',1,inplace = True)
    df3[col].replace('No',0,inplace = True)
df3.replace('Female',1,inplace = True) # Encoding Male/Female
df3.replace('Male',0,inplace = True)
for column in df3.columns:
    print(f'{column} : {df3[column].unique()}')
df4 = pd.get_dummies(data = df3, columns = ['InternetService','Contract','PaymentMethod'])
df4.columns
df4.head()
df4.dtypes<jupyter_output><empty_output><jupyter_text>Scaling the data<jupyter_code>from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
col_to_scale = ['tenure','MonthlyCharges','TotalCharges']
df4[col_to_scale] = scaler.fit_transform(df4[col_to_scale])
for column in df4.columns:
    print(f'{column} : {df4[column].unique()}')
x = df4.drop('Churn',axis = 1)
y = df4['Churn']
from sklearn.model_selection import train_test_split
x_train,x_test, y_train,y_test = train_test_split(x,y,test_size = 0.2)
len(x_train)
x_train.shape
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential([
    keras.layers.Dense(200, input_shape=(26,), activation='relu'),
    keras.layers.Dense(200, activation='relu'),
    keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer = 'adam',
             loss = 'binary_crossentropy',
             metrics = ['accuracy'])
model.fit(x_train, y_train, epochs = 10)
model.evaluate(x_test,y_test)
y_pred  = model.predict(x_test)
y_pred
pred = []
for i in y_pred:
    if i > 0.5:
        pred.append(1)
    else:
        pred.append(0)
pred[:10]
y_test[:10]
from sklearn.metrics import confusion_matrix , classification_report
print(classification_report(y_test,pred))
cm = tf.math.confusion_matrix(labels = y_test, predictions = pred)
cm
import seaborn as sns
plt.figure(figsize = (10,7))
sns.heatmap(cm, annot = True, fmt = 'd')
plt.xlabel('Predicted')
plt.ylabel('Truth')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1487248322147651, 'fraction_numerical': 0.01664429530201342, 'mean_word_length': 6.5425101214574894, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '345276', 'license': 'Apache-2.0', 'n_tokens_mistral': 1375, 'n_tokens_neox': 1310, 'n_words': 264, 'path': 'Prediction of customer retention - Deep learning- TensorFlow.ipynb', 'repo_name': 'Code-SameerKhan/Jupyter_Notebooks', 'size': '3725'}