<jupyter_start><jupyter_text>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`).<jupyter_code>%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
# 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(),
)
# 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
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

def train(model, dataloader, 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<jupyter_output>Using cpu device<jupyter_text>`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:<jupyter_code>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]}, NeuralNetwork, loss_fn=loss_fn, epochs=5)
modeling_set.fit(train_data)<jupyter_output><empty_output><jupyter_text>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`:<jupyter_code>test_nn = partial(test, loss_fn=loss_fn)
hard_metrics_set = Vset(name='hard_metrics', modules=[test_nn], module_keys=["acc"])
hard_metrics = hard_metrics_set.evaluate(test_data, modeling_set.out)

df = dict_to_df(hard_metrics, param_key='modeling')
df<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1249066932072655, 'fraction_numerical': 0.012192087583976113, 'mean_word_length': 3.3982494529540483, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '407608', 'license': 'MIT', 'n_tokens_mistral': 1378, 'n_tokens_neox': 1316, 'n_words': 317, 'path': 'notebooks/03_computer_vision_dnn.ipynb', 'repo_name': 'Yu-Group/veridical-flow', 'size': '4019'}