I'm trying to look for accuarcy/PRecision/Reacll etc... So i used this code and it works verry well for me but actually i want to change the output form as tabular My output:
Column 2 acc: 1.0
Column 2 p: 1.0
Column 2 r: 1.0
Column 1 acc: 1.0
Column 1 p: 1.0
Column 1 r: 1.0
Column 3 acc: 1.0
Column 3 p: 1.0
Column 3 r: 1.0
The output that i want:
+----------+-----------+-------+---------+
| Feature | Precision |Recall | Accuracy|
+----------+-----------+-------+---------+
| 1 | 1.0 | 1.0 | 1.0 |
| 2 | 1.0 | 1.0 | 1.0 |
| 3 | 1.0 | 1.0 | 1.0 |
+----------+----------+--------+---------+
My code:
def calc_acc(original, predect1):
common_columns = list(set(original.columns).intersection(predect1.columns))
avg_a = 0.0
avg_p = 0.0
avg_r = 0.0
for c in common_columns:
c_acc = accuracy_score(original[c], predect1[c])
p = precision_score(original[c], predect1[c], average='macro', labels=np.unique(predect1[c]))
r = recall_score(original[c], predect1[c], average='macro', labels=np.unique(predect1[c]))
print(f'Column {c} acc: {c_acc}')
print(f'Column {c} p: {p}')
print(f'Column {c} r: {r}')
avg_a += c_acc/len(common_columns)
avg_p += p/len(common_columns)
avg_r += r/len(common_columns)
NB: c is the column
use this code to draw PrettyTable
:
from prettytable import PrettyTable
pt = PrettyTable()
pt.field_names = ['Feature','Precision','Recall','Accuracy']
pt.add_row([c,p,r,c_acc])
finally your desire code and output like this:
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score, recall_score
from prettytable import PrettyTable
def calc_acc(original, predect1):
common_columns = list(set(original.columns).intersection(predect1.columns))
avg_a = 0.0
avg_p = 0.0
avg_r = 0.0
pt = PrettyTable()
pt.field_names = ['Feature','Precision','Recall','Accuracy']
for c in common_columns:
c_acc = accuracy_score(original[c], predect1[c])
p = precision_score(original[c], predect1[c], average='macro', labels=np.unique(predect1[c]))
r = recall_score(original[c], predect1[c], average='macro', labels=np.unique(predect1[c]))
pt.add_row([c,p,r,c_acc])
avg_a += c_acc/len(common_columns)
avg_p += p/len(common_columns)
avg_r += r/len(common_columns)
print(pt)
pre = [[1, 1, 3], [2, 3, 4]]
pre = pd.DataFrame(pre, columns= ['1', '2', '3'])
calc_acc(pre, pre)
output: