美文网首页pytorch
pytorch 中使用 tensorboard,常用 demo

pytorch 中使用 tensorboard,常用 demo

作者: 蓝天白云bubble | 来源:发表于2020-01-30 13:15 被阅读0次

    一、代码 demo

    import torch
    import torch.nn as nn
    import numpy as np
    
    from tensorboardX import SummaryWriter
    
    input_size = 1
    output_size = 1
    num_epochs = 60
    learning_rate = 0.01
    writer = SummaryWriter(comment='Linear')
    x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                        [9.779], [6.182], [7.59], [2.167], [7.042],
                        [10.791], [5.313], [7.997],[3.1]], dtype=np.float32)
    y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                       [3.366], [2.596], [2.53], [1.221], [2.827],
                       [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
    
    model = nn.Linear(input_size, output_size)
    criterion = nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
    
    for epoch in range(num_epochs):
        inputs = torch.from_numpy(x_train)
        targets = torch.from_numpy(y_train)
    
        output = model(inputs)
        loss = criterion(output, targets)
    
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    
        # 将标量值存储到 tensorboard 中
        writer.add_scalar('Train', loss, epoch)
        if (epoch + 1) % 5 == 0:
            print('Epoch {}/{}, loss={:.4f}'.format(epoch + 1, num_epochs, loss.item()))
    
    # 将网络的结构存储到 tensorboard 中
    writer.add_graph(model, (inputs,))
    
    predicated = model(torch.from_numpy(x_train)).detach().numpy()
    writer.close()
    

    二、查看 tensorboard

    在 tensorboard 生成的 runs 文件夹同级目录下执行命令:

    tensorboard --logdir=runs
    

    然后访问相应的链接即可。

    相关文章

      网友评论

        本文标题:pytorch 中使用 tensorboard,常用 demo

        本文链接:https://www.haomeiwen.com/subject/piyithtx.html