Skip to content

Commit 78c6afe

Browse files
committed
Update tutorials for pytorch 0.4.0
1 parent 9087fe6 commit 78c6afe

File tree

40 files changed

+44263
-0
lines changed

40 files changed

+44263
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import torch
2+
import torch.nn as nn
3+
import torchvision
4+
import torchvision.transforms as transforms
5+
6+
7+
# Device configuration
8+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9+
10+
# Hyper-parameters
11+
input_size = 784
12+
hidden_size = 500
13+
num_classes = 10
14+
num_epochs = 5
15+
batch_size = 100
16+
learning_rate = 0.001
17+
18+
# MNIST dataset
19+
train_dataset = torchvision.datasets.MNIST(root='../../data',
20+
train=True,
21+
transform=transforms.ToTensor(),
22+
download=True)
23+
24+
test_dataset = torchvision.datasets.MNIST(root='../../data',
25+
train=False,
26+
transform=transforms.ToTensor())
27+
28+
# Data loader
29+
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
30+
batch_size=batch_size,
31+
shuffle=True)
32+
33+
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
34+
batch_size=batch_size,
35+
shuffle=False)
36+
37+
# Fully connected neural network with one hidden layer
38+
class NeuralNet(nn.Module):
39+
def __init__(self, input_size, hidden_size, num_classes):
40+
super(NeuralNet, self).__init__()
41+
self.fc1 = nn.Linear(input_size, hidden_size)
42+
self.relu = nn.ReLU()
43+
self.fc2 = nn.Linear(hidden_size, num_classes)
44+
45+
def forward(self, x):
46+
out = self.fc1(x)
47+
out = self.relu(out)
48+
out = self.fc2(out)
49+
return out
50+
51+
model = NeuralNet(input_size, hidden_size, num_classes).to(device)
52+
53+
# Loss and optimizer
54+
criterion = nn.CrossEntropyLoss()
55+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
56+
57+
# Train the model
58+
total_step = len(train_loader)
59+
for epoch in range(num_epochs):
60+
for i, (images, labels) in enumerate(train_loader):
61+
# Move tensors to the configured device
62+
images = images.reshape(-1, 28*28).to(device)
63+
labels = labels.to(device)
64+
65+
# Forward pass
66+
outputs = model(images)
67+
loss = criterion(outputs, labels)
68+
69+
# Backward and optimize
70+
optimizer.zero_grad()
71+
loss.backward()
72+
optimizer.step()
73+
74+
if (i+1) % 100 == 0:
75+
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
76+
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
77+
78+
# Test the model
79+
# In test phase, we don't need to compute gradients (for memory efficiency)
80+
with torch.no_grad():
81+
correct = 0
82+
total = 0
83+
for images, labels in test_loader:
84+
images = images.reshape(-1, 28*28).to(device)
85+
labels = labels.to(device)
86+
outputs = model(images)
87+
_, predicted = torch.max(outputs.data, 1)
88+
total += labels.size(0)
89+
correct += (predicted == labels).sum().item()
90+
91+
print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))
92+
93+
# Save the model checkpoint
94+
torch.save(model.state_dict(), 'model.ckpt')
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import torch
2+
import torch.nn as nn
3+
import numpy as np
4+
import matplotlib.pyplot as plt
5+
6+
7+
# Hyper-parameters
8+
input_size = 1
9+
output_size = 1
10+
num_epochs = 60
11+
learning_rate = 0.001
12+
13+
# Toy dataset
14+
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
15+
[9.779], [6.182], [7.59], [2.167], [7.042],
16+
[10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
17+
18+
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
19+
[3.366], [2.596], [2.53], [1.221], [2.827],
20+
[3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
21+
22+
# Linear regression model
23+
model = nn.Linear(input_size, output_size)
24+
25+
# Loss and optimizer
26+
criterion = nn.MSELoss()
27+
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
28+
29+
# Train the model
30+
for epoch in range(num_epochs):
31+
# Convert numpy arrays to torch tensors
32+
inputs = torch.from_numpy(x_train)
33+
targets = torch.from_numpy(y_train)
34+
35+
# Forward pass
36+
outputs = model(inputs)
37+
loss = criterion(outputs, targets)
38+
39+
# Backward and optimize
40+
optimizer.zero_grad()
41+
loss.backward()
42+
optimizer.step()
43+
44+
if (epoch+1) % 5 == 0:
45+
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
46+
47+
# Plot the graph
48+
predicted = model(torch.from_numpy(x_train)).detach().numpy()
49+
plt.plot(x_train, y_train, 'ro', label='Original data')
50+
plt.plot(x_train, predicted, label='Fitted line')
51+
plt.legend()
52+
plt.show()
53+
54+
# Save the model checkpoint
55+
torch.save(model.state_dict(), 'model.ckpt')
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import torch
2+
import torch.nn as nn
3+
import torchvision
4+
import torchvision.transforms as transforms
5+
6+
7+
# Hyper-parameters
8+
input_size = 784
9+
num_classes = 10
10+
num_epochs = 5
11+
batch_size = 100
12+
learning_rate = 0.001
13+
14+
# MNIST dataset (images and labels)
15+
train_dataset = torchvision.datasets.MNIST(root='../../data',
16+
train=True,
17+
transform=transforms.ToTensor(),
18+
download=True)
19+
20+
test_dataset = torchvision.datasets.MNIST(root='../../data',
21+
train=False,
22+
transform=transforms.ToTensor())
23+
24+
# Data loader (input pipeline)
25+
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
26+
batch_size=batch_size,
27+
shuffle=True)
28+
29+
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
30+
batch_size=batch_size,
31+
shuffle=False)
32+
33+
# Logistic regression model
34+
model = nn.Linear(input_size, num_classes)
35+
36+
# Loss and optimizer
37+
# nn.CrossEntropyLoss() computes softmax internally
38+
criterion = nn.CrossEntropyLoss()
39+
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
40+
41+
# Train the model
42+
total_step = len(train_loader)
43+
for epoch in range(num_epochs):
44+
for i, (images, labels) in enumerate(train_loader):
45+
# Reshape images to (batch_size, input_size)
46+
images = images.reshape(-1, 28*28)
47+
48+
# Forward pass
49+
outputs = model(images)
50+
loss = criterion(outputs, labels)
51+
52+
# Backward and optimize
53+
optimizer.zero_grad()
54+
loss.backward()
55+
optimizer.step()
56+
57+
if (i+1) % 100 == 0:
58+
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
59+
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
60+
61+
# Test the model
62+
# In test phase, we don't need to compute gradients (for memory efficieny)
63+
with torch.no_grad():
64+
correct = 0
65+
total = 0
66+
for images, labels in test_loader:
67+
images = images.reshape(-1, 28*28)
68+
outputs = model(images)
69+
_, predicted = torch.max(outputs.data, 1)
70+
total += labels.size(0)
71+
correct += (predicted == labels).sum()
72+
73+
print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
74+
75+
# Save the model checkpoint
76+
torch.save(model.state_dict(), 'model.ckpt')

0 commit comments

Comments
 (0)