<jupyter_start><jupyter_text>**Predict Customer Conversion (Churn) with Machine Learning** Importing necessary libraries<jupyter_code>import numpy as np
import pandas as pd
import sklearn
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split<jupyter_output><empty_output><jupyter_text>Reading and exploring the dataset<jupyter_code>df = pd.read_csv("customer-churn-dataset.csv")
df
df.shape
df.columns.values<jupyter_output><empty_output><jupyter_text>To check for missing values or (NA)<jupyter_code>df.isna().sum()<jupyter_output><empty_output><jupyter_text>Dataset Statistics<jupyter_code>df.describe()
df['Churn'].value_counts()<jupyter_output><empty_output><jupyter_text>Visualizing the conversion<jupyter_code>sns.countplot(df['Churn'])<jupyter_output>/usr/local/lib/python3.7/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
  FutureWarning<jupyter_text>Percentage-wise results<jupyter_code>numRetained = df[df.Churn == 'No'].shape[0]
numChurned = df[df.Churn == 'Yes'].shape[0]

# print the percentage of customers that stayed
print(numRetained/(numRetained + numChurned) * 100,'% of customers stayed with the company')
# peint the percentage of customers that left
print(numChurned/(numRetained + numChurned) * 100, '% of customers left the company')<jupyter_output>73.4630129206304 % of customers stayed with the company
26.536987079369588 % of customers left the company<jupyter_text>Gender-wise visualization of customer conversion<jupyter_code>sns.countplot(x ='gender', hue='Churn', data=df)<jupyter_output><empty_output><jupyter_text>Visualization of customer conversion for the internet service<jupyter_code>sns.countplot(x='InternetService', hue='Churn', data=df)<jupyter_output><empty_output><jupyter_text>Visualization of Numerical data<jupyter_code>numericFeatures = ['tenure', 'MonthlyCharges']
fig, ax = plt.subplots(1,2, figsize=(28, 8))
df[df.Churn == "No"][numericFeatures].hist(bins=20, color='blue', alpha=0.5, ax=ax)
df[df.Churn == "Yes"][numericFeatures].hist(bins=20, color='orange', alpha=0.5, ax=ax)<jupyter_output><empty_output><jupyter_text>Dropping unnecessary columns from the dataset<jupyter_code>cleanDF = df.drop('customerID', axis=1)
# Convert all the non-numeric columns to numeric
for column in cleanDF.columns:
  if cleanDF[column].dtype == np.number:
    continue
  cleanDF[column] = LabelEncoder().fit_transform(cleanDF[column])
cleanDF.dtypes<jupyter_output><empty_output><jupyter_text>Scaling of data<jupyter_code>x = cleanDF.drop('Churn', axis=1)
y = cleanDF['Churn']
x = StandardScaler().fit_transform(x)<jupyter_output><empty_output><jupyter_text>Split the data into 80% for training and 20% for testing<jupyter_code>xtrain, xtest, ytrain, ytest = train_test_split(x,y, test_size=0.2, random_state=42)<jupyter_output><empty_output><jupyter_text>Creating and Training the Logistic Regression Model<jupyter_code>model = LogisticRegression()
# Train the model
model.fit(xtrain, ytrain)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
                   intercept_scaling=1, l1_ratio=None, max_iter=100,
                   multi_class='auto', n_jobs=None, penalty='l2',
                   random_state=None, solver='lbfgs', tol=0.0001, verbose=0,
                   warm_start=False)<jupyter_output><empty_output><jupyter_text>Creating predictions on the Test data<jupyter_code>predictions = model.predict(xtest)

# print the predictions
print(predictions)<jupyter_output>[1 0 0 ... 0 0 0]<jupyter_text>Final scores - precision, recall and f1-score<jupyter_code>print(classification_report(ytest, predictions))<jupyter_output>precision    recall  f1-score   support

           0       0.85      0.91      0.88      1036
           1       0.69      0.56      0.62       373

    accuracy                           0.82      1409
   macro avg       0.77      0.74      0.75      1409
weighted avg       0.81      0.82      0.81      1409
{'fraction_non_alphanumeric': 0.10635390571623776, 'fraction_numerical': 0.03461626053290822, 'mean_word_length': 5.574850299401198, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '587189', 'license': 'CC0-1.0', 'n_tokens_mistral': 1543, 'n_tokens_neox': 1441, 'n_words': 312, 'path': 'customer-conversion-prediction/customer_conversion_prediction.ipynb', 'repo_name': 'rajgmishra/machine-learning-datasets', 'size': '4391'}