Surya_from_1627

USML8

Sep 27th, 2026
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. from sklearn.preprocessing import StandardScaler
  4. from sklearn.decomposition import PCA
  5. from sklearn.model_selection import train_test_split
  6. from sklearn.linear_model import LogisticRegression
  7. from sklearn.metrics import confusion_matrix
  8. import matplotlib.pyplot as plt
  9. import seaborn as sns
  10.  
  11. ---------------------------------------------------------------------------
  12. data = {
  13.     'Height': [170, 165, 180, 175, 160, 172, 168, 177, 162, 158],
  14.     'Weight': [65, 59, 75, 68, 55, 70, 62, 74, 58, 54],
  15.     'Age': [30, 25, 35, 28, 22, 32, 27, 33, 24, 21],
  16.     'Gender': [1, 0, 1, 1, 0, 1, 0, 1, 0, 0],
  17. }
  18. df = pd.DataFrame(data)
  19. print(df)
  20. ---------------------------------------------------------------------------
  21. X = df.drop('Gender', axis=1)
  22. y = df['Gender']
  23.  
  24. scaler = StandardScaler()
  25. X_scaled = scaler.fit_transform(df)
  26. ---------------------------------------------------------------------------
  27. pca = PCA(n_components=2)
  28. X_pca = pca.fit_transform(X_scaled)
  29.  
  30. X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.3, random_state=42)
  31.  
  32. model = LogisticRegression()
  33. model.fit(X_train, y_train)
  34.  
  35. y_pred = model.predict(X_test)
  36.  
  37. ---------------------------------------------------------------------------
  38. cm = confusion_matrix(y_test, y_pred)
  39.  
  40. plt.figure(figsize=(5,4))
  41. sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Female', 'Male'], yticklabels=['Female', 'Male'])
  42. plt.xlabel('Predicted Label')
  43. plt.ylabel('True Label')
  44. plt.title('Confusion Matrix')
  45. plt.show()
  46.  
  47. ---------------------------------------------------------------------------
  48. y_numeric = pd.factorize(y)[0]
  49.  
  50. plt.figure(figsize=(12, 5))
  51.  
  52. plt.subplot(1, 2, 1)
  53. plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y_numeric, cmap='coolwarm', edgecolor='k', s=80)
  54. plt.xlabel('Original Feature 1')
  55. plt.ylabel('Original Feature 2')
  56. plt.title('Before PCA: Using First 2 Standardized Features')
  57. plt.colorbar(label='Target classes')
  58.  
  59. plt.subplot(1, 2, 2)
  60. plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_numeric, cmap='coolwarm', edgecolor='k', s=80)
  61. plt.xlabel('Principal Component 1')
  62. plt.ylabel('Principal Component 2')
  63. plt.title('After PCA: Projected onto 2 Principal Components')
  64. plt.colorbar(label='Target classes')
  65.  
  66. plt.tight_layout()
  67. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment