preamble
This article focuses on the use of tensorboard.
tensorboard is a visualization that supports artificial intelligence learning.
The official address of tensorboard:/tensorboard
The content of this article is from the video tutorial 16 lessons, I personally feel that for tensorboard talk very good.
Use of Tensorboard
Use the code below:
import torch
import as nn
import torchvision
import as transforms
import as plt
import sys
import as F
from import SummaryWriter
# pip install tensorboard 安装 tensorboard
# 启动 tensorboard 启动成功的话,The address ishttp://localhost:6006/
# logdirbe tantamount to SummaryWriter('runs/mnist1')input address
# tensorboard --logdir=C:\Project\python_test\github\PythonTest\PythonTest\PythonTest\pytorchTutorial\runs
# tensorboardofficial address:/tensorboard
############## TENSORBOARD ########################
writer = SummaryWriter('runs/mnist1')
###################################################
# Device configuration
device = ('cuda' if .is_available() else 'cpu')
# Hyper-parameters
input_size = 784 # 28x28
hidden_size = 500
num_classes = 10
num_epochs = 1
batch_size = 64
learning_rate = 0.001
# MNIST dataset
train_dataset = (root='./data',
train=True,
transform=(),
download=True)
test_dataset = (root='./data',
train=False,
transform=())
# Data loader
train_loader = (dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = (dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
examples = iter(test_loader)
example_data, example_targets = next(examples)
for i in range(6):
(2,3,i+1)
(example_data[i][0], cmap='gray')
#()
############## TENSORBOARD ########################
img_grid = .make_grid(example_data)
writer.add_image('mnist_images', img_grid)
#()
#()
###################################################
# Fully connected neural network with one hidden layer
class NeuralNet():
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.input_size = input_size
self.l1 = (input_size, hidden_size)
= ()
self.l2 = (hidden_size, num_classes)
def forward(self, x):
out = self.l1(x)
out = (out)
out = self.l2(out)
# no activation and no softmax at the end
return out
model = NeuralNet(input_size, hidden_size, num_classes).to(device)
# Loss and optimizer
criterion = ()
optimizer = ((), lr=learning_rate)
############## TENSORBOARD ########################
writer.add_graph(model, example_data.reshape(-1, 28*28).to(device))
#()
#()
###################################################
# Train the model
running_loss = 0.0
running_correct = 0
n_total_steps = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# origin shape: [100, 1, 28, 28]
# resized: [100, 784]
images = (-1, 28*28).to(device)
labels = (device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
()
()
running_loss += ()
_, predicted = (, 1)
running_correct += (predicted == labels).sum().item()
if (i+1) % 100 == 0:
print (f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {():.4f}')
############## TENSORBOARD ########################
writer.add_scalar('training loss', running_loss / 100, epoch * n_total_steps + i)
running_accuracy = running_correct / 100 / (0)
writer.add_scalar('accuracy', running_accuracy, epoch * n_total_steps + i)
running_correct = 0
running_loss = 0.0
###################################################
# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
class_labels = []
class_preds = []
with torch.no_grad():
n_correct = 0
n_samples = 0
for images, labels in test_loader:
images = (-1, 28*28).to(device)
labels = (device)
outputs = model(images)
# max returns (value ,index)
values, predicted = (, 1)
n_samples += (0)
n_correct += (predicted == labels).sum().item()
class_probs_batch = [(output, dim=0) for output in outputs]
class_preds.append(class_probs_batch)
class_labels.append(labels)
# 10000, 10, and 10000, 1
# stack concatenates tensors along a new dimension
# cat concatenates tensors in the given dimension
class_preds = ([(batch) for batch in class_preds])
class_labels = (class_labels)
acc = 100.0 * n_correct / n_samples
print(f'Accuracy of the network on the 10000 test images: {acc} %')
############## TENSORBOARD ########################
classes = range(10)
for i in classes:
labels_i = class_labels == i
preds_i = class_preds[:, i]
writer.add_pr_curve(str(i), labels_i, preds_i, global_step=0)
()
###################################################
(of a computer) runhttp://localhost:6006 , you can get the following graph, and you can analyze the learning results based on the curves and other information in the graph.
Portal:
Learning Artificial Intelligence from Zero - Python-Pytorch Learning - Full Episode
Note: This post is original, please contact the author for authorization and attribution for any form of reproduction!
If you think this article is still good, please click [Recommend] below, thank you very much!
/kiba/p/18601612