GamerBhai02

ML Exp 1

Sep 8th, 2025
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | Source Code | 0 0
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import seaborn as sns
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.preprocessing import StandardScaler
  6. from sklearn.linear_model import LogisticRegression
  7. from sklearn.metrics import (
  8.     confusion_matrix, classification_report,
  9.     roc_curve, auc, precision_score, recall_score, f1_score
  10. )
  11. df = pd.read_csv('heart.csv')
  12. display(df)
  13. X = df.drop("target", axis=1)
  14. y = df["target"]
  15.  
  16. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  17.  
  18. scaler = StandardScaler()
  19. X_train_scaled = scaler.fit_transform(X_train)
  20. X_test_scaled = scaler.transform(X_test)
  21.  
  22. model = LogisticRegression(max_iter=1000)
  23. model.fit(X_train_scaled, y_train)
  24.  
  25. y_pred = model.predict(X_test_scaled)
  26. y_pred_proba = model.predict_proba(X_test_scaled)[:, 1]
  27.  
  28. cm = confusion_matrix(y_test, y_pred)
  29. precision = precision_score(y_test, y_pred)
  30. recall = recall_score(y_test, y_pred)
  31. f1 = f1_score(y_test, y_pred)
  32.  
  33. print("Confusion Matrix:\n", cm)
  34. print("\nClassification Report:\n", classification_report(y_test, y_pred))
  35. print(f"Precision: {precision:.3f}")
  36. print(f"Recall: {recall:.3f}")
  37. print(f"F1 Score: {f1:.3f}")
  38.  
  39. plt.figure(figsize=(5,4))
  40. sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", cbar=False)
  41. plt.xlabel("Predicted")
  42. plt.ylabel("Actual")
  43. plt.title("Confusion Matrix")
  44. plt.show()
  45.  
  46. fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
  47. roc_auc = auc(fpr, tpr)
  48.  
  49. plt.figure(figsize=(6,5))
  50. plt.plot(fpr, tpr, color="darkorange", lw=2, label=f"ROC curve (AUC = {roc_auc:.2f})")
  51. plt.plot([0, 1], [0, 1], color="navy", lw=2, linestyle="--")
  52. plt.xlabel("False Positive Rate")
  53. plt.ylabel("True Positive Rate")
  54. plt.title("Receiver Operating Characteristic (ROC) Curve")
  55. plt.legend(loc="lower right")
  56. plt.show()
Tags: ML
Advertisement
Add Comment
Please, Sign In to add comment