FINLAB

10

Oct 8th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.56 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import itertools
  5. from sklearn.model_selection import train_test_split
  6. from sklearn import tree
  7. from sklearn.metrics import classification_report
  8. from sklearn.metrics import confusion_matrix  
  9. from dtreeplt import dtreeplt
  10.  
  11.  
  12.  
  13. def plot_confusion_matrix(cm, classes,
  14.                           normalize=False,
  15.                           title='Confusion matrix',
  16.                           cmap=plt.cm.Blues):
  17.     """
  18.    This function prints and plots the confusion matrix.
  19.    Normalization can be applied by setting `normalize=True`.
  20.    """
  21.     plt.figure(figsize = (5, 5))
  22.     plt.imshow(cm, interpolation='nearest', cmap=cmap)
  23.     plt.title(title)
  24.     plt.colorbar()
  25.     tick_marks = np.arange(len(classes))
  26.     plt.xticks(tick_marks, classes, rotation=45)
  27.     plt.yticks(tick_marks, classes)
  28.  
  29.     if normalize:
  30.         cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
  31.         print("Normalized confusion matrix")
  32.     else:
  33.         print('Confusion matrix, without normalization')
  34.  
  35.     print(cm)
  36.  
  37.     thresh = cm.max() / 2.
  38.     for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
  39.         plt.text(j, i, cm[i, j],
  40.                  horizontalalignment="center",
  41.                  color="white" if cm[i, j] > thresh else "black")
  42.  
  43.     plt.tight_layout()
  44.     plt.ylabel('True')
  45.     plt.xlabel('Predicted')
  46.    
  47.    
  48. #讀入資料
  49. AllData = pd.read_csv('all_data.csv')
  50.  
  51.  
  52. CleanData = AllData.dropna()
  53. CleanData = CleanData.reset_index(drop=True)
  54. CleanData = CleanData.drop('mdate', axis = 1)
  55. CleanData = CleanData.drop('pmkt', axis = 1)
  56.  
  57. X = CleanData.drop('Y', axis = 1)
  58.  
  59. y = CleanData['Y']
  60. y = y.astype(int)
  61. #切分資料(70%訓練、30%測試)
  62. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3,
  63.                                                     random_state=12345)
  64.  
  65. #建立分類器
  66. clf = tree.DecisionTreeClassifier(criterion = 'gini', max_depth = 5)
  67. clf.fit(X_train, y_train)
  68.  
  69.  
  70.  
  71.  
  72. #混淆矩陣
  73. cnf_matrix = confusion_matrix(y_test, clf.predict(X_test))
  74. target_names=['0', '1']
  75. plot_confusion_matrix(cnf_matrix, classes =target_names,
  76.                       title='Confusion matrix')
  77. plt.show()
  78. print(confusion_matrix(y_test,clf.predict(X_test)))
  79.  
  80. #精準度、召回率
  81. print(classification_report(y_test, clf.predict(X_test)))
  82.  
  83. #印出正確率
  84. from sklearn import metrics
  85. accuracy = metrics.accuracy_score(y_test, clf.predict(X_test))
  86. print(accuracy)
  87.  
  88. #特徵重要性
  89.  
  90. feature_names= X.keys().tolist()
  91. clf.feature_importances_.tolist()
  92. a=clf.feature_importances_.tolist()
  93.  
  94. df = pd.DataFrame({'feature':feature_names,  
  95.                    'feature_importance':clf.feature_importances_.tolist()})
  96. df = df.sort_values(by=['feature_importance'], ascending=False).reset_index(drop=True)
  97.  
  98. def autolabel(rects):
  99.     for rect in rects:
  100.         height = rect.get_height()
  101.         plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%f'%float(height),
  102.                  ha='center', va='bottom')
  103.  
  104. plt.style.use('ggplot')
  105. fig = plt.figure(figsize=(8, 4))
  106. plt.rcParams['font.family'] = 'DFKai-sb'  #標楷體
  107. gini = plt.bar(df.index, df['feature_importance'], align='center')
  108. plt.xlabel('Feature')  #X軸名稱
  109. plt.ylabel('Feature Importance')  #Y軸名稱
  110. plt.xticks(df.index, df['feature'])  #X軸項目名稱
  111.  
  112. autolabel(gini)
  113.  
  114. plt.show()
  115.  
  116. dtree = dtreeplt(model = clf,feature_names = X.keys().tolist(), target_names = y.keys().tolist())
  117. fig = dtree.view()
  118. fig.savefig('output.png')
Add Comment
Please, Sign In to add comment