thomasdeboer commited on
Commit
53d1aef
·
verified ·
1 Parent(s): 7b9b0ca

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. README.md +159 -1
  2. config.json +37 -0
  3. inference.py +74 -0
  4. model.py +31 -0
  5. pytorch_model.bin +3 -0
  6. requirements.txt +4 -0
README.md CHANGED
@@ -1,3 +1,161 @@
1
  ---
2
- license: cc-by-4.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language: en
3
+ license: mit
4
+ tags:
5
+ - image-classification
6
+ - pytorch
7
+ - garbage-classification
8
+ - waste-management
9
+ - environmental
10
+ datasets:
11
+ - garbage-classification-dataset
12
+ metrics:
13
+ - accuracy
14
+ - cross-entropy-loss
15
+ library_name: pytorch
16
+ pipeline_tag: image-classification
17
  ---
18
+
19
+ # Garbage Classification Model (LargeNet)
20
+
21
+ ## Model Description
22
+
23
+ This is a PyTorch-based convolutional neural network trained to classify images of garbage into 7 categories:
24
+ - **Battery**: Used batteries and battery waste
25
+ - **Biological**: Organic and biodegradable waste
26
+ - **Cardboard**: Cardboard boxes and packaging
27
+ - **Glass**: Glass bottles, jars, and containers
28
+ - **Metal**: Metal cans, foil, and containers
29
+ - **Paper**: Paper waste, documents, and newspaper
30
+ - **Plastic**: Plastic bottles, bags, and containers
31
+
32
+ The model uses a custom CNN architecture called "LargeNet" that processes 128x128 RGB images.
33
+
34
+ ## Model Architecture
35
+
36
+ ```
37
+ LargeNet(
38
+ (conv1): Conv2d(3, 5, kernel_size=5)
39
+ (pool): MaxPool2d(kernel_size=2, stride=2)
40
+ (conv2): Conv2d(5, 10, kernel_size=5)
41
+ (fc1): Linear(in_features=8410, out_features=32)
42
+ (fc2): Linear(in_features=32, out_features=7)
43
+ )
44
+ ```
45
+
46
+ **Architecture Details:**
47
+ - Input: 128x128 RGB images
48
+ - 2 Convolutional layers with ReLU activation
49
+ - MaxPooling after each convolution
50
+ - 2 Fully connected layers
51
+ - Output: 7 classes with softmax probabilities
52
+
53
+ ## Training Details
54
+
55
+ **Training Hyperparameters:**
56
+ - Batch size: 64
57
+ - Learning rate: 0.01
58
+ - Optimizer: SGD
59
+ - Loss function: CrossEntropyLoss
60
+ - Best epoch: 61
61
+ - Training dataset: Garbage Classification Dataset (2100 images)
62
+
63
+ **Data Preprocessing:**
64
+ - Images resized to 128x128 pixels
65
+ - Normalized with mean=[0.5, 0.5, 0.5] and std=[0.5, 0.5, 0.5]
66
+ - Data split: 72% train, 18% validation, 10% test
67
+
68
+ ## Usage
69
+
70
+ ### Quick Start
71
+
72
+ ```python
73
+ from inference import GarbageClassifier
74
+
75
+ # Initialize the classifier
76
+ classifier = GarbageClassifier(".")
77
+
78
+ # Classify an image
79
+ result = classifier.predict("path/to/garbage_image.jpg")
80
+
81
+ print(f"Predicted class: {result['class']}")
82
+ print(f"Confidence: {result['confidence']:.2%}")
83
+ print(f"All probabilities: {result['all_probabilities']}")
84
+ ```
85
+
86
+ ### Manual Usage
87
+
88
+ ```python
89
+ import torch
90
+ from PIL import Image
91
+ from torchvision import transforms
92
+ from model import load_model
93
+
94
+ # Load model
95
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
96
+ model = load_model("pytorch_model.bin", device)
97
+
98
+ # Prepare image
99
+ transform = transforms.Compose([
100
+ transforms.Resize((128, 128)),
101
+ transforms.ToTensor(),
102
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
103
+ ])
104
+
105
+ image = Image.open("image.jpg").convert('RGB')
106
+ image_tensor = transform(image).unsqueeze(0).to(device)
107
+
108
+ # Predict
109
+ with torch.no_grad():
110
+ outputs = model(image_tensor)
111
+ probabilities = torch.nn.functional.softmax(outputs, dim=1)
112
+ _, predicted = torch.max(probabilities, 1)
113
+
114
+ class_names = ["battery", "biological", "cardboard", "glass", "metal", "paper", "plastic"]
115
+ print(f"Predicted class: {class_names[predicted.item()]}")
116
+ ```
117
+
118
+ ## Model Performance
119
+
120
+ The model achieved competitive performance on the garbage classification task. For detailed metrics and performance analysis, please refer to the training logs and evaluation results.
121
+
122
+ ## Limitations and Bias
123
+
124
+ - The model is trained on a specific garbage dataset and may not generalize well to all types of waste
125
+ - Performance may vary with different lighting conditions, image quality, and garbage appearances
126
+ - The dataset may have regional or cultural biases in garbage representation
127
+ - Works best with clear, well-lit images of individual garbage items
128
+
129
+ ## Intended Use
130
+
131
+ This model is intended for:
132
+ - Educational purposes in waste management and environmental studies
133
+ - Prototype development for waste sorting applications
134
+ - Research in automated recycling systems
135
+ - Environmental awareness applications
136
+
137
+ **Not recommended for:**
138
+ - Production waste sorting systems without additional validation
139
+ - Critical infrastructure without human oversight
140
+ - Scenarios requiring 100% accuracy
141
+
142
+ ## Citation
143
+
144
+ If you use this model, please cite:
145
+ ```
146
+ @misc{garbage-classifier-largenet,
147
+ author = {Your Name},
148
+ title = {Garbage Classification Model},
149
+ year = {2026},
150
+ publisher = {HuggingFace},
151
+ url = {https://huggingface.co/your-username/garbage-classifier-largenet}
152
+ }
153
+ ```
154
+
155
+ ## License
156
+
157
+ MIT License
158
+
159
+ ## Contact
160
+
161
+ For questions or feedback, please open an issue on the model repository.
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architecture": "LargeNet",
3
+ "num_classes": 7,
4
+ "input_size": [
5
+ 128,
6
+ 128
7
+ ],
8
+ "input_channels": 3,
9
+ "class_names": [
10
+ "battery",
11
+ "biological",
12
+ "cardboard",
13
+ "glass",
14
+ "metal",
15
+ "paper",
16
+ "plastic"
17
+ ],
18
+ "normalization": {
19
+ "mean": [
20
+ 0.5,
21
+ 0.5,
22
+ 0.5
23
+ ],
24
+ "std": [
25
+ 0.5,
26
+ 0.5,
27
+ 0.5
28
+ ]
29
+ },
30
+ "training_params": {
31
+ "batch_size": 64,
32
+ "learning_rate": 0.01,
33
+ "best_epoch": 61,
34
+ "optimizer": "SGD",
35
+ "loss_function": "CrossEntropyLoss"
36
+ }
37
+ }
inference.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from torchvision import transforms
4
+ from model import load_model
5
+ import json
6
+ import os
7
+
8
+ class GarbageClassifier:
9
+ def __init__(self, model_dir="."):
10
+ """Initialize the garbage classifier"""
11
+ # Load config
12
+ with open(os.path.join(model_dir, "config.json"), "r") as f:
13
+ self.config = json.load(f)
14
+
15
+ # Setup device
16
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+ # Load model
19
+ model_path = os.path.join(model_dir, "pytorch_model.bin")
20
+ self.model = load_model(model_path, self.device)
21
+
22
+ # Setup transforms
23
+ mean = self.config["normalization"]["mean"]
24
+ std = self.config["normalization"]["std"]
25
+ size = tuple(self.config["input_size"])
26
+
27
+ self.transform = transforms.Compose([
28
+ transforms.Resize(size),
29
+ transforms.ToTensor(),
30
+ transforms.Normalize(mean, std)
31
+ ])
32
+
33
+ self.class_names = self.config["class_names"]
34
+
35
+ def predict(self, image_path):
36
+ """
37
+ Predict the class of a garbage image
38
+
39
+ Args:
40
+ image_path: Path to the image file
41
+
42
+ Returns:
43
+ dict: Contains 'class', 'confidence', and 'all_probabilities'
44
+ """
45
+ # Load and preprocess image
46
+ image = Image.open(image_path).convert('RGB')
47
+ image_tensor = self.transform(image).unsqueeze(0).to(self.device)
48
+
49
+ # Make prediction
50
+ with torch.no_grad():
51
+ outputs = self.model(image_tensor)
52
+ probabilities = torch.nn.functional.softmax(outputs, dim=1)
53
+ confidence, predicted = torch.max(probabilities, 1)
54
+
55
+ # Format results
56
+ predicted_class = self.class_names[predicted.item()]
57
+ confidence_score = confidence.item()
58
+ all_probs = {
59
+ self.class_names[i]: probabilities[0][i].item()
60
+ for i in range(len(self.class_names))
61
+ }
62
+
63
+ return {
64
+ "class": predicted_class,
65
+ "confidence": confidence_score,
66
+ "all_probabilities": all_probs
67
+ }
68
+
69
+ # Example usage:
70
+ if __name__ == "__main__":
71
+ classifier = GarbageClassifier(".")
72
+ result = classifier.predict("path/to/image.jpg")
73
+ print(f"Predicted class: {result['class']}")
74
+ print(f"Confidence: {result['confidence']:.2%}")
model.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ class LargeNet(nn.Module):
6
+ def __init__(self):
7
+ super(LargeNet, self).__init__()
8
+ self.name = "large"
9
+ self.conv1 = nn.Conv2d(3, 5, 5)
10
+ self.pool = nn.MaxPool2d(2, 2)
11
+ self.conv2 = nn.Conv2d(5, 10, 5)
12
+ self.fc1 = nn.Linear(10 * 29 * 29, 32)
13
+ self.fc2 = nn.Linear(32, 7)
14
+
15
+ def forward(self, x):
16
+ x = self.pool(F.relu(self.conv1(x)))
17
+ x = self.pool(F.relu(self.conv2(x)))
18
+ x = x.view(-1, 10 * 29 * 29)
19
+ x = F.relu(self.fc1(x))
20
+ x = self.fc2(x)
21
+ x = x.squeeze(1) # Flatten to [batch_size]
22
+ return x
23
+
24
+ def load_model(model_path, device='cpu'):
25
+ """Load the trained model from saved weights"""
26
+ model = LargeNet()
27
+ state_dict = torch.load(model_path, map_location=device)
28
+ model.load_state_dict(state_dict)
29
+ model.to(device)
30
+ model.eval()
31
+ return model
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3500f580debe699b96badecdad7705fb4a9118e8db109fdd87535a8d1b768c0
3
+ size 1087304
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.0.0
2
+ torchvision>=0.15.0
3
+ pillow>=9.0.0
4
+ numpy>=1.21.0