File size: 2,314 Bytes
299bc83 91e97d6 299bc83 91e97d6 d6b7c50 91e97d6 d6b7c50 91e97d6 d6b7c50 91e97d6 |
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 |
---
tags:
- model_hub_mixin
- pytorch_model_hub_mixin
datasets:
- zalando-datasets/fashion_mnist
metrics:
- accuracy
library_name: pytorch
pipeline_tag: image-classification
---
# mlp-fashion-mnist
A multi-layer perceptron (MLP) trained on the Fashion-MNIST dataset.
It is a PyTorch adaptation of the TensorFlow model in Chapter 10 of Aurelien Geron's book 'Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow'.
Code: https://github.com/sambitmukherjee/handson-ml3-pytorch/blob/main/chapter10/mlp_fashion_mnist.ipynb
Experiment tracking: https://wandb.ai/sadhaklal/mlp-fashion-mnist
## Usage
```
!pip install -q datasets
from datasets import load_dataset
fashion_mnist = load_dataset("zalando-datasets/fashion_mnist")
features = fashion_mnist['train'].features
id2label = {id: label for id, label in enumerate(features['label'].names)}
import torch
import torchvision.transforms.v2 as v2
tfms = v2.Compose([
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True)
])
device = torch.device("cpu")
import torch.nn as nn
from huggingface_hub import PyTorchModelHubMixin
class MLP(nn.Module, PyTorchModelHubMixin):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(28 * 28, 300)
self.fc2 = nn.Linear(300, 100)
self.fc3 = nn.Linear(100, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
act = torch.relu(self.fc1(x))
act = torch.relu(self.fc2(act))
return self.fc3(act)
model = MLP.from_pretrained("sadhaklal/mlp-fashion-mnist")
model.to(device)
example = fashion_mnist['test'][0]
import matplotlib.pyplot as plt
plt.imshow(example['image'], cmap='gray')
print(f"Ground truth: {id2label[example['label']]}")
img = tfms(example['image'])
x_batch = img.unsqueeze(0)
model.eval()
x_batch = x_batch.to(device)
with torch.no_grad():
logits = model(x_batch)
proba = torch.softmax(logits, dim=-1)
confidence, pred = proba.max(dim=-1)
print(f"Predicted class: {id2label[pred[0].item()]}")
print(f"Predicted confidence: {round(confidence[0].item(), 4)}")
```
## Metric
Accuracy on the test set: 0.8829
---
This model has been pushed to the Hub using the [PyTorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration. |