非常抱歉之前的回答没有正确理解你的需求。根据你的要求,以下是重新编写统计准确率的代码:

# 统计准确率
correct = 0
total = 0

with torch.no_grad():
    for i, input_tensor in enumerate(val_tensors):
        val_output = network(input_tensor)

        # 计算相似度
        target_similarity = F.cosine_similarity(val_output, tensor_list[i].unsqueeze(0), dim=1)

        other_similarities = []
        for j, tensor in enumerate(tensor_list):
            if j != i:
                similarity = F.cosine_similarity(val_output, tensor.unsqueeze(0), dim=1)
                other_similarities.append(similarity)

        other_similarities = torch.cat(other_similarities)

        # 判断标签类别
        labels = [torch.tensor([1, 0, 0, 0]), torch.tensor([0, 1, 0, 0]), torch.tensor([0, 0, 1, 0]), torch.tensor([1, 1, 1, 1])]
        label_index = torch.argmax(tensor_list[i])
        label = labels[label_index]

        # 如果当前输出和自身标签之间的相似度最大,则准确率加1
        if target_similarity > torch.max(other_similarities):
            predicted_index = torch.argmax(val_output)
            if torch.all(torch.eq(label, labels[predicted_index])):
                correct += 1

        total += 1

# 打印验证信息
print('Epoch: %d, Validation Accuracy: %.2f%%' % (epoch + 1, 100 * correct / total))

在验证阶段,计算输出和标签之间的相似度。然后,根据标签类别列表 [torch.tensor([1, 0, 0, 0]), torch.tensor([0, 1, 0, 0]), torch.tensor([0, 0, 1, 0]), torch.tensor([1, 1, 1, 1])],确定当前样本的标签。接下来,将当前输出与除了自身标签之外的其他标签进行相似度比较。如果当前输出和自身标签之间的相似度最大,并且预测的标签与真实标签相等,则准确率加1。最后,计算和打印验证准确率。

再次对之前的回答造成的困扰表示抱歉,希望这次能够满足你的需求!

PyTorch 模型验证:计算输出与标签相似度以统计准确率

原文地址: https://www.cveoy.top/t/topic/K9k 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录