我正在生成一個confusion matrix來了解我text-classifier的predictionvs的想法ground-truth。目的是了解哪些intents 被預測為另一個intents。但問題是我有太多的類(超過160),所以矩陣是sparse,其中大部分欄位是zeros。顯然,對角線元素很可能是非零的,因為它基本上是正確預測的指示。
既然如此,我想生成一個更簡單的版本,因為我們只關心non-zero元素是否存在non-diagonal,因此,我想洗掉所有元素為零的rows 和columns(忽略diagonal條目),這樣圖形變得更小并且易于查看。怎么做?
以下是我到目前為止所做的代碼片段,它將為所有意圖生成映射,即(#intent, #intent)維度圖。
import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
import seaborn as sns
%matplotlib inline
sns.set(rc={'figure.figsize':(64,64)})
confusion_matrix = pd.crosstab(df['ground_truth_intent_name'], df['predicted_intent_name'])
variables = sorted(list(set(df['ground_truth_intent_name'])))
temp = DataFrame(confusion_matrix, index=variables, columns=variables)
sns.heatmap(temp, annot=True)
TL; 博士
這temp是一個pandas dataframe. 我需要洗掉所有元素為零的所有行和列(忽略對角線元素,即使它們不為零)。
uj5u.com熱心網友回復:
您可以any在比較中使用,但首先您需要用以下內容填充對角線0:
# also consider using
# a = np.isclose(confusion_matrix.to_numpy(), 0)
a = confusion_matrix.to_numpy() != 0
# fill diagonal
np.fill_diagonal(a, False)
# columns with at least one non-zero
cols = a.any(axis=0)
# rows with at least one non-zero
rows = a.any(axis=1)
# boolean indexing
confusion_matrix.loc[rows, cols]
讓我們舉個例子:
# random data
np.random.seed(1)
# this would agree with the above
a = np.random.randint(0,2, (5,5))
a[2] = 0
a[:-1,-1] = 0
confusion_matrix = pd.DataFrame(a)
所以資料將是:
0 1 2 3 4
0 1 1 0 0 0
1 1 1 1 1 0
2 0 0 0 0 0
3 0 0 1 0 0
4 0 1 0 0 1
和代碼輸出(注意第 2 行和第 4 列消失了):
0 1 2 3
0 1 1 0 0
1 1 1 1 1
3 0 0 1 0
4 0 1 0 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389663.html
標籤:Python 熊猫 matplotlib 交叉表 混淆矩阵
上一篇:在Python中使用`np.array_split`后將資料幀匯出為單獨的檔案
下一篇:當月累計金額
