Advertisement
Guest User

Untitled

a guest
May 20th, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. def plot_classification_report(cr, title='Classification report ', with_avg_total=False, cmap=plt.cm.Blues):
  5.  
  6. lines = cr.split('\n')
  7.  
  8. classes = []
  9. plotMat = []
  10. for line in lines[2 : (len(lines) - 3)]:
  11. #print(line)
  12. t = line.split()
  13. # print(t)
  14. classes.append(t[0])
  15. v = [float(x) for x in t[1: len(t) - 1]]
  16. print(v)
  17. plotMat.append(v)
  18.  
  19. if with_avg_total:
  20. aveTotal = lines[len(lines) - 1].split()
  21. classes.append('avg/total')
  22. vAveTotal = [float(x) for x in t[1:len(aveTotal) - 1]]
  23. plotMat.append(vAveTotal)
  24.  
  25.  
  26. plt.imshow(plotMat, interpolation='nearest', cmap=cmap)
  27. plt.title(title)
  28. plt.colorbar()
  29. x_tick_marks = np.arange(3)
  30. y_tick_marks = np.arange(len(classes))
  31. plt.xticks(x_tick_marks, ['precision', 'recall', 'f1-score'], rotation=45)
  32. plt.yticks(y_tick_marks, classes)
  33. plt.tight_layout()
  34. plt.ylabel('Classes')
  35. plt.xlabel('Measures')
  36. plt.show()
  37.  
  38.  
  39. # Test example of classification report
  40. sampleClassificationReport = """ precision recall f1-score support
  41.  
  42. 1 0.62 1.00 0.76 66
  43. 2 0.93 0.93 0.93 40
  44. 3 0.59 0.97 0.73 67
  45. 4 0.47 0.92 0.62 272
  46. 5 1.00 0.16 0.28 413
  47.  
  48. avg / total 0.77 0.57 0.49 858"""
  49.  
  50. plot_classification_report(sampleClassificationReport)
  51.  
  52. import pandas as pd
  53.  
  54. from sklearn.datasets import load_wine
  55. from sklearn.metrics import classification_report
  56. from sklearn.naive_bayes import MultinomialNB
  57. from sklearn.linear_model import LogisticRegression
  58. from sklearn.model_selection import train_test_split
  59.  
  60. data = load_wine()
  61. X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, shuffle=True)
  62.  
  63. model = MultinomialNB().fit(X_train, y_train)
  64. y_pred = model.predict(X_test)
  65. classificationReport = classification_report(y_test, y_pred, target_names=data.target_names)
  66. plot_classification_report(classificationReport)
  67.  
  68. model = LogisticRegression().fit(X, y)
  69. y_pred = model.predict(X)
  70. classificationReport = classification_report(y, y_pred, target_names=data.target_names)
  71. plot_classification_report(classificationReport)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement