Spaces:
Sleeping
Sleeping
Download plant_classifier/model.py from ZZW45/image-classifier: direct link, hf CLI and curl.
- Browser
- Download file 2.25 kB
-
https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/model.py
- Command line
-
hf download hf://spaces/ZZW45/image-classifier/plant_classifier/model.py
-
curl -L -o model.py https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/model.py
2.25 kB
| """A small convolutional classifier trained entirely from scratch.""" | |
| from __future__ import annotations | |
| import math | |
| from collections.abc import Sequence | |
| from torch import Tensor, nn | |
| class PlantDiseaseCNN(nn.Module): | |
| """Four convolutional stages followed by global pooling and a classifier.""" | |
| def __init__( | |
| self, | |
| num_classes: int = 39, | |
| channels: Sequence[int] = (32, 64, 128, 256), | |
| dropout: float = 0.3, | |
| ) -> None: | |
| super().__init__() | |
| if isinstance(num_classes, bool) or not isinstance(num_classes, int) or num_classes < 2: | |
| raise ValueError("num_classes must be an integer of at least 2") | |
| if len(channels) != 4 or any( | |
| isinstance(c, bool) or not isinstance(c, int) or c < 1 for c in channels | |
| ): | |
| raise ValueError("channels must contain four positive integers") | |
| if isinstance(dropout, bool) or not math.isfinite(dropout) or not 0 <= dropout < 1: | |
| raise ValueError("dropout must be finite and in [0, 1)") | |
| self.model_config = { | |
| "num_classes": num_classes, | |
| "channels": list(channels), | |
| "dropout": float(dropout), | |
| } | |
| blocks: list[nn.Module] = [] | |
| in_channels = 3 | |
| for out_channels in channels: | |
| blocks.append( | |
| nn.Sequential( | |
| nn.Conv2d(in_channels, out_channels, 3, padding=1, bias=False), | |
| nn.BatchNorm2d(out_channels), | |
| nn.ReLU(inplace=True), | |
| nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False), | |
| nn.BatchNorm2d(out_channels), | |
| nn.ReLU(inplace=True), | |
| nn.MaxPool2d(2), | |
| ) | |
| ) | |
| in_channels = out_channels | |
| self.features = nn.Sequential(*blocks) | |
| self.classifier = nn.Sequential( | |
| nn.AdaptiveAvgPool2d(1), | |
| nn.Flatten(), | |
| nn.Dropout(dropout), | |
| nn.Linear(channels[-1], num_classes), | |
| ) | |
| def forward(self, images: Tensor) -> Tensor: | |
| """Return unnormalised logits; CrossEntropyLoss applies log-softmax.""" | |
| return self.classifier(self.features(images)) | |