For Data cleaning

import pandas as pd
import numpy as np
import warnings
import seaborn as sns
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
df = pd.read_csv('https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv')
df.replace(['?','NA','-',''],np.nan,inplace=True)
print(df.isnull().sum())
print(df.isnull().sum()/len(df)*100)
for col in df.columns:
    missing_pct=df[col].isnull().mean()*100
    if missing_pct==0:
        continue
    elif missing_pct>60:
        df.drop(columns=[col],inplace=True)
    elif df[col].dtype=='object':
        df[col].fillna(df[col].mode()[0],inplace=True)
    else:
        if abs(df[col].skew())>1:
            df[col].fillna(df[col].median(),inplace=True)
        else:
            df[col].fillna(df[col].mean(),inplace=True)
print(df.isnull().sum().sum(),"missing values left")
sns.boxplot(x=df['Fare'])
plt.show()
#Handeling Outliers
def handel_outlier(df,coln,method='cap'):
    df=df.copy()
    for col in coln:
        Q1=df[col].quantile(0.25)
        Q3=df[col].quantile(0.75)
        IQR=Q3-Q1
        lower=Q1-1.5*IQR
        upper=Q3+1.5*IQR
        if method=='remove':
            df=df[(df[col]>=lower) & (df[col]<=upper)]
        elif method=='cap':
             df[col] = np.where(df[col] > upper, upper,
                        np.where(df[col] < lower, lower, df[col]))
    return df
numeric_col=df.select_dtypes(include=np.number).columns
df_clean=handel_outlier(df,numeric_col)
sns.boxplot(x=df_clean['Fare'])
plt.show()
num_df=df.select_dtypes(include=["int64","float64"])
corr_mtx=num_df.corr()
print(corr_mtx)
sns.heatmap(corr_mtx,annot=True,cmap="coolwarm",fmt=".2f")
plt.title("correlation matrix")
plt.show()

 for models 

Code: 
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import (accuracy_score, confusion_matrix, precision_score,
                             recall_score, roc_curve, auc)

# ============ STEP 1: LOAD DATA ============
# Titanic
data = pd.read_csv('https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv')
# Diabetes (use this instead for the practical)
# data = pd.read_csv("C:/Users/Admin/Downloads/diabetes.csv")

target = 'Survived'          # diabetes: 'Outcome'

# ============ STEP 2: PREPARE DATA (edit per dataset) ============
# Titanic only. For diabetes, delete these lines (it is already numeric).
data = data.drop(columns=['PassengerId', 'Name', 'Ticket', 'Cabin'])
data['Age'] = data['Age'].fillna(data['Age'].median())
data['Embarked'] = data['Embarked'].fillna(data['Embarked'].mode()[0])
data['Sex'] = data['Sex'].map({'male': 0, 'female': 1})
data = pd.get_dummies(data, columns=['Embarked'], drop_first=True, dtype=int)

# Diabetes only: zeros that are really missing
# for c in ['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI']:
#     data[c] = data[c].replace(0, np.nan).fillna(data[c].median())

# ============ STEP 3: SPLIT ============
X = data.drop(columns=[target])
y = data[target]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

# ============ STEP 4: CHOOSE MODEL (only this changes) ============
clf = DecisionTreeClassifier(max_depth=4, random_state=42)
# from sklearn.naive_bayes import GaussianNB
# clf = GaussianNB()
# from sklearn.ensemble import RandomForestClassifier
# clf = RandomForestClassifier(n_estimators=100, random_state=42)

clf.fit(X_train, y_train)

# ============ STEP 5: PREDICT ============
y_pred = clf.predict(X_test)
y_pred_prob = clf.predict_proba(X_test)[:, 1]

# ============ STEP 6: METRICS (same for every classifier) ============
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
precision = precision_score(y_test, y_pred)
sensitivity = recall_score(y_test, y_pred)
TN, FP, FN, TP = conf_matrix.ravel()
specificity = TN / (TN + FP)
standard_error = np.sqrt((accuracy * (1 - accuracy)) / len(y_test))

fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
roc_auc = auc(fpr, tpr)

print("Accuracy:", accuracy)
print("Confusion Matrix:\n", conf_matrix)
print("Standard Error:", standard_error)
print("Precision:", precision)
print("Sensitivity (Recall):", sensitivity)
print("Specificity:", specificity)
print("AUC:", roc_auc)

# ============ STEP 7: ROC CURVE (same for every classifier) ============
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()

# ============ STEP 8: MODEL-SPECIFIC PLOT ============
# Decision tree only
plt.figure(figsize=(12, 8))
plot_tree(clf, feature_names=X.columns, class_names=['0', '1'], filled=True, max_depth=3)
plt.title("Decision Tree (Max Depth = 3)")
plt.show()

# Random forest only (replace the plot_tree block with this)
# pd.Series(clf.feature_importances_, index=X.columns).sort_values().plot(kind='barh')
# plt.title("Feature Importance"); plt.show()
