2 回答

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
將任何2D矩陣(混淆與否)轉(zhuǎn)換為熊貓數(shù)據(jù)幀非常簡(jiǎn)單:
from sklearn.metrics import confusion_matrix
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
cm = confusion_matrix(y_true, y_pred)
print(cm)
# result:
[[2 0 0]
[0 0 1]
[1 0 2]]
import pandas as pd
df = pd.DataFrame(cm)
print(df)
# result:
0 1 2
0 2 0 0
1 0 0 1
2 1 0 2
full,具有兩行和列名稱(chēng)。
合并數(shù)據(jù)幀也是直截了當(dāng)?shù)模?/p>
cm2 = [[1, 0, 0],
[0, 0, 1],
[2, 0, 1]]
df2 = pd.DataFrame(cm2)
cm3 = [[0, 0, 2],
[1, 2, 1],
[2, 0, 0]]
df3 = pd.DataFrame(cm3)
frames = [df, df2, df3]
final = pd.concat(frames)
print(final)
# result:
0 1 2
0 2 0 0
1 0 0 1
2 1 0 2
0 1 0 0
1 0 0 1
2 2 0 1
0 0 0 2
1 1 2 1
2 2 0 0
如果在循環(huán)中使用它,則始終可以從空列表開(kāi)始,用于每個(gè)新數(shù)據(jù)幀,并獲取最終幀:frames=[]frames.append(df)pd.concat(frames)
frames = []
for model_name, model in models.items():
y_pred = cross_val_predict(model, features, ylabels, cv=cv_splitter)
cm = confusion_matrix(y_true, y_pred)
df = pd.DataFrame(cm)
frames.append(df)
final = pd.concat(frames)

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
存儲(chǔ)在列表中,然后使用:np.vstack()
import numpy as np
all_cm = list()
for model_name, model in models.items():
y_pred = cross_val_predict(model, features, ylabels, cv=cv_splitter)
print("Model: {}".format(model_name))
print("Accuracy: {}".format(accuracy_score(ylabels, y_pred)))
cm = confusion_matrix(ylabels, y_pred)
all_cm.append(cm)
final_matrix = np.vstack(all_cm)
print(final_matrix)
人工數(shù)據(jù)示例:
import numpy as np
np.random.seed(0)
all_cm = list()
for i in range(3):
all_cm.append(np.random.rand(3,3))
final_matrix = np.vstack(all_cm)
print(final_matrix)
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]
[0.43758721 0.891773 0.96366276]
[0.38344152 0.79172504 0.52889492]
[0.56804456 0.92559664 0.07103606]
[0.0871293 0.0202184 0.83261985]
[0.77815675 0.87001215 0.97861834]
[0.79915856 0.46147936 0.78052918]
[0.11827443 0.63992102 0.14335329]]
添加回答
舉報(bào)