Skip to content

Commit 31422ef

Browse files
committed
pytorch introduction code
1 parent 0a28749 commit 31422ef

File tree

10 files changed

+74
-26
lines changed

10 files changed

+74
-26
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
## [1.0.0] - 2022-02-27
1+
## [1.0.0] - 2022-03-03
22

33
### Changed
44
- detaching TensorFlow from mltu, now mltu is only a collection of utilities for training machine learning models
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Introduction to speech recognition with TensorFlow
2+
## Master the basics of speech recognition with TensorFlow: Learn how to build and train models, implement real-time audio recognition, and develop practical applications
3+
4+
5+
## **Detailed tutorial**:
6+
## [Introduction to speech recognition with TensorFlow](https://pylessons.com/speech-recognition)
7+
8+
<p align="center">
9+
<img src="https://pylessons.com/media/Tutorials/TensorFlow-CAPTCHA-solver/speech-recognition/speech-recognition.png">
10+
</p>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Introduction to speech recognition with TensorFlow
2+
## Master the basics of speech recognition with TensorFlow: Learn how to build and train models, implement real-time audio recognition, and develop practical applications<br><br>
3+
4+
# **Detailed tutorial**:
5+
## [Introduction to PyTorch in a practical way](https://pylessons.com/pytorch-introduction)
6+
7+
<p align="center">
8+
<img src="https://pylessons.com/media/Tutorials/TensorFlow-CAPTCHA-solver/pytorch-introduction/pytorch-introduction.png">
9+
</p>

Tutorials/06_pytorch_introduction/model.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import torch.nn as nn
22
import torch.nn.functional as F
33

4+
# Define the model architecture
45
class Net(nn.Module):
56
def __init__(self):
67
super(Net, self).__init__()
@@ -17,4 +18,5 @@ def forward(self, x):
1718
x = F.relu(self.fc1(x))
1819
x = F.dropout(x, training=self.training)
1920
x = self.fc2(x)
20-
return F.log_softmax(x, dim=1)
21+
x = F.log_softmax(x, dim=1)
22+
return x
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
numpy
2+
opencv-python
3+
tqdm
4+
torch
5+
torchsummary

Tutorials/06_pytorch_introduction/test.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from model import Net
88

9-
path='Datasets/data' # Path where to save the mnist dataset
9+
path='Datasets/mnist' # Path where to save the downloaded mnist dataset
1010
def fetch(url):
1111
if os.path.exists(path) is False:
1212
os.makedirs(path)
@@ -32,21 +32,22 @@ def fetch(url):
3232
network.load_state_dict(torch.load("Models/06_pytorch_introduction/model.pt"))
3333
network.eval() # set to evaluation mode
3434

35-
35+
# loop over test images
3636
for test_image, test_target in zip(test_data, test_targets):
3737

38-
# convert to tensor
38+
# normalize image and convert to tensor
3939
inference_image = torch.from_numpy(test_image).float() / 255.0
4040
inference_image = inference_image.unsqueeze(0).unsqueeze(0)
4141

4242
# predict
4343
output = network(inference_image)
4444
pred = output.argmax(dim=1, keepdim=True)
45+
prediction = str(pred.item())
4546

4647
test_image = cv2.resize(test_image, (400, 400))
47-
cv2.imshow(str(pred.item()), test_image)
48+
cv2.imshow(prediction, test_image)
4849
key = cv2.waitKey(0)
4950
if key == ord('q'): # break on q key
5051
break
51-
52-
cv2.destroyAllWindows()
52+
53+
cv2.destroyAllWindows()

Tutorials/06_pytorch_introduction/train.py

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55
import requests, gzip, os, hashlib
66

77
import torch
8-
import torch.nn.functional as F
8+
import torch.nn as nn
99
import torch.optim as optim
10+
from torchsummary import summary
1011

1112
from model import Net
1213

13-
path='Datasets/data'
14+
# define path to store dataset
15+
path='Datasets/mnist'
1416
def fetch(url):
1517
if os.path.exists(path) is False:
1618
os.makedirs(path)
@@ -33,12 +35,14 @@ def fetch(url):
3335

3436
# uncomment to show images from dataset using OpenCV
3537
# for train_image, train_target in zip(train_data, train_targets):
36-
# train_image = cv2.resize(train_image, (300, 300))
38+
# train_image = cv2.resize(train_image, (400, 400))
3739
# cv2.imshow("Image", train_image)
38-
# cv2.waitKey(0)
39-
# cv2.destroyAllWindows()
40+
# # if Q button break this loop
41+
# if cv2.waitKey(0) & 0xFF == ord('q'):
42+
# break
43+
# cv2.destroyAllWindows()
4044

