1. 程式人生 > 其它 >機器學習之效能度量-實現混淆矩陣(confusion matrix)

機器學習之效能度量-實現混淆矩陣(confusion matrix)

技術標籤:機器學習python演算法機器學習

"""
@author: JacksonKim
@filename: confusion_matrix.py
@start: 2021/02/01
@end:   2021/02/01
"""

import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier

'''
混淆矩陣是機器學習中總結分類模型預測結果的情形分析表,以矩陣形式將資料集中的記錄按照真實的類別與分類模型預測的類別判斷兩個標準進行彙總:
1. TR:真正例,將正類預測為正類
2. FP: 假正例,將反例預測為正例
3. TN: 真反例,將反例預測為反例
4. FN: 假反例,將正例預測為反例
5. P:查準率, P = TP / (TP + FP)
6. R: 查全率, R = TP / (TP + FN)
'''
# 計算TP, 正例為1,反例為0 def TP(y_true, y_predict): assert len(y_true) == len(y_predict) # assert斷言函式,當表示式為false時觸發異常 return np.sum((y_true == 1) & (y_predict == 1)) # 計算FN def FN(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 1) & (y_predict ==
0)) # 計算FP def FP(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 0) & (y_predict == 1)) # 計算TN def TN(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 0) & (y_predict == 0)) # 生成混淆矩陣 def confusion_matrix(y_true,
y_predict): return np.array([ [TN(y_true, y_predict), FP(y_true, y_predict)], [FN(y_true, y_predict), TP(y_true, y_predict)] ]) # 獲取資料集 def get_data(): # 使用鸞尾花資料集和knn演算法測試 iris = datasets.load_iris() X = iris.data[:, :2] # 取鸞尾花資料集每個元素(list)的前兩個數 Y = iris.target # 獲取鸞尾花資料集的分類 # 畫出原始資料的分類散點圖 # plt.scatter(X[Y == 0, 0], X[Y == 0, 1], color='r') # plt.scatter(X[Y == 1, 0], X[Y == 1, 1], color='b') # plt.scatter(X[Y == 2, 0], X[Y == 2, 1], color='g') # plt.show() # 選取原始資料集的兩個分類做二分類任務 iris_x = X[Y < 2] iris_y = Y[Y < 2] print(iris_x) print(iris_y) # 畫出這兩類資料的散點圖 plt.scatter(iris_x[iris_y == 0, 0], iris_x[iris_y == 0, 1], color='r') plt.scatter(iris_x[iris_y == 1, 0], iris_x[iris_y == 1, 1], color='b') # plt.show() return iris_x, iris_y # 使用留出法處理資料 def train_test_split(x, y): shuffle_indexs = np.random.permutation(len(x)) test_radio = 0.3 # 設定測試集比例 test_size = int(len(x) * test_radio) # 求出測試集大小 # 求出訓練/測試集 test_indexs = shuffle_indexs[:test_size] train_indexs = shuffle_indexs[test_size:] train_x = x[train_indexs] train_y = y[train_indexs] test_x = x[test_indexs] test_y = y[test_indexs] return train_x, test_x, train_y, test_y # 使用KNN演算法作為分類器 def KNN(x, y): knn_clf = KNeighborsClassifier() train_x, test_x, train_y, test_y = train_test_split(x, y) # 劃分訓練/測試集 knn_clf.fit(train_x, train_y) # 進行訓練 score = knn_clf.score(test_x, test_y) # 實現我們的預測是100% print("score:", score) y_predict = knn_clf.predict(test_x) # 進行預測 matrix = confusion_matrix(test_y, y_predict) # 生成混淆矩陣 print(matrix) # 列印矩陣 x_data, y_data = get_data() KNN(x_data, y_data)