Skip to content

Commit 7f15277

Browse files
committed
update
1 parent 045ddcd commit 7f15277

File tree

11 files changed

+153
-1
lines changed

11 files changed

+153
-1
lines changed

doc/pub/week4/pdf/week4.pdf

-899 KB
Binary file not shown.
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 torch.nn.functional as F
4+
import torch.optim as optim
5+
from torchvision import datasets, transforms
6+
7+
# Set device
8+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9+
10+
# Define transforms
11+
transform = transforms.Compose([
12+
transforms.ToTensor(),
13+
transforms.Normalize((0.1307,), (0.3081,))
14+
])
15+
16+
# Load datasets
17+
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
18+
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
19+
20+
# Create data loaders
21+
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
22+
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
23+
24+
# Define CNN model
25+
class CNN(nn.Module):
26+
def __init__(self):
27+
super(CNN, self).__init__()
28+
self.conv1 = nn.Conv2d(1, 32, 3, padding=1)
29+
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
30+
self.pool = nn.MaxPool2d(2, 2)
31+
self.fc1 = nn.Linear(64*7*7, 1024)
32+
self.fc2 = nn.Linear(1024, 10)
33+
self.dropout = nn.Dropout(0.5)
34+
35+
def forward(self, x):
36+
x = self.pool(F.relu(self.conv1(x)))
37+
x = self.pool(F.relu(self.conv2(x)))
38+
x = x.view(-1, 64*7*7)
39+
x = self.dropout(F.relu(self.fc1(x)))
40+
x = self.fc2(x)
41+
return x
42+
43+
# Initialize model, loss function, and optimizer
44+
model = CNN().to(device)
45+
criterion = nn.CrossEntropyLoss()
46+
optimizer = optim.Adam(model.parameters(), lr=0.001)
47+
48+
# Training loop
49+
num_epochs = 10
50+
for epoch in range(num_epochs):
51+
model.train()
52+
running_loss = 0.0
53+
for batch_idx, (data, target) in enumerate(train_loader):
54+
data, target = data.to(device), target.to(device)
55+
optimizer.zero_grad()
56+
outputs = model(data)
57+
loss = criterion(outputs, target)
58+
loss.backward()
59+
optimizer.step()
60+
running_loss += loss.item()
61+
62+
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {running_loss/len(train_loader):.4f}')
63+
64+
# Testing the model
65+
model.eval()
66+
correct = 0
67+
total = 0
68+
with torch.no_grad():
69+
for data, target in test_loader:
70+
data, target = data.to(device), target.to(device)
71+
outputs = model(data)
72+
_, predicted = torch.max(outputs.data, 1)
73+
total += target.size(0)
74+
correct += (predicted == target).sum().item()
75+
76+
print(f'Test Accuracy: {100 * correct / total:.2f}%')
7.48 MB
Binary file not shown.
1.57 MB
Binary file not shown.
9.77 KB
Binary file not shown.
4.44 KB
Binary file not shown.
44.9 MB
Binary file not shown.
9.45 MB
Binary file not shown.
58.6 KB
Binary file not shown.
28.2 KB
Binary file not shown.

0 commit comments

Comments
 (0)