import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix
from sklearn.cluster import KMeans
from scipy.stats import ttest_ind
Map encoded values back to original text for Payment Method
payment_method_mapping = dict(zip(label_encoders['Payment Method'].classes_, range(len(label_encoders['Payment Method'].classes_))))
reverse_payment_method_mapping = {v: k for k, v in payment_method_mapping.items()}
Convert the code so that it uses plotly instead of matplotlib.
Remove all existing comments and replace them with multiple-line comments giving extremely detailed explanation of what each code does - use semi-formal tone.
python
"""
This script performs data preprocessing, exploratory data analysis, and visualization on the Telco Customer Churn dataset.
It begins by importing necessary libraries for data manipulation, visualization, and machine learning. The dataset is loaded,
and basic information is displayed to understand its structure and contents. Missing values are identified and handled
appropriately by dropping irrelevant columns and imputing missing 'Total Charges' with the median value. Categorical features
are encoded using Label Encoding to convert them into numerical representations suitable for machine learning algorithms.
Numerical features are standardized using StandardScaler to ensure they have a mean of zero and a standard deviation of one,
facilitating better model performance.
Subsequently, various visualizations are created using Plotly to provide interactive and insightful representations of the data.
These visualizations include the distribution of customer churn, a correlation heatmap to identify relationships between features,
and analyses of churn rates based on payment methods, gender, and contract types. Additionally, a box plot is generated to
examine the distribution of monthly charges in relation to churn status. Each visualization assists in uncovering patterns
and trends that are critical for understanding customer behavior and informing predictive modeling efforts.
"""
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix
from sklearn.cluster import KMeans
from scipy.stats import ttest_ind
# Load the dataset and display initial information
file_path = "Telco_customer_churn.csv"
df = pd.read_csv(file_path)
"""
The dataset's structure and initial records are displayed to provide a comprehensive overview.
This includes the data types of each column and the first few rows to ensure that the data has been loaded correctly.
"""
print("Dataset Overview:")
print(df.info())
print(df.head())
"""
Missing values within the dataset are identified to assess the need for data cleaning. Understanding the extent of missing data
is crucial for determining appropriate imputation or removal strategies to maintain data integrity.
"""
print("Missing values:", df.isnull().sum())
"""
Unnecessary columns that do not contribute to the analysis or may introduce noise are removed. This step streamlines the dataset
by eliminating irrelevant features, thereby enhancing the efficiency of subsequent data processing and modeling tasks.
"""
df.drop(['CustomerID', 'Lat Long', 'Latitude', 'Longitude', 'Zip Code'], axis=1, inplace=True)
"""
The 'Total Charges' column contains missing values, which are addressed by converting the column to a numeric data type.
Any non-numeric entries are coerced to NaN, and missing values are subsequently filled with the median value of the column.
This imputation method preserves the central tendency of the data without being skewed by outliers.
"""
df['Total Charges'] = pd.to_numeric(df['Total Charges'], errors='coerce')
df['Total Charges'].fillna(df['Total Charges'].median(), inplace=True)
"""
Categorical features within the dataset are identified and encoded using Label Encoding. This transformation converts
categorical text data into numerical form, enabling the application of machine learning algorithms that require numerical input.
A dictionary of LabelEncoders is maintained for potential inverse transformations or future reference.
"""
categorical_cols = df.select_dtypes(include=['object']).columns
label_encoders = {}
for col in categorical_cols:
label_encoders[col] = LabelEncoder()
df[col] = label_encoders[col].fit_transform(df[col])
"""
Numerical features are standardized to have a mean of zero and a standard deviation of one using StandardScaler.
Standardization ensures that each feature contributes equally to the analysis, preventing features with larger scales
from dominating those with smaller scales during model training.
"""
scaler = StandardScaler()
df[['Monthly Charges', 'Total Charges', 'Tenure Months']] = scaler.fit_transform(
df[['Monthly Charges', 'Total Charges', 'Tenure Months']]
)
"""
An interactive bar chart is created to visualize the distribution of customer churn within the dataset.
This visualization highlights the proportion of customers who have churned versus those who have not, providing a clear
understanding of the churn rate.
"""
churn_distribution = df['Churn Label'].value_counts().reset_index()
churn_distribution.columns = ['Churn Label', 'Count']
churn_distribution['Churn Label'] = churn_distribution['Churn Label'].map({0: 'No Churn', 1: 'Churn'})
fig = px.bar(churn_distribution, x='Churn Label', y='Count',
title="Churn Distribution",
labels={'Churn Label': 'Churn Status', 'Count': 'Number of Customers'},
color='Churn Label')
fig.show()
"""
A correlation matrix is computed to identify the relationships between different numerical features in the dataset.
An interactive heatmap is then generated to visualize these correlations, with color intensity indicating the strength
and direction of each relationship. This analysis aids in feature selection and understanding potential multicollinearity.
"""
corr_matrix = df.corr()
fig = px.imshow(corr_matrix,
title="Feature Correlation Heatmap",
labels=dict(color="Correlation"),
x=corr_matrix.columns,
y=corr_matrix.columns,
color_continuous_scale="RdBu",
zmin=-1, zmax=1)
fig.update_layout(width=800, height=700)
fig.show()
"""
The 'Payment Method' feature is decoded back to its original categorical labels to facilitate meaningful analysis.
An interactive stacked bar chart is created to examine the relationship between different payment methods and churn rates.
This visualization reveals which payment methods are associated with higher or lower churn rates, providing insights for targeted strategies.
"""
payment_method_mapping = dict(zip(label_encoders['Payment Method'].classes_, range(len(label_encoders['Payment Method'].classes_))))
reverse_payment_method_mapping = {v: k for k, v in payment_method_mapping.items()}
df['Payment Method Text'] = df['Payment Method'].map(reverse_payment_method_mapping)
churn_payment = df.groupby(['Payment Method Text', 'Churn Label']).size().reset_index(name='Count')
churn_payment['Churn Label'] = churn_payment['Churn Label'].map({0: 'No Churn', 1: 'Churn'})
fig = px.bar(churn_payment, x='Payment Method Text', y='Count', color='Churn Label',
title="Churn by Payment Method",
labels={'Payment Method Text': 'Payment Method', 'Count': 'Number of Customers'},
barmode='group')
fig.show()
"""
An interactive bar chart is generated to display churn rates segmented by gender. This visualization helps in understanding
if there is a significant difference in churn behavior between different gender groups, which can inform personalized retention efforts.
"""
gender_churn = df.groupby(['Gender', 'Churn Label']).size().reset_index(name='Count')
gender_churn['Churn Label'] = gender_churn['Churn Label'].map({0: 'No Churn', 1: 'Churn'})
fig = px.bar(gender_churn, x='Gender', y='Count', color='Churn Label',
title='Churn by Gender',
labels={'Gender': 'Gender', 'Count': 'Number of Customers'},
barmode='group')
fig.show()
"""
A comparative analysis of churn rates across different contract types is conducted using an interactive bar chart.
This visualization highlights which types of contracts are more prone to churn, enabling the identification of specific contract
features that may influence customer retention.
"""
contract_churn = df.groupby(['Contract', 'Churn Label']).size().reset_index(name='Count')
contract_churn['Churn Label'] = contract_churn['Churn Label'].map({0: 'No Churn', 1: 'Churn'})
fig = px.bar(contract_churn, x='Contract', y='Count', color='Churn Label',
title='Churn by Contract Type',
labels={'Contract': 'Contract Type', 'Count': 'Number of Customers'},
barmode='group')
fig.show()
"""
An interactive box plot is created to examine the distribution of monthly charges in relation to churn status.
This visualization identifies any significant differences in billing amounts between customers who have churned and those who have not,
potentially uncovering cost-related factors influencing churn.
"""
fig = px.box(df, x='Churn Label', y='Monthly Charges',
title='Monthly Charges vs Churn',
labels={'Churn Label': 'Churn Status', 'Monthly Charges': 'Monthly Charges'},
points='all')
fig.update_xaxes(tickvals=[0, 1], ticktext=['No Churn', 'Churn'])
fig.show()