【手写AI代码目录】准备发布的教程

1. tensorboard

from torch.utils.tensorboard import SummaryWriter

# TensorBoard
writer = SummaryWriter('runs/mnist_experiment_1')
...

        if i % 100 == 99:    # 每 100 个 batch 打印一次并记录到 TensorBoard
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 100))
            writer.add_scalar('Training Loss',
                              running_loss / 100,
                              epoch * len(trainloader) + i)
            writer.add_scalar('Accuracy',
                              correct / total,
                              epoch * len(trainloader) + i)
            running_loss = 0.0
            total = 0
            correct = 0
            
# 不要忘了关闭 SummaryWriter
writer.close()

然后终端启动命令: tensorboard --logdir=runs

2. F.cross_entropy(input_tensor, target) = F.log_softmax() + F.nll_loss()

两者 计算的loss 相同

import torch
import torch.nn.functional as F
import torch.nn as nn

# 定义一个输入张量,形状为 (B, C)
input_tensor = torch.randn(3, 5)  # 假设批量大小为 3,类别数量为 5

target = torch.LongTensor([1, 0, 2])

# 使用 log_softmax 函数计算对数softmax值
output_tensor = F.log_softmax(input_tensor, dim=1)

# print("Input Tensor:")
# print(input_tensor)

print("\nOutput Tensor (Log-Softmax):")
print(output_tensor)

# 计算 NLL Loss
loss = F.nll_loss(output_tensor, target)
print("NLL Loss:", loss.item())

# 计算交叉熵损失
loss = F.cross_entropy(input_tensor, target)

print("Cross-Entropy Loss:", loss.item())

相关推荐

  1. AI代码目录准备发布教程

    2024-03-27 07:00:05       35 阅读
  2. 面试代码总结

    2024-03-27 07:00:05       42 阅读
  3. 代码题【基础篇】

    2024-03-27 07:00:05       26 阅读
  4. AI代码:请帮我一段kmeans算法python代码

    2024-03-27 07:00:05       36 阅读
  5. c++bitset

    2024-03-27 07:00:05       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-27 07:00:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-27 07:00:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-27 07:00:05       82 阅读
  4. Python语言-面向对象

    2024-03-27 07:00:05       91 阅读

热门阅读

  1. vue 文件预览(docx、.xlsx、pdf)

    2024-03-27 07:00:05       42 阅读
  2. net core 使用 iTextSharp 生成PDF

    2024-03-27 07:00:05       26 阅读
  3. 触发器的工艺结构原理及选型参数总结

    2024-03-27 07:00:05       43 阅读
  4. 决策树介绍

    2024-03-27 07:00:05       37 阅读
  5. 深入学习Spark SQL:处理结构化数据的利器

    2024-03-27 07:00:05       36 阅读
  6. 决策树-计算信息熵

    2024-03-27 07:00:05       35 阅读
  7. 决策树学习心得

    2024-03-27 07:00:05       42 阅读
  8. Stable Diffusion 本地部署教程

    2024-03-27 07:00:05       38 阅读
  9. 压力测试(QPS)及测试工具Locust

    2024-03-27 07:00:05       40 阅读
  10. Spark SizeTrackingAppendOnlyMap 相关源代码分析

    2024-03-27 07:00:05       38 阅读
  11. Stable Diffusion XL之核心基础内容

    2024-03-27 07:00:05       38 阅读
  12. k8s 的资源清单

    2024-03-27 07:00:05       36 阅读