Skip to content

Commit a2ee927

Browse files
2 parents cb19107 + 3776289 commit a2ee927

File tree

6 files changed

+106
-133
lines changed

6 files changed

+106
-133
lines changed

ML/Pytorch/Basics/pytorch_rnn_gru_lstm.py

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,14 @@
88

99
# Imports
1010
import torch
11-
import torchvision
12-
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions
13-
import torch.optim as optim # For all Optimization algorithms, SGD, Adam, etc.
14-
import torch.nn.functional as F # All functions that don't have any parameters
15-
from torch.utils.data import (
16-
DataLoader,
17-
) # Gives easier dataset managment and creates mini batches
18-
import torchvision.datasets as datasets # Has standard datasets we can import in a nice way
19-
import torchvision.transforms as transforms # Transformations we can perform on our dataset
11+
import torchvision # torch package for vision related things
12+
import torch.nn.functional as F # Parameterless functions, like (some) activation functions
13+
import torchvision.datasets as datasets # Standard datasets
14+
import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation
15+
from torch import optim # For optimizers like SGD, Adam, etc.
16+
from torch import nn # All neural network modules
17+
from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc.
18+
from tqdm import tqdm # For a nice progress bar!
2019

2120
# Set device
2221
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -29,7 +28,7 @@
2928
sequence_length = 28
3029
learning_rate = 0.005
3130
batch_size = 64
32-
num_epochs = 2
31+
num_epochs = 3
3332

3433
# Recurrent neural network (many-to-one)
3534
class RNN(nn.Module):
@@ -101,18 +100,12 @@ def forward(self, x):
101100

102101

103102
# Load Data
104-
train_dataset = datasets.MNIST(
105-
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
106-
)
107-
108-
test_dataset = datasets.MNIST(
109-
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
110-
)
111-
103+
train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True)
104+
test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True)
112105
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
113106
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)
114107

115-
# Initialize network
108+
# Initialize network (try out just using simple RNN, or GRU, and then compare with LSTM)
116109
model = RNN_LSTM(input_size, hidden_size, num_layers, num_classes).to(device)
117110

118111
# Loss and optimizer
@@ -121,7 +114,7 @@ def forward(self, x):
121114

122115
# Train Network
123116
for epoch in range(num_epochs):
124-
for batch_idx, (data, targets) in enumerate(train_loader):
117+
for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
125118
# Get data to cuda if possible
126119
data = data.to(device=device).squeeze(1)
127120
targets = targets.to(device=device)
@@ -134,16 +127,11 @@ def forward(self, x):
134127
optimizer.zero_grad()
135128
loss.backward()
136129

137-
# gradient descent or adam step
130+
# gradient descent update step/adam step
138131
optimizer.step()
139132

140133
# Check accuracy on training & test to see how good our model
141134
def check_accuracy(loader, model):
142-
if loader.dataset.train:
143-
print("Checking accuracy on training data")
144-
else:
145-
print("Checking accuracy on test data")
146-
147135
num_correct = 0
148136
num_samples = 0
149137

@@ -160,13 +148,10 @@ def check_accuracy(loader, model):
160148
num_correct += (predictions == y).sum()
161149
num_samples += predictions.size(0)
162150

163-
print(
164-
f"Got {num_correct} / {num_samples} with \
165-
accuracy {float(num_correct)/float(num_samples)*100:.2f}"
166-
)
167-
# Set model back to train
151+
# Toggle model back to train
168152
model.train()
153+
return num_correct / num_samples
169154

170155

171-
check_accuracy(train_loader, model)
172-
check_accuracy(test_loader, model)
156+
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:2f}")
157+
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
Lines changed: 26 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,33 @@
11
"""
2-
Example code of a simple CNN network training on MNIST dataset.
3-
The code is intended to show how to create a CNN network as well
4-
as how to initialize loss, optimizer, etc. in a simple way to get
5-
training to work with function that checks accuracy as well.
2+
A simple walkthrough of how to code a convolutional neural network (CNN)
3+
using the PyTorch library. For demonstration we train it on the very
4+
common MNIST dataset of handwritten digits. In this code we go through
5+
how to create the network as well as initialize a loss function, optimizer,
6+
check accuracy and more.
67
7-
Video explanation: https://youtu.be/wnK3uWv_WkU
8-
Got any questions leave a comment on youtube :)
9-
10-
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
11-
* 2020-04-08 Initial coding
8+
Programmed by Aladdin Persson
9+
* 2020-04-08: Initial coding
10+
* 2021-03-24: More detailed comments and small revision of the code
1211
1312
"""
1413

1514
# Imports
1615
import torch
17-
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions
18-
import torch.optim as optim # For all Optimization algorithms, SGD, Adam, etc.
19-
import torch.nn.functional as F # All functions that don't have any parameters
20-
from torch.utils.data import (
21-
DataLoader,
22-
) # Gives easier dataset managment and creates mini batches
23-
import torchvision.datasets as datasets # Has standard datasets we can import in a nice way
24-
import torchvision.transforms as transforms # Transformations we can perform on our dataset
16+
import torchvision # torch package for vision related things
17+
import torch.nn.functional as F # Parameterless functions, like (some) activation functions
18+
import torchvision.datasets as datasets # Standard datasets
19+
import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation
20+
from torch import optim # For optimizers like SGD, Adam, etc.
21+
from torch import nn # All neural network modules
22+
from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc.
23+
from tqdm import tqdm # For nice progress bar!
2524

2625
# Simple CNN
2726
class CNN(nn.Module):
2827
def __init__(self, in_channels=1, num_classes=10):
2928
super(CNN, self).__init__()
3029
self.conv1 = nn.Conv2d(
31-
in_channels=1,
30+
in_channels=in_channels,
3231
out_channels=8,
3332
kernel_size=(3, 3),
3433
stride=(1, 1),
@@ -51,40 +50,35 @@ def forward(self, x):
5150
x = self.pool(x)
5251
x = x.reshape(x.shape[0], -1)
5352
x = self.fc1(x)
54-
5553
return x
5654

5755

5856
# Set device
5957
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
6058

6159
# Hyperparameters
62-
in_channel = 1
60+
in_channels = 1
6361
num_classes = 10
6462
learning_rate = 0.001
6563
batch_size = 64
66-
num_epochs = 5
64+
num_epochs = 3
6765

6866
# Load Data
69-
train_dataset = datasets.MNIST(
70-
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
71-
)
67+
train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True)
68+
test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True)
7269
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
73-
test_dataset = datasets.MNIST(
74-
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
75-
)
7670
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)
7771

7872
# Initialize network
79-
model = CNN().to(device)
73+
model = CNN(in_channels=in_channels, num_classes=num_classes).to(device)
8074

8175
# Loss and optimizer
8276
criterion = nn.CrossEntropyLoss()
8377
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
8478

8579
# Train Network
8680
for epoch in range(num_epochs):
87-
for batch_idx, (data, targets) in enumerate(train_loader):
81+
for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
8882
# Get data to cuda if possible
8983
data = data.to(device=device)
9084
targets = targets.to(device=device)
@@ -101,14 +95,7 @@ def forward(self, x):
10195
optimizer.step()
10296

10397
# Check accuracy on training & test to see how good our model
104-
105-
10698
def check_accuracy(loader, model):
107-
if loader.dataset.train:
108-
print("Checking accuracy on training data")
109-
else:
110-
print("Checking accuracy on test data")
111-
11299
num_correct = 0
113100
num_samples = 0
114101
model.eval()
@@ -123,12 +110,10 @@ def check_accuracy(loader, model):
123110
num_correct += (predictions == y).sum()
124111
num_samples += predictions.size(0)
125112

126-
print(
127-
f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}"
128-
)
129113

130114
model.train()
115+
return num_correct/num_samples
131116

132117

133-
check_accuracy(train_loader, model)
134-
check_accuracy(test_loader, model)
118+
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
119+
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,69 @@
11
"""
2-
Working code of a simple Fully Connected (FC) network training on MNIST dataset.
3-
The code is intended to show how to create a FC network as well
4-
as how to initialize loss, optimizer, etc. in a simple way to get
5-
training to work with function that checks accuracy as well.
2+
A simple walkthrough of how to code a fully connected neural network
3+
using the PyTorch library. For demonstration we train it on the very
4+
common MNIST dataset of handwritten digits. In this code we go through
5+
how to create the network as well as initialize a loss function, optimizer,
6+
check accuracy and more.
67
7-
Video explanation: https://youtu.be/Jy4wM2X21u0
8-
Got any questions leave a comment on youtube :)
9-
10-
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
11-
* 2020-04-08 Initial coding
8+
Programmed by Aladdin Persson
9+
* 2020-04-08: Initial coding
10+
* 2021-03-24: Added more detailed comments also removed part of
11+
check_accuracy which would only work specifically on MNIST.
1212
1313
"""
1414

1515
# Imports
1616
import torch
17-
import torchvision
18-
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions
19-
import torch.optim as optim # For all Optimization algorithms, SGD, Adam, etc.
20-
import torch.nn.functional as F # All functions that don't have any parameters
21-
from torch.utils.data import (
22-
DataLoader,
23-
) # Gives easier dataset managment and creates mini batches
24-
import torchvision.datasets as datasets # Has standard datasets we can import in a nice way
25-
import torchvision.transforms as transforms # Transformations we can perform on our dataset
26-
27-
# Create Fully Connected Network
17+
import torchvision # torch package for vision related things
18+
import torch.nn.functional as F # Parameterless functions, like (some) activation functions
19+
import torchvision.datasets as datasets # Standard datasets
20+
import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation
21+
from torch import optim # For optimizers like SGD, Adam, etc.
22+
from torch import nn # All neural network modules
23+
from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc.
24+
from tqdm import tqdm # For nice progress bar!
25+
26+
# Here we create our simple neural network. For more details here we are subclassing and
27+
# inheriting from nn.Module, this is the most general way to create your networks and
28+
# allows for more flexibility. I encourage you to also check out nn.Sequential which
29+
# would be easier to use in this scenario but I wanted to show you something that
30+
# "always" works.
2831
class NN(nn.Module):
2932
def __init__(self, input_size, num_classes):
3033
super(NN, self).__init__()
34+
# Our first linear layer take input_size, in this case 784 nodes to 50
35+
# and our second linear layer takes 50 to the num_classes we have, in
36+
# this case 10.
3137
self.fc1 = nn.Linear(input_size, 50)
3238
self.fc2 = nn.Linear(50, num_classes)
3339

3440
def forward(self, x):
41+
"""
42+
x here is the mnist images and we run it through fc1, fc2 that we created above.
43+
we also add a ReLU activation function in between and for that (since it has no parameters)
44+
I recommend using nn.functional (F)
45+
"""
46+
3547
x = F.relu(self.fc1(x))
3648
x = self.fc2(x)
3749
return x
3850

3951

40-
# Set device
52+
# Set device cuda for GPU if it's available otherwise run on the CPU
4153
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
4254

43-
# Hyperparameters
55+
# Hyperparameters of our neural network which depends on the dataset, and
56+
# also just experimenting to see what works well (learning rate for example).
4457
input_size = 784
4558
num_classes = 10
4659
learning_rate = 0.001
4760
batch_size = 64
48-
num_epochs = 1
61+
num_epochs = 3
4962

50-
# Load Data
51-
train_dataset = datasets.MNIST(
52-
root="dataset/", train=True, transform=transforms.ToTensor(), download=True
53-
)
63+
# Load Training and Test data
64+
train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True)
65+
test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True)
5466
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
55-
test_dataset = datasets.MNIST(
56-
root="dataset/", train=False, transform=transforms.ToTensor(), download=True
57-
)
5867
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)
5968

6069
# Initialize network
@@ -66,7 +75,7 @@ def forward(self, x):
6675

6776
# Train Network
6877
for epoch in range(num_epochs):
69-
for batch_idx, (data, targets) in enumerate(train_loader):
78+
for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
7079
# Get data to cuda if possible
7180
data = data.to(device=device)
7281
targets = targets.to(device=device)
@@ -85,15 +94,9 @@ def forward(self, x):
8594
# gradient descent or adam step
8695
optimizer.step()
8796

88-
# Check accuracy on training & test to see how good our model
89-
9097

98+
# Check accuracy on training & test to see how good our model
9199
def check_accuracy(loader, model):
92-
if loader.dataset.train:
93-
print("Checking accuracy on training data")
94-
else:
95-
print("Checking accuracy on test data")
96-
97100
num_correct = 0
98101
num_samples = 0
99102
model.eval()
@@ -109,12 +112,9 @@ def check_accuracy(loader, model):
109112
num_correct += (predictions == y).sum()
110113
num_samples += predictions.size(0)
111114

112-
print(
113-
f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}"
114-
)
115-
116115
model.train()
116+
return num_correct/num_samples
117117

118118

119-
check_accuracy(train_loader, model)
120-
check_accuracy(test_loader, model)
119+
print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
120+
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")

ML/Pytorch/Basics/pytorch_tensorbasics.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
between different types (int, float etc) and how to convert a tensor to an
1212
numpy array and vice-versa.
1313
14+
Programmed by Aladdin Persson
15+
* 2020-06-27: Initial coding
16+
1417
"""
1518

1619
import torch

ML/Pytorch/CNN_architectures/pytorch_inceptionet.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
# Imports
1313
import torch
14-
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions
14+
from torch import nn
1515

1616

1717
class GoogLeNet(nn.Module):

0 commit comments

Comments
 (0)