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

        有一些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])

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值