gradio/Test Pytorch.ipynb
2019-04-09 21:06:02 -07:00

19 KiB

In [1]:
%load_ext autoreload
%autoreload 2

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import gradio
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-800f83bb710d> in <module>
      2 get_ipython().run_line_magic('autoreload', '2')
      3 
----> 4 import torch
      5 import torch.nn as nn
      6 import torchvision

ModuleNotFoundError: No module named 'torch'
In [2]:
# Device configuration
device = torch.device('cpu')

# Hyper-parameters 
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 2
batch_size = 100
learning_rate = 0.001

# MNIST dataset 
train_dataset = torchvision.datasets.MNIST(root='../../data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='../../data',train=False, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size,shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-aa6a81b0840f> in <module>
      1 # Device configuration
----> 2 device = torch.device('cpu')
      3 
      4 # Hyper-parameters
      5 input_size = 784

NameError: name 'torch' is not defined
In [3]:
# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size) 
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)  
    
    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

model = NeuralNet(input_size, hidden_size, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)  

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):  
        # Move tensors to the configured device
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-b0dc3fab7f79> in <module>
      1 # Fully connected neural network with one hidden layer
----> 2 class NeuralNet(nn.Module):
      3     def __init__(self, input_size, hidden_size, num_classes):
      4         super(NeuralNet, self).__init__()
      5         self.fc1 = nn.Linear(input_size, hidden_size)

NameError: name 'nn' is not defined
In [4]:
# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-91667d2d5612> in <module>
      1 # Test the model
      2 # In test phase, we don't need to compute gradients (for memory efficiency)
----> 3 with torch.no_grad():
      4     correct = 0
      5     total = 0

NameError: name 'torch' is not defined
In [5]:
value = torch.from_numpy(images.numpy())
print(value.dtype)
value = torch.autograd.Variable(value)
print(value.dtype)
prediction = model(value)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-f12a632f31c3> in <module>
----> 1 value = torch.from_numpy(images.numpy())
      2 print(value.dtype)
      3 value = torch.autograd.Variable(value)
      4 print(value.dtype)
      5 prediction = model(value)

NameError: name 'torch' is not defined
In [6]:
images.numpy().astype('float64').dtype
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-3125682ab905> in <module>
----> 1 images.numpy().astype('float64').dtype

NameError: name 'images' is not defined
In [7]:
prediction.data.numpy().shape
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-ab875561c356> in <module>
----> 1 prediction.data.numpy().shape

NameError: name 'prediction' is not defined
In [8]:
prediction.data.numpy()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-177468ca29d9> in <module>
----> 1 prediction.data.numpy()

NameError: name 'prediction' is not defined
In [9]:
inp = gradio.inputs.Sketchpad(flatten=True, scale=1/255, dtype='float32')
io = gradio.Interface(inputs=inp, outputs="label", model_type="pytorch", model=model)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-bf0f365c764e> in <module>
----> 1 inp = gradio.inputs.Sketchpad(flatten=True, scale=1/255, dtype='float32')
      2 io = gradio.Interface(inputs=inp, outputs="label", model_type="pytorch", model=model)

NameError: name 'gradio' is not defined
In [10]:
io.launch()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-137b131e2f9c> in <module>
----> 1 io.launch()

NameError: name 'io' is not defined
In [11]:
model
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-1f8a688cae5d> in <module>
----> 1 model

NameError: name 'model' is not defined
In [ ]:
 
In [ ]: