Calculation accuracy, regression rate, F1 score and other indicators in pytorch

Calculation accuracy, regression rate, F1 score and other indicators in pytorch

After training the network in pytorch, the learning results need to be tested. The methods used in the routines on the official website are all correct, and the torch.eq() function is used.
But in order to evaluate the results more finely, we also need to calculate various other indicators. After flipping through the official website API, I found that there is no function for calculating TP, TN, FP, and FN. . .
After a lot of brainstorming, I thought that pytorch fully supports numpy, so I can directly judge whether it can be judged directly. I tried it and it works.

# TP    predict 和 label 同时为1
TP += ((pred_choice == 1) & (target.data == 1)).cpu().sum()
# TN    predict 和 label 同时为0
TN += ((pred_choice == 0) & (target.data == 0)).cpu().sum()
# FN    predict 0 label 1
FN += ((pred_choice == 0) & (target.data == 1)).cpu().sum()
# FP    predict 1 label 0
FP += ((pred_choice == 1) & (target.data == 0)).cpu().sum()

p = TP / (TP + FP)
r = TP / (TP + FN)
F1 = 2 * r * p / (r + p)
acc = (TP + TN) / (TP + TN + FP + FN

This way you can see all the indicators.
Because the target is Variable, you need to use target.data to get the corresponding tensor, and because it is calculated on the gpu, you need to use .cpu() to move it to the cpu.
Because this is a batch of statistics, you need to use += to accumulate the statistics of the entire epoch. Of course, it needs to be zeroed before the epoch starts

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326014579&siteId=291194637