================================================================================
EXPERIMENT 4: DATA EXPLORATION, CLEANING, PREPROCESSING & VISUALISATION
================================================================================

--------------------------------------------------------------------------------
1. DATA EXPLORATION CODE (data_exploration.py)
--------------------------------------------------------------------------------
import os, pandas as pd
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH)

print("Shape:", df.shape)
print("Data Types:\n", df.dtypes)
print("Describe:\n", df.describe().round(2))
print("Missing Values:\n", df.isnull().sum()[df.isnull().sum() > 0])
print("Duplicates Count:", df.duplicated().sum())
print("Value Counts:\n", df["Contract_Type"].value_counts())

--------------------------------------------------------------------------------
2. DATA CLEANING CODE (data_cleaning.py)
--------------------------------------------------------------------------------
import os, pandas as pd, numpy as np
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH)

# Drop duplicates
df = df.drop_duplicates()

# Impute missing values (Numerical: Median, Categorical: Mode)
num_cols = list(df.select_dtypes(include=[np.number]).columns)
cat_cols = [c for c in df.columns if c not in num_cols]
for col in num_cols: df[col] = df[col].fillna(df[col].median())
for col in cat_cols: df[col] = df[col].fillna(df[col].mode()[0])

# IQR Outlier Capping
for col in num_cols:
    if "id" in col.lower(): continue
    q1, q3 = df[col].quantile(0.25), df[col].quantile(0.75)
    iqr = q3 - q1
    df[col] = np.clip(df[col], q1 - 1.5 * iqr, q3 + 1.5 * iqr)

df = df.rename(columns={"Tenure_Months": "Tenure", "Monthly_Charges": "Monthly_Fee"})
print("Cleaned Shape:", df.shape)

--------------------------------------------------------------------------------
3. PREPROCESSING & DISCRETIZATION (preprocessing.py)
--------------------------------------------------------------------------------
import os, pandas as pd, numpy as np
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH).drop_duplicates().fillna(0)

# Discretization (Equal-width binning)
df["Age_Bin"] = pd.cut(df["Age"], bins=3, labels=["Young", "Middle", "Senior"])

# Label Encoding & One-Hot Encoding
df["Contract_Code"] = pd.factorize(df["Contract_Type"])[0]
df_ohe = pd.get_dummies(df, columns=["Contract_Type"], drop_first=True, dtype=int)

# Normalization & Standardization
num_col = "Age"
norm = (df[num_col] - df[num_col].min()) / (df[num_col].max() - df[num_col].min())
std = (df[num_col] - df[num_col].mean()) / df[num_col].std()

# Train-Test Split (80% Train, 20% Test)
shuffled = df.sample(frac=1, random_state=42)
split = int(0.8 * len(df))
train_df, test_df = shuffled.iloc[:split], shuffled.iloc[split:]
print(f"Train: {len(train_df)} | Test: {len(test_df)}")

--------------------------------------------------------------------------------
4. DATA VISUALISATION (data_visualisation.py)
--------------------------------------------------------------------------------
import os, matplotlib, matplotlib.pyplot as plt, seaborn as sns, pandas as pd, numpy as np
matplotlib.use('Agg')
FILE_PATH = os.path.join(os.path.dirname(__file__), "..", "datasets", "customer_churn_raw.csv")
df = pd.read_csv(FILE_PATH).dropna()
num_cols = list(df.select_dtypes(include=[np.number]).columns)

plt.figure(); sns.histplot(df[num_cols[0]], kde=True); plt.savefig("01_hist.png"); plt.close()
plt.figure(); sns.countplot(data=df, x="Contract_Type"); plt.savefig("02_count.png"); plt.close()
plt.figure(); sns.boxplot(data=df, x="Contract_Type", y=num_cols[0]); plt.savefig("03_box.png"); plt.close()
plt.figure(); sns.scatterplot(data=df, x=num_cols[0], y=num_cols[1]); plt.savefig("04_scatter.png"); plt.close()
plt.figure(); sns.heatmap(df[num_cols].corr(), annot=True); plt.savefig("05_heatmap.png"); plt.close()
g = sns.pairplot(df[num_cols[:3]], corner=True); g.savefig("06_pair.png"); plt.close('all')
print("Visualisations generated.")
