pytorch的一些操作

取出标签对应的样本特征

第一种操作

samples = torch.randn(6,3)
labels = torch.tensor([1,1,0,0,0,1])
# 取出label 是1 的数据
mask = labels == 1
samples[mask]
image.png

第二种操作

samples = torch.randn(6,3)
print(samples)

labels = torch.tensor([1,1,0,0,0,1])
print(labels)

# 取出标签为1
index = torch.eq(labels,1)
index = index.nonzero()[:,0]
print(index)
result = torch.index_select(samples, 0, index)
print(result)
image.png

取出预测置信度大于预测置信度阈值的数据

all_output = torch.randn(5,3)
all_output = torch.nn.Softmax(dim=1)(all_output)
max_prob, predict = torch.max(all_output, 1)
print(max_prob, predict)
print((max_prob > 0.5))
select_sample_index = torch.squeeze((max_prob > 0.5).nonzero(), dim=1)
print(select_sample_index)  # 这就是预测置信度大于阈值的数据索引
image.png

取出预测置信度大于熵阈值的数据

logits = torch.randn(5,3)
softmax_logits = torch.softmax(logits, dim=1)
print(softmax_logits)
entropy = -1.0 * ((1e-8 + softmax_logits) * torch.log(softmax_logits + 1e-8)).sum(dim=1)
print(entropy)
select_sample_index = torch.squeeze((entropy < 1).nonzero(), dim=1)
print(select_sample_index)
image.png

torch.Tensor.index_add_函数

  • 用途:比如数据样本中,相同标签的样本特征加在一起
import torch
# 五个类别,样本特征长度是3
x = torch.ones(5, 3)
# 现在有四个样本,样本特征长度是3
t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float)
index = torch.tensor([0, 2, 4, 2])
new_x = x.index_add(0, index, t) 

t 的第 0 行加到X的第 0 行[1, 2, 3] + 1 = 【2,3,4】
t 的第 1 行加到X的第 2 行[4, 5, 6]+1 = 【5,6,7】
t 的第 2 行加到X的第 4 行[7, 8, 9]+1 = 【8,9,10】
t 的第 3 行加到X的第 2 行 [10, 11, 12] + 【5,6,7】 = 【15, 17, 19】

image.png

样本选择。 对于token级别的任务,我们只有token级别的伪标签。在进行高质量数据选择时, 我们通常需要选择句子级别的样本。因此,我们可以计算一个句子中高质量token 占句子token的比例,比例越高,表明句子质量越好。

    def entropy_select_for_token_task(self, logits, activate):
        """
        :param logits:  batch * seq_length * label_num
        :param activate:  batch * seq_length
        :return: 句子级别的索引
        """
        # 取出activate的 token
        selected_logits = logits[activate == 1, :]   #  valid_token * num_class
        # 计算这些token 的预测熵
        entropy = -torch.sum(selected_logits * torch.log(selected_logits), dim=-1, keepdim=True).squeeze()
        # 取出符合条件的token
        select_token_index = torch.squeeze((entropy < self.entropy_threshold).nonzero(), dim=1)
        # 记录每个句子中有效token的数量
        valid_count = torch.sum(activate == 1, dim=1, keepdim=True).squeeze()
        # 计算符合条件的token 在句子中所占的比例
        valid_token_ratios = []
        start = 0
        for size in valid_count:
            end = start + size
            subset = select_token_index[(select_token_index >= start) & (select_token_index < end)]
            ratio = len(subset) / size
            valid_token_ratios.append(ratio.item())
            start = end

        valid_token_ratios = torch.tensor(valid_token_ratios).to(self.device)
        # 只有当一个句子中的有效token 超过一定的比例,我们才选择
        select_sentence_index = torch.squeeze((valid_token_ratios > self.sentence_threshold).nonzero(), dim=1)

        # 如果选择之后的样本数量为0
        if select_sentence_index.shape[0] == 0:
            self.print('注意:筛选的阈值过小,导致没有样本符合条件!!! 返回有效样本比例最高的一半样本!!!')
            # 取出 比例最好的一半的句子
            _, sort_index = torch.sort(valid_token_ratios, dim=0, descending=True)
            select_sentence_index = sort_index[:valid_token_ratios.shape[0] // 2]

        return select_sentence_index
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容