Skip to content

Commit b5157f8

Browse files
authored
fix sample so it works on the GPU (#505)
1 parent 673410d commit b5157f8

File tree

1 file changed

+37
-40
lines changed
  • Samples/Tutorial Samples/PyTorch Image Classification/PyTorchTraining - Image Classification

1 file changed

+37
-40
lines changed

Samples/Tutorial Samples/PyTorch Image Classification/PyTorchTraining - Image Classification/PyTorchTraining.py

Lines changed: 37 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,21 @@
2121

2222
# CIFAR10 dataset consists of 50K training images. We define the batch size of 10 to load 5,000 batches of images.
2323
batch_size = 10
24-
number_of_labels = 10
24+
number_of_labels = 10
2525

26-
# Create an instance for training.
27-
# When we run this code for the first time, the CIFAR10 train dataset will be downloaded locally.
26+
# Create an instance for training.
27+
# When we run this code for the first time, the CIFAR10 train dataset will be downloaded locally.
2828
train_set =CIFAR10(root="./data",train=True,transform=transformations,download=True)
2929

3030
# Create a loader for the training set which will read the data within batch size and put into memory.
3131
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=0)
3232
print("The number of images in a training set is: ", len(train_loader)*batch_size)
3333

3434
# Create an instance for testing, note that train is set to False.
35-
# When we run this code for the first time, the CIFAR10 test dataset will be downloaded locally.
35+
# When we run this code for the first time, the CIFAR10 test dataset will be downloaded locally.
3636
test_set = CIFAR10(root="./data", train=False, transform=transformations, download=True)
3737

38-
# Create a loader for the test set which will read the data within batch size and put into memory.
38+
# Create a loader for the test set which will read the data within batch size and put into memory.
3939
# Note that both shuffle is set to false for the test loader.
4040
test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=0)
4141
print("The number of images in a test set is: ", len(test_loader)*batch_size)
@@ -49,12 +49,12 @@
4949
class Network(nn.Module):
5050
def __init__(self):
5151
super(Network, self).__init__()
52-
52+
5353
self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=1)
5454
self.bn1 = nn.BatchNorm2d(12)
5555
self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=1)
5656
self.bn2 = nn.BatchNorm2d(12)
57-
57+
5858
self.pool = nn.MaxPool2d(2,2)
5959

6060
self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=1)
@@ -75,8 +75,9 @@ def forward(self, input):
7575

7676
return output
7777

78-
# Instantiate a neural network model
78+
# Instantiate a neural network model
7979
model = Network()
80+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
8081

8182
# Define the loss function with Classification Cross-Entropy loss and an optimizer with Adam optimizer
8283
loss_fn = nn.CrossEntropyLoss()
@@ -89,34 +90,34 @@ def saveModel():
8990

9091
# Function to test the model with the test dataset and print the accuracy for the test images
9192
def testAccuracy():
92-
93+
9394
model.eval()
9495
accuracy = 0.0
9596
total = 0.0
96-
97+
9798
with torch.no_grad():
98-
99+
99100
for data in test_loader:
100101
images, labels = data
101102
# Run the model on the test set to predict labels
102-
outputs = model(images)
103+
outputs = model(images.to(device))
104+
outputs = outputs.cpu()
103105
# The label with the highest energy will be our prediction
104106
_, predicted = torch.max(outputs.data, 1)
105107
total += labels.size(0)
106108
accuracy += (predicted == labels).sum().item()
107-
109+
108110
# Compute the accuracy over all test images
109111
accuracy = (100 * accuracy / total)
110-
return(accuracy)
112+
return(accuracy)
111113

112114

113115
# Training function. We simply have to loop over our data iterator, and feed the inputs to the network and optimize.
114116
def train(num_epochs):
115-
117+
116118
best_accuracy = 0.0
117119

118120
# Define your execution device
119-
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
120121
print("The model will be running on", device, "device")
121122
# Convert model parameters and buffers to CPU or Cuda
122123
model.to(device)
@@ -125,7 +126,7 @@ def train(num_epochs):
125126
running_loss = 0.0
126127

127128
for i, (images, labels) in enumerate(train_loader, 0):
128-
129+
129130
# wrap the inputs in Variable
130131
images = Variable(images.to(device))
131132
labels = Variable(labels.to(device))
@@ -143,8 +144,8 @@ def train(num_epochs):
143144

144145
# Let's print statistics for every 1,000 images
145146
running_loss += loss.item() # extract the loss value
146-
if i % 1000 == 999:
147-
# print every 1000 (twice per epoch)
147+
if i % 1000 == 999:
148+
# print every 1000 (twice per epoch)
148149
print('[%d, %5d] loss: %.3f' %
149150
(epoch + 1, i + 1, running_loss / 1000))
150151
# zero the loss
@@ -153,7 +154,7 @@ def train(num_epochs):
153154
# Compute and print the average accuracy of this epoch when tested over all 10000 test images
154155
accuracy = testAccuracy()
155156
print('For epoch', epoch+1,'the test accuracy over the whole test set is %d %%' % (accuracy))
156-
157+
157158
# We want to save the model if the accuracy is the best
158159
if accuracy > best_accuracy:
159160
saveModel()
@@ -170,37 +171,37 @@ def imageshow(img):
170171

171172
# Function to test the model with a batch of images and show the labels predictions
172173
def testBatch():
173-
# get batch of images from the test DataLoader
174+
# get batch of images from the test DataLoader
174175
images, labels = next(iter(test_loader))
175176

176177
# show all images as one image grid
177178
imageshow(torchvision.utils.make_grid(images))
178-
179-
# Show the real labels on the screen
180-
print('Real labels: ', ' '.join('%5s' % classes[labels[j]]
179+
180+
# Show the real labels on the screen
181+
print('Real labels: ', ' '.join('%5s' % classes[labels[j]]
181182
for j in range(batch_size)))
182-
183+
183184
# Let's see what if the model identifiers the labels of those example
184185
outputs = model(images)
185-
186+
186187
# We got the probability for every 10 labels. The highest (max) probability should be correct label
187188
_, predicted = torch.max(outputs, 1)
188-
189+
189190
# Let's show the predicted labels on the screen to compare with the real ones
190-
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
191+
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
191192
for j in range(batch_size)))
192-
193+
193194

194195
#Function to Convert to ONNX
195196
def Convert_ONNX():
196-
197+
197198
# set the model to inference mode
198199
model.eval()
199-
200-
# Let's create a dummy input tensor
200+
201+
# Let's create a dummy input tensor
201202
dummy_input = torch.randn(1, 3, 32, 32, requires_grad=True)
202203

203-
# Export the model
204+
# Export the model
204205
torch.onnx.export(model, # model being run
205206
dummy_input, # model input (or a tuple for multiple inputs)
206207
"ImageClassifier.onnx", # where to save the model (can be a file or file-like object)
@@ -234,17 +235,17 @@ def testClassess():
234235
print('Accuracy of %5s : %2d %%' % (
235236
classes[i], 100 * class_correct[i] / class_total[i]))
236237

237-
238+
238239

239240
if __name__ == "__main__":
240-
241+
241242
# Let's build our model
242243
train(5)
243244
print('Finished Training')
244245

245246
# Test which classes performed well
246247
testAccuracy()
247-
248+
248249
# Let's load the model we just created and test the accuracy per label
249250
model = Network()
250251
path = "myFirstModel.pth"
@@ -257,7 +258,3 @@ def testClassess():
257258

258259
# Conversion to ONNX
259260
Convert_ONNX()
260-
261-
262-
263-

0 commit comments

Comments
 (0)