[WIP: Feb2023] TorchSharp Tensorboard #722
Replies: 4 comments
-
Related discussion: PyTorch for Deep Learning: Creating and Deploying Deep Learning Applicationsimport torch
import torch.nn as nn
import torch.utils.data
import torchvision
from functools import partial
from torch import optim
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms |
Beta Was this translation helpful? Give feedback.
-
@GeorgeS2019 -- please file this as an issue instead of a Discussion topic. |
Beta Was this translation helpful? Give feedback.
-
using Torch;
using Torch.Schedulers;
using Torch.Utils;
using Torch.Optim;
using System;
using System.IO;
namespace TensorboardExample
{
class Program
{
static void Main(string[] args)
{
// Define the neural network
var model = new Sequential();
model.Add(new Linear(2, 128));
model.Add(new ReLU());
model.Add(new Linear(128, 1));
// Define the optimizer
var optimizer = new SGD(model.Parameters(), 0.01);
// Define the loss function
var loss = new MSELoss();
// Define the data
var inputs = new Tensor(new[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }, new[] { 5, 2 });
var targets = new Tensor(new[] { 2.0f, 4.0f, 6.0f, 8.0f, 10.0f }, new[] { 5, 1 });
// Train the model
int epochCount = 100;
int logInterval = 10;
int batchSize = inputs.Shape[0];
for (int epoch = 0; epoch < epochCount; epoch++)
{
optimizer.ZeroGrad();
var output = model.Forward(inputs);
var l = loss.Forward(output, targets);
l.Backward();
optimizer.Step();
// Log the histograms of the weights and biases
if (epoch % logInterval == 0)
{
var summaryWriter = new SummaryWriter();
summaryWriter.UseEventFile(Path.Combine(Directory.GetCurrentDirectory(), "runs", "example"));
var linear = model[0] as Linear;
summaryWriter.AddHistogram("weights", linear.Weight, epoch);
summaryWriter.AddHistogram("biases", linear.Bias, epoch);
summaryWriter.Flush();
}
}
// Print the final loss
Console.WriteLine("Loss: " + loss.Forward(model.Forward(inputs), targets).ToScalar());
}
}
}
|
Beta Was this translation helpful? Give feedback.
-
Another example of ChatGPT getting things wrong. Tensorboard histograms are not supported by TorchSharp yet, and when it does, it will follow PyTorch naming conventions rather than standard .NET naming. |
Beta Was this translation helpful? Give feedback.
-
We now have Tensorboard!
PyTorch code
TorchSharp code
add_scalar(tag, scalar_value, global_step=None, walltime=None, new_style=False, double_precision=False)
add_scalars(main_tag, tag_scalar_dict, global_step=None, walltime=None)
add_histogram(tag, values, global_step=None, bins='tensorflow', walltime=None, max_bins=None)
add_image(tag, img_tensor, global_step=None, walltime=None, dataformats='CHW')
add_images(tag, img_tensor, global_step=None, walltime=None, dataformats='NCHW')
more ...
Beta Was this translation helpful? Give feedback.
All reactions