GamerBhai02

ML Exp 6

Oct 6th, 2025 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | Source Code | 0 0
  1. import pandas as pd
  2. from sklearn.model_selection import train_test_split
  3. from sklearn.preprocessing import StandardScaler, LabelEncoder
  4. from sklearn.tree import DecisionTreeClassifier, plot_tree
  5. from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
  6. import matplotlib.pyplot as plt
  7.  
  8. data = pd.read_csv("Social_Network_Ads.csv")
  9.  
  10. le = LabelEncoder()
  11. data['Gender'] = le.fit_transform(data['Gender'])  # Male=1, Female=0
  12.  
  13. X = data[['Gender', 'Age', 'EstimatedSalary']]
  14. y = data['Purchased']
  15.  
  16. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
  17.  
  18. scaler = StandardScaler()
  19. X_train = scaler.fit_transform(X_train)
  20. X_test = scaler.transform(X_test)
  21.  
  22. id3 = DecisionTreeClassifier(criterion='entropy', random_state=42)
  23. id3.fit(X_train, y_train)
  24.  
  25. # Predictions
  26. y_pred = id3.predict(X_test)
  27.  
  28. print("Accuracy:", accuracy_score(y_test, y_pred))
  29. print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
  30. print("\nClassification Report:\n", classification_report(y_test, y_pred))
  31.  
  32. plt.figure(figsize=(20,12))
  33. plot_tree(
  34.     id3,
  35.     feature_names=['Gender','Age','EstimatedSalary'],
  36.     class_names=['Not Purchased','Purchased'],
  37.     fontsize=15,
  38.     filled=True
  39. )
  40. plt.show()
  41.  
  42.  
  43. new_sample = pd.DataFrame({'Gender':[1], 'Age':[30], 'EstimatedSalary':[100000]})
  44. new_sample_scaled = scaler.transform(new_sample)
  45. prediction = id3.predict(new_sample_scaled)
  46.  
  47. predicted_class = 'Purchased' if prediction[0]==1 else 'Not Purchased'
  48. print(f"The predicted purchase status for the new sample is {predicted_class}")
  49.  
  50. https://jumpshare.com/s/qM5yLBS964qeCHauD2d2
Tags: ML
Advertisement
Add Comment
Please, Sign In to add comment