【发布时间】:2020-05-26 23:58:38
【问题描述】:
我知道这是一个原始问题,但是我应该在我的代码中添加什么来输出除了损失之外的神经网络的训练准确性,我查看了 PyTorch 教程,他们展示了如何在图像分类,但我不知道如何在我的简单 XOR 求解 NN 中做到这一点,下面是代码:
# Step 1: importing our dependencies
import torch
from torch.autograd import Variable
import numpy as np
# Our data
x = Variable(torch.Tensor([[0, 0, 1], [0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 0, 0],
[1, 1, 1], [0, 0, 0]]))
y = Variable(torch.Tensor([[0], [1], [1], [1], [1], [0], [0]]))
# Step 2: building our class model
class NeuralNetwork(torch.nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.linear_ij = torch.nn.Linear(3, 4)
self.linear_jk = torch.nn.Linear(4, 1)
def forward(self, x):
matmul = self.linear_ij(x)
activation = torch.sigmoid(matmul)
matmul = self.linear_jk(activation)
prediction = torch.sigmoid(matmul)
return prediction
# Our model
model = NeuralNetwork()
# Constructing the loss function and the optimization algorithm
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=1)
# Step 3: the training process
for epoch in range(10000):
prediction = model(x)
loss = criterion(prediction, y)
if epoch % 1000 == 0 or epoch == 10000 - 1:
print("epoch ", epoch, ",", "loss: ", loss.item())
# Backpropagation process
optimizer.zero_grad()
loss.backward()
optimizer.step()
这就是它作为输出提供的内容:
epoch 0 , loss: 0.6983293294906616
epoch 1000 , loss: 0.015215665102005005
epoch 2000 , loss: 0.0048239342868328094
epoch 3000 , loss: 0.00280318153090775
epoch 4000 , loss: 0.001963752554729581
epoch 5000 , loss: 0.0015071843517944217
epoch 6000 , loss: 0.0012211233843117952
epoch 7000 , loss: 0.0010254186345264316
epoch 8000 , loss: 0.000883264874573797
epoch 9000 , loss: 0.0007753585232421756
epoch 9999 , loss: 0.0006908221403136849
至于测试:
# Testing our model
model.eval()
x_test = Variable(torch.Tensor([[1, 1, 0], [0, 0, 1], [0, 1, 1]]))
y_test = Variable(torch.Tensor([[0], [0], [1]]))
y_pred = model(x_test)
print(model(x_test))
输出:
tensor([[0.0026],
[0.0011],
[0.9991]], grad_fn=<SigmoidBackward>)
【问题讨论】:
标签: python python-3.x neural-network pytorch