Advertisement
makispaiktis

ML - Lab 2 - xtest, ytest, xtrain, ytrain in tree classificator

Oct 18th, 2022 (edited)
1,686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from sklearn import datasets, tree
  4. from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
  5.  
  6. # Load an iris dataset
  7. iris = datasets.load_iris()
  8. data = iris.data[:, [0, 1]]         # Select only the 2 first columns (0, 1)
  9. # print("Dataset: ")                  # Length = 150
  10. # print(data)
  11. # print()
  12. target = iris.target                # Like the class column
  13. # print("Target: ")
  14. # print(target)
  15. # print()
  16. target[100:125] = 0
  17. target[125:150] = 1
  18. # print("Target: ")
  19. # print(target)
  20. # print()
  21.  
  22.  
  23. # Split into training and testing data
  24. # Select 120/150 entries for training
  25. xtrain = np.concatenate((data[0:40], data[50:90], data[100:140]))
  26. ytrain = np.concatenate((target[0:40], target[50:90], target[100:140]))
  27. # Select 30/150 entries for testing
  28. xtest = np.concatenate((data[40:50], data[90:100], data[140:150]))
  29. ytest = np.concatenate((target[40:50], target[90:100], target[140:150]))
  30. print(str(len(xtrain)) + " training entries, " + str(len(xtest)) + " testing entries")
  31.  
  32. # Classifier - Prediction
  33. clf = tree.DecisionTreeClassifier(min_samples_split=20)
  34. clf = clf.fit(xtrain, ytrain)
  35. pred = clf.predict(xtest)
  36. # Plot
  37. fig = plt.figure(figsize=(10, 9))
  38. tree.plot_tree(clf, class_names=['No', 'Yes'], filled=True)
  39. plt.show()
  40. # Metrics
  41. print("Confusion Matrix = ")
  42. print(confusion_matrix(ytest, pred))
  43. print("Accuracy = " + str(accuracy_score(ytest, pred)))
  44. print("Precision = " + str(precision_score(ytest, pred, pos_label=1)))
  45. print("Recall = " + str(recall_score(ytest, pred, pos_label=1)))
  46. print("F1 score = " + str(f1_score(ytest, pred, pos_label=1)))
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement