Python与MATLAB小练习:计算准确度Accuracy

凯鲁嘎吉 / 2023-04-29 / 原文

Python与MATLAB小练习:计算准确度Accuracy

分别使用Python与MATLAB编程,计算聚类准确度。思路为:首先利用匈牙利算法将训练后的标签进行调整,然后再计算准确度。

1. Python程序

 1 # Python demo
 2 #  -*- coding: utf-8 -*-
 3 # Author:凯鲁嘎吉 Coral Gajic
 4 #
 5 # Python小练习:计算准确度Accuracy
 6 # 先用匈牙利算法调整标签,然后再计算准确度
 7 import numpy as np
 8 # 已经调整过标签了
 9 def cluster_acc(y_true, y_pred):
10     y_true = y_true.astype(np.int64)
11     assert y_pred.size == y_true.size
12     D = max(y_pred.max(), y_true.max()) + 1
13     w = np.zeros((D, D), dtype=np.int64)
14     for i in range(y_pred.size):
15         w[y_pred[i], y_true[i]] += 1
16     from sklearn.utils.linear_assignment_ import linear_assignment
17     # 匈牙利算法调整标签
18     ind = linear_assignment(w.max() - w)
19     return sum([w[i, j] for i, j in ind]) * 1.0 / y_pred.size
20 
21 y_true = np.array([2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1])
22 y_pred_1 = np.array([1, 1, 2, 1, 1, 2, 2, 2, 3, 2, 2, 3, 1, 3, 3, 2, 3]) # 未调整的标签
23 y_pred_2 = np.array([2, 2, 3, 2, 2, 3, 3, 3, 1, 3, 3, 1, 2, 1, 1, 3, 1]) # 调整后的标签
24 result_1 = cluster_acc(y_true, y_pred_1)
25 result_2 = cluster_acc(y_true, y_pred_2)
26 print('1:', result_1)
27 print('2:', result_2)

结果:

1: 0.6470588235294118
2: 0.6470588235294118

2. MATLAB程序

结果:

未调整标签的准确度:0.294118
调整标签后的准确度:0.647059

完成。