计算匹配的计数频率和分组数据帧的准确性

Compute the count frequency of match and accuracy of grouped dataframes

我有 4 个数据帧,想比较和计算匹配精度。

DATA_LABELS = {'DATA_LABELS': ['1', '2', '3', '3', '4', '3', '3', '1', '2', '4']}
EQ_LABELS =     {'EQ_LABELS': ['1', '1', '1', '1', '1', '0', '0', '0', '0', '0']}
EQ_NUM =           {'EQ_NUM': ['1', '1', '1', '2', '2', '1', '1', '2', '2', '2']}
pred =               {'pred': ['1', '2', '1', '3', '4', '3', '2', '1', '3', '4']}

数据按EQ_LABELS和EQ_NUM分组,例如:

当EQ_LABELS = 1且EQ_NUM = 1时,对应的DATA_LABELS和pred为['1', '2', '3']和['1' , '2', '1'], 所以 total = 3 and Correct (equal) = 2, pred_proba (accuracy) = 0.67

其他人:

  EQ_LABELS EQ_NUM total Correct pred_proba
    1       1      3      2      0.67
    1       2      2      2      1.00
    0       1      2      1      0.50
    0       2      3      2      0.67

我想得到两个新的数据帧作为输出,如

y_true  =  {'y_true': ['1', '1', '0', '0']}
y_pred =   {'y_pred': ['0.67', '1', '0.5', '0.67']}

试试这个:

#Using your data definitions
DATA_LABELS = {'DATA_LABELS': ['1', '2', '3', '3', '4', '3', '3', '1', '2', '4']}
EQ_LABELS =     {'EQ_LABELS': ['1', '1', '1', '1', '1', '0', '0', '0', '0', '0']}
EQ_NUM =           {'EQ_NUM': ['1', '1', '1', '2', '2', '1', '1', '2', '2', '2']}
pred =               {'pred': ['1', '2', '1', '3', '4', '3', '2', '1', '3', '4']}

#Creating combined dataframe
df = pd.concat([pd.DataFrame(i) for i in [DATA_LABELS, EQ_LABELS, EQ_NUM, pred]], axis=1)

#Creating boolean matrix then grouping and taking the mean
(df['DATA_LABELS'] == df['pred']).groupby([df['EQ_LABELS'],df['EQ_NUM']])\
                                 .mean()\
                                 .rename('pred_proba')\
                                 .reset_index()

输出:

  EQ_LABELS EQ_NUM  pred_proba
0         0      1    0.500000
1         0      2    0.666667
2         1      1    0.666667
3         1      2    1.000000

并且,返回字典:

y_true = df_out[['EQ_LABELS']].rename(columns={'EQ_LABELS':'y_true'}).to_dict(orient='list')
y_pred = df_out[['pred_proba']].rename(columns={'pred_proba':'y_pred'}).to_dict(orient='list')
print(y_true)
print(y_pred)

输出:

{'y_true': ['0', '0', '1', '1']}
{'y_pred': [0.5, 0.6666666666666666, 0.6666666666666666, 1.0]}