Fashion-MNIST Classification¶
This notebooks shows an example of using vflow
on the Fashion-MNIST dataset using deep neural networks. It requires installing pytorch and torchvision (pip install torch torchvision
).
In [1]:
%load_ext autoreload
%autoreload 2
from vflow import Vset, init_args, build_vset, dict_to_df
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
from functools import partial
In [2]:
# load data
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
In [3]:
# Define model
class NeuralNetwork(nn.Module):
def __init__(self, fc1=512, fc2=512):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, fc1),
nn.ReLU(),
nn.Linear(fc1, fc2),
nn.ReLU(),
nn.Linear(fc2, 10),
nn.ReLU()
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
In [4]:
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
def train(dataloader, model, loss_fn, epochs, **kwargs):
# initialize model with **kwargs
if isinstance(model, type):
model = model(**kwargs)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
size = len(dataloader.dataset)
for t in range(epochs):
# print(f"Epoch {t+1}\n-------------------------------")
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device)
# Compute prediction error
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(X)
# print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
return model
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
return correct
Using cpu device
build_vset(name, obj, param_dict, verbose=True)
can be used to construct a Vset
by currying obj
with all possible combinations of parameters in param_dict
.
We can use it here to simplify hyperparameter tuning:
In [5]:
batch_size = 64
loss_fn = nn.CrossEntropyLoss()
# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
train_data, test_data = init_args((train_dataloader, test_dataloader), names=['train_data', 'test_data'])
# fit neural network
modeling_set = build_vset('modeling', train, {'fc1': [256, 512], 'fc2': [256, 512]}, model=NeuralNetwork, loss_fn=loss_fn, epochs=5)
modeling_set.fit(train_data)
Out[5]:
<vflow.vset.Vset at 0x7f5bf83c00a0>
If using build_vset
with verbose=True
, we can visualize parameter combinations in our dataframe by passing param_key=vset_name
to dict_to_df
:
In [6]:
test_nn = partial(test, loss_fn=loss_fn)
hard_metrics_set = Vset(name='hard_metrics', vfuncs=[test_nn], vfunc_keys=["acc"])
hard_metrics = hard_metrics_set.evaluate(test_data, modeling_set.fitted_vfuncs)
df = dict_to_df(hard_metrics, param_key='modeling')
df
Out[6]:
init-modeling | init-modeling | fc1-modeling | fc2-modeling | hard_metrics | out | |
---|---|---|---|---|---|---|
0 | test_data | train_data | 256 | 256 | acc | 0.6059 |
1 | test_data | train_data | 256 | 512 | acc | 0.5512 |
2 | test_data | train_data | 512 | 256 | acc | 0.5808 |
3 | test_data | train_data | 512 | 512 | acc | 0.4907 |