41-
# define hyperparameters
45+
# define training hyperparameters
4246
n_epochs = 5
4347
batch_size_train = 64
4448
batch_size_test = 64
@@ -56,50 +60,67 @@ def fetch(url):
5660
test_batches = [np.array(test_data[i:i+batch_size_test]) for i in range(0, len(test_data), batch_size_test)]
5761
test_target_batches = [np.array(test_targets[i:i+batch_size_test]) for i in range(0, len(test_targets), batch_size_test)]
5862

59-
# create network and optimizer
63+
# create network
6064
network = Net()
65+
66+
# uncomment to print network summary
67+
summary(network, (1, 28, 28), device="cpu")
68+
69+
# define loss function and optimizer
6170
optimizer = optim.Adam(network.parameters(), lr=learning_rate)
71+
loss_function = nn.CrossEntropyLoss()
6272

6373
# create training loop
6474
def train(epoch):
75+
# set network to training mode
6576
network.train()
6677

6778
loss_sum = 0
79+
# create a progress bar
6880
train_pbar = tqdm(zip(train_batches, train_target_batches), total=len(train_batches))
69-
for data, target in train_pbar:
81+
for index, (data, target) in enumerate(train_pbar, start=1):
7082

7183
# convert data to torch.FloatTensor
7284
data = torch.from_numpy(data).float()
7385
target = torch.from_numpy(target).long()
7486

87+
# zero the parameter gradients
7588
optimizer.zero_grad()
89+
90+
# forward + backward + optimize
7691
output = network(data)
77-
loss = F.nll_loss(output, target)
92+
loss = loss_function(output, target)
7893
loss.backward()
7994
optimizer.step()
8095

96+
# update progress bar with loss value
8197
loss_sum += loss.item()
82-
train_pbar.set_description(f"Epoch {epoch}, loss: {loss_sum / len(train_batches):.4f}")
98+
train_pbar.set_description(f"Epoch {epoch}, loss: {loss_sum / index:.4f}")
8399

84100
# create testing loop
85101
def test(epoch):
102+
# set network to evaluation mode
86103
network.eval()
87104

88-
correct = 0
89-
loss_sum = 0
105+
correct, loss_sum = 0, 0
106+
# create progress bar
90107
val_pbar = tqdm(zip(test_batches, test_target_batches), total=len(test_batches))
91108
with torch.no_grad():
92-
for data, target in val_pbar:
109+
for index, (data, target) in enumerate(val_pbar, start=1):
110+
93111
# convert data to torch.FloatTensor
94112
data = torch.from_numpy(data).float()
95113
target = torch.from_numpy(target).long()
96114

115+
# forward pass
97116
output = network(data)
98-
loss_sum += F.nll_loss(output, target).item() / target.size(0)
117+
118+
# update progress bar with loss and accuracy values
119+
loss_sum += loss_function(output, target).item() / target.size(0)
99120
pred = output.data.max(1, keepdim=True)[1]
100121
correct += pred.eq(target.data.view_as(pred)).sum() / target.size(0)
101122

102-
val_pbar.set_description(f"val_loss: {loss_sum / len(test_batches):.4f}, val_accuracy: {correct / len(test_batches):.4f}")
123+
val_pbar.set_description(f"val_loss: {loss_sum / index:.4f}, val_accuracy: {correct / index:.4f}")
103124

104125
# train and test the model
105126
for epoch in range(1, n_epochs + 1):

mltu/tensorflow/requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
tensorflow<=2.10.1
1+
tensorflow<=2.10.1
2+
tf2onnx

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ tqdm
44
pandas
55
numpy
66
opencv-python
7-
tf2onnx
87
onnxruntime # onnxruntime-gpu for GPU support
98
librosa==0.9.2
109
importlib==1.0.4

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def get_version(initpath: str) -> str:
4141
'gpu': ['onnxruntime-gpu'],
4242
},
4343
python_requires='>=3',
44-
packages = ['mltu'],
44+
packages = ['mltu', 'mltu.utils', 'mltu.torch', 'mltu.tensorflow'],
4545
include_package_data=True,
4646
project_urls={
4747
'Source': 'https://github.com/pythonlessons/mltu/',

0 commit comments

Comments
 (0)