深度学习NLP任务中一些功能性代码块pytoch实现记录

喜你入骨 提交于 2020-01-10 10:58:18

        有一些NLP任务中需要实现一些小功能,还是不是很熟练,但是自己写起来又有点难度,故此记录下来。以后每遇到新的就添加上来——不定时更新添加!

1、由predictions和labels计算准确率、正确率、recall和F1

#准确率的计算
correct += (predict == label).sum().item()
total += label.size(0)
train_acc = correct / total

#精确率、recall和F1的计算
for i in range(self.number_of_classes):
    if i == self.none_label:
        continue
    #TP和FP
    self._true_positives += ((predictions==i)*(gold_labels==i)*mask.bool()).sum()
    self._false_positives += ((predictions==i)*(gold_labels!=i)*mask.bool()).sum()       
    #TN和FN
    self._true_negatives += ((predictions!=i)*(gold_labels!=i)*mask.bool()).sum()
    self._false_negatives += ((predictions!=i)*(gold_labels==i)*mask.bool()).sum()

#精确率、
precision = float(self._true_positives) / (float(self._true_positives + self._false_positives) + 1e-13)

#recall 
recall = float(self._true_positives) / (float(self._true_positives + self._false_negatives) + 1e-13)

#F1
f1_measure = 2. * ((precision * recall) / (precision + recall + 1e-13))

之所以记录,是因为对tensor这种操作不熟悉。

2、tensor的创建

a = torch.randn([2,3])

#创建一个和a形状一样的,值全部为1e-9的tensor
b = torch.full(a.size(),1e-9)

#创建值为1
c = torch.ones([2,3])

#创建值为0的tensor
d = torch.zeros([2,3])

#创建一个空的tensor
e = torch.empty([2,3])

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!