[英]How can I reduce lines of code and make it work with other data?
我有這樣的多類:
predicted = [1 0 2 1 1 0 1 2 1 2 2 0 0 0 0 2 2 1 1 1 0 1 0 1 2 1 1 2 0 0]
actual = [1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]
我想找到每個類的精度(0,1,2)
這是我的代碼:
TP_0 = 0
TP_1 = 0
TP_2 = 0
FP_0 = 0
FP_1 = 0
FP_2 = 0
for i in range(len(y_pred)):
if y_pred[i] == y_test[i] :
if y_pred[i] == 0:
TP_0 += 1
elif y_pred[i] == 1:
TP_1 += 1
else:
TP_2 += 1
else:
if y_pred[i] == 0:
FP_0 += 1
elif y_pred[i] == 1:
FP_1 += 1
else:
FP_2 += 1
precision_0 = TP_0/(TP_0+FP_0)
precision_1 = TP_1/(TP_1+FP_1)
precision_2 = TP_2/(TP_2+FP_2)
如果我以前知道類和數據的數量,它就可以工作。 但現在無論我是否認識他們,我都想讓它發揮作用,就像我有更多的課程一樣。
如何減少代碼或使其動態化?
注意:我不喜歡用圖書館來完成它。
你可以試試這個:
from collections import defaultdict
def precision(y_test, y_pred):
# to count false-pos and true-pos
tp = defaultdict(int)
fp = defaultdict(int)
classes = max(max(y_test), max(y_pred))
# count tp and fp
for i in range(len(y_pred)):
if y_pred[i] == y_test[i]:
tp[y_test[i]] += 1
else:
fp[y_test[i]] += 1
# calculate prec for every class
precision = dict()
for cls in range(classes+1):
precision[cls] = tp[cls] / (tp[cls] + fp[cls])
return precision
predicted = [0, 1, 2, 3, 0, 1, 1]
actual = [0, 1, 2, 0, 1, 2, 3]
Output:
{0: 0.5, 1: 0.5, 2: 0.5, 3: 0.0}
您將獲得帶有鍵的字典 - class 和值 - 精度。
import numpy as np
# Convert to arrays
y_pred = np.array(y_pred)
y_test = np.array(y_test)
def get_precision(pred, truth, num_classes):
precision_by_class = []
match = (pred == truth) # Binary array indicating whether each prediction is true
for i_class in range(num_classes): # Iterate over classes
# match[pred == i_class].sum() -> number of correct predictions of specific class
# (pred == i_class).sum() -> number of times specific class was predicted
out.append(match[pred == i_class].sum() / (pred == i_class).sum())
accuracy = match.mean() # Total accuracy
return precision_by_class, accuracy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.