-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmnist.py
98 lines (78 loc) · 3.03 KB
/
mnist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from moe2 import MoE
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Hyperparameters
input_size = 784
num_classes = 10
learning_rate = 0.001
batch_size = 64
num_epochs = 50
#
num_experts = 200
hidden_size = 200
k = 8
# Load MNIST dataset
train_dataset = datasets.MNIST(root='data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = datasets.MNIST(root='data',
train=False,
transform=transforms.ToTensor())
# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
#models
hydra = MoE(input_size, num_classes, num_experts, hidden_size, k=k, noisy_gating=True, mlp = False).to(device)
bench = MoE(input_size, num_classes, num_experts, hidden_size, k=k, noisy_gating=True, mlp = True).to(device)
# Train the model
total_step = len(train_loader)
eval_dict = {}
for i,model in enumerate([hydra]):
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
evals = []
for epoch in range(num_epochs):
for z, (images, labels) in enumerate(train_loader):
# Reshape images to (batch_size, input_size)
images = images.reshape(-1, input_size).to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs[0], labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
correct = 0
total = 0
cc = 0
for images, labels in test_loader:
images = images.reshape(-1, input_size).to(device)
labels = labels.to(device)
outputs = model(images)[0]
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
evals.append(correct/total)
print(f'Accuracy of the model on the 10000 test images: {correct/total} %')
eval_dict[i] = evals
from matplotlib import pyplot as plt
for i in [0,1]:
plt.scatter(range(len(eval_dict[i])), eval_dict[i])
import pandas as pd
pd.Series(eval_dict[0]).mean()
pd.Series(eval_dict[1]).mean()#hydra