Skip to content

Commit a024120

Browse files
cassiebreviusubramen
authored andcommitted
updated quickstart to class model (pytorch#30)
* fix build model * updated quickstart to class model
1 parent 74be97c commit a024120

File tree

2 files changed

+36
-22
lines changed

2 files changed

+36
-22
lines changed

beginner_source/quickstart/build_model_tutorial.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
###############################################
77
# The data has been loaded and transformed we can now build the model.
88
# We will leverage `torch.nn <https://pytorch.org/docs/stable/nn.html>`_
9-
# predefined layers that Pytorch has that can simplify our code.
9+
10+
# predefined layers that PyTorch has that can simplify our code.
1011
#
1112
# In the below example, for our FashionMNIT image dataset, we are using a `Sequential`
1213
# container from class `torch.nn. Sequential <https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html>`_
@@ -53,18 +54,26 @@
5354
# --------------------------
5455
#
5556

56-
class NeuralNework(nn.Module):
57-
def __init__(self, x):
58-
super(NeuralNework, self).__init__()
57+
58+
class NeuralNetwork(nn.Module):
59+
def __init__(self):
60+
super(NeuralNetwork, self).__init__()
61+
self.flatten = nn.Flatten()
5962
self.layer1 = nn.Linear(28*28, 512)
6063
self.layer2 = nn.Linear(512, 512)
6164
self.output = nn.Linear(512, 10)
6265

6366
def forward(self, x):
67+
68+
x = self.flatten(x)
6469
x = F.relu(self.layer1(x))
6570
x = F.relu(self.layer2(x))
6671
x = self.output(x)
6772
return F.softmax(x, dim=1)
73+
model = NeuralNetwork().to(device)
74+
75+
print(model)
76+
6877

6978
#############################################
7079
# Get Device for Training
@@ -90,8 +99,6 @@ def forward(self, x):
9099
#
91100
# From the docs:
92101
# ``torch.nn.Flatten(start_dim: int = 1, end_dim: int = -1)``
93-
#
94-
95102
# Here is an example using one of the training_data set items:
96103
tensor = training_data[0][0]
97104
print(tensor.size())
@@ -112,6 +119,7 @@ def forward(self, x):
112119
#
113120
# Now that we have flattened our tensor dimension we will apply a linear layer transform that will calculate/learn the weights and the bias.
114121
#
122+
115123
# From the docs:
116124
#
117125
# ``torch.nn.Linear(in_features: int, out_features: int, bias: bool = True)``

beginner_source/quickstart_tutorial.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,10 @@
1313
#
1414
# PyTorch has two basic data primitives: ``DataSet`` and ``DataLoader``.
1515
# The `torchvision.datasets` ``DataSet`` object includes a ``transforms`` mechanism to
16-
# modify data in-place. Below is an example of how to load that data from the Pytorch open datasets and transform the data to a normalized tensor.
17-
16+
# modify data in-place. Below is an example of how to load that data from the PyTorch open datasets and transform the data to a normalized tensor.
1817
# This example is using the `torchvision.datasets` which is a subclass from the primitive `torch.utils.data.Dataset`. Note that the primitive dataset doesnt have the built in transforms param like the built in dataset in `torchvision.datasets.`
1918
#
20-
# To see more examples and details of how to work with Tensors, Datasets, DataLoaders and Transforms in Pytoch with this example checkout these resources:
19+
# To see more examples and details of how to work with Tensors, Datasets, DataLoaders and Transforms in PyTorch with this example checkout these resources:
2120
#
2221
# - `Tensors <quickstart/tensor_tutorial.html>`_
2322
# - `DataSet and DataLoader <quickstart/data_quickstart_tutorial.html>`_
@@ -29,6 +28,7 @@
2928
import matplotlib.pyplot as plt
3029
from torch.utils.data import DataLoader
3130
from torchvision import datasets, transforms
31+
import torch.nn.functional as F
3232

3333
classes = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
3434

@@ -51,26 +51,32 @@
5151
train_dataloader = DataLoader(training_data, batch_size=batch_size, num_workers=0, pin_memory=True)
5252
test_dataloader = DataLoader(test_data, batch_size=batch_size, num_workers=0, pin_memory=True)
5353

54+
################################
5455
# Creating Models
5556
# ---------------
5657
#
5758
# There are two ways of creating models: in-line or as a class. This
58-
# quickstart will consider an in-line definition. For more examples checkout `building the model <quickstart/build_model_tutorial.html>`_.
59+
# quickstart will consider a class definition. For more examples checkout `building the model <quickstart/build_model_tutorial.html>`_.
5960

6061
device = 'cuda' if torch.cuda.is_available() else 'cpu'
6162
print('Using {} device'.format(device))
6263

63-
# in-line model
64-
65-
model = nn.Sequential(
66-
nn.Flatten(),
67-
nn.Linear(28*28, 512),
68-
nn.ReLU(),
69-
nn.Linear(512, 512),
70-
nn.ReLU(),
71-
nn.Linear(512, len(classes)),
72-
nn.Softmax(dim=1)
73-
).to(device)
64+
# Define model
65+
class NeuralNetwork(nn.Module):
66+
def __init__(self):
67+
super(NeuralNetwork, self).__init__()
68+
self.flatten = nn.Flatten()
69+
self.layer1 = nn.Linear(28*28, 512)
70+
self.layer2 = nn.Linear(512, 512)
71+
self.output = nn.Linear(512, 10)
72+
73+
def forward(self, x):
74+
x = self.flatten(x)
75+
x = F.relu(self.layer1(x))
76+
x = F.relu(self.layer2(x))
77+
x = self.output(x)
78+
return F.softmax(x, dim=1)
79+
model = NeuralNetwork().to(device)
7480

7581
print(model)
7682

@@ -193,7 +199,7 @@ def test(dataloader, model):
193199
print(f'Predicted: "{predicted}", Actual: "{actual}"')
194200

195201
##################################################################
196-
# Pytorch Quickstart Topics
202+
# PyTorch Quickstart Topics
197203
# ----------------------------------------
198204
# | `Tensors <quickstart/tensor_tutorial.html>`_
199205
# | `DataSets and DataLoaders <quickstart/data_quickstart_tutorial.html>`_

0 commit comments

Comments
 (0)