File size: 7,619 Bytes
efb1801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/env python3
"""
Model Validation Script for Strawberry Ripeness Classification
Tests the trained model on sample images to verify functionality
"""

import os
import sys
import torch
import numpy as np
import cv2
from pathlib import Path
import json
from datetime import datetime

# Add current directory to path for imports
sys.path.append('.')

from train_ripeness_classifier import create_model, get_transforms

def load_model(model_path):
    """Load the trained classification model"""
    print(f"Loading model from: {model_path}")
    
    if not os.path.exists(model_path):
        raise FileNotFoundError(f"Model file not found: {model_path}")
    
    # Create model architecture
    model = create_model(num_classes=3, backbone='resnet18', pretrained=False)
    
    # Load trained weights
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model.load_state_dict(torch.load(model_path, map_location=device))
    model = model.to(device)
    model.eval()
    
    print(f"Model loaded successfully on {device}")
    return model, device

def get_test_images():
    """Get sample test images from the dataset"""
    test_dirs = [
        'model/ripeness_manual_dataset/unripe',
        'model/ripeness_manual_dataset/ripe', 
        'model/ripeness_manual_dataset/overripe'
    ]
    
    test_images = []
    for test_dir in test_dirs:
        if os.path.exists(test_dir):
            images = list(Path(test_dir).glob('*.jpg'))[:3]  # Get first 3 images from each class
            for img_path in images:
                test_images.append({
                    'path': str(img_path),
                    'true_label': os.path.basename(test_dir),
                    'class_name': os.path.basename(test_dir)
                })
    
    return test_images

def predict_image(model, device, image_path, transform):
    """Predict ripeness for a single image"""
    try:
        # Load and preprocess image
        image = cv2.imread(image_path)
        if image is None:
            return None, "Failed to load image"
        
        # Convert BGR to RGB
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        from PIL import Image
        image_pil = Image.fromarray(image)
        
        # Apply transforms
        input_tensor = transform(image_pil).unsqueeze(0).to(device)
        
        # Get prediction
        with torch.no_grad():
            outputs = model(input_tensor)
            probabilities = torch.softmax(outputs, dim=1)
            predicted_class_idx = torch.argmax(probabilities, dim=1).item()
            confidence = probabilities[0][predicted_class_idx].item()
        
        # Get class names
        class_names = ['overripe', 'ripe', 'unripe']
        predicted_class = class_names[predicted_class_idx]
        
        # Get all probabilities
        probs_dict = {
            class_names[i]: float(probabilities[0][i].item()) 
            for i in range(len(class_names))
        }
        
        return {
            'predicted_class': predicted_class,
            'confidence': confidence,
            'probabilities': probs_dict
        }, None
        
    except Exception as e:
        return None, str(e)

def validate_model():
    """Main validation function"""
    print("=== Strawberry Ripeness Classification Model Validation ===")
    print(f"Validation time: {datetime.now().isoformat()}")
    print()
    
    # Load model
    model_path = 'model/ripeness_classifier_best.pth'
    try:
        model, device = load_model(model_path)
    except Exception as e:
        print(f"❌ Failed to load model: {e}")
        return False
    
    # Get transforms
    _, transform = get_transforms(img_size=224)
    
    # Get test images
    test_images = get_test_images()
    if not test_images:
        print("❌ No test images found")
        return False
    
    print(f"Found {len(test_images)} test images")
    print()
    
    # Test predictions
    results = []
    correct_predictions = 0
    total_predictions = 0
    
    print("Testing predictions...")
    print("-" * 80)
    
    for i, test_img in enumerate(test_images):
        image_path = test_img['path']
        true_label = test_img['true_label']
        
        # Make prediction
        prediction, error = predict_image(model, device, image_path, transform)
        
        if error:
            print(f"❌ Image {i+1}: Error - {error}")
            continue
        
        predicted_class = prediction['predicted_class']
        confidence = prediction['confidence']
        
        # Check if prediction is correct
        is_correct = predicted_class == true_label
        if is_correct:
            correct_predictions += 1
        total_predictions += 1
        
        # Print result
        status = "✅" if is_correct else "❌"
        print(f"{status} Image {i+1}: {os.path.basename(image_path)}")
        print(f"   True: {true_label} | Predicted: {predicted_class} ({confidence:.3f})")
        print(f"   Probabilities: overripe={prediction['probabilities']['overripe']:.3f}, "
              f"ripe={prediction['probabilities']['ripe']:.3f}, "
              f"unripe={prediction['probabilities']['unripe']:.3f}")
        print()
        
        # Store result
        results.append({
            'image_path': image_path,
            'true_label': true_label,
            'predicted_class': predicted_class,
            'confidence': confidence,
            'probabilities': prediction['probabilities'],
            'correct': is_correct
        })
    
    # Calculate accuracy
    accuracy = (correct_predictions / total_predictions * 100) if total_predictions > 0 else 0
    
    print("=" * 80)
    print("VALIDATION RESULTS")
    print("=" * 80)
    print(f"Total images tested: {total_predictions}")
    print(f"Correct predictions: {correct_predictions}")
    print(f"Accuracy: {accuracy:.1f}%")
    print()
    
    # Class-wise analysis
    class_stats = {}
    for result in results:
        true_class = result['true_label']
        if true_class not in class_stats:
            class_stats[true_class] = {'correct': 0, 'total': 0}
        class_stats[true_class]['total'] += 1
        if result['correct']:
            class_stats[true_class]['correct'] += 1
    
    print("Class-wise Performance:")
    for class_name, stats in class_stats.items():
        class_accuracy = (stats['correct'] / stats['total'] * 100) if stats['total'] > 0 else 0
        print(f"  {class_name}: {stats['correct']}/{stats['total']} ({class_accuracy:.1f}%)")
    print()
    
    # Save detailed results
    validation_results = {
        'validation_time': datetime.now().isoformat(),
        'model_path': model_path,
        'device': str(device),
        'total_images': total_predictions,
        'correct_predictions': correct_predictions,
        'accuracy_percent': accuracy,
        'class_stats': class_stats,
        'detailed_results': results
    }
    
    results_path = 'model_validation_results.json'
    with open(results_path, 'w') as f:
        json.dump(validation_results, f, indent=2)
    
    print(f"Detailed results saved to: {results_path}")
    
    # Validation verdict
    if accuracy >= 90:
        print("🎉 VALIDATION PASSED: Model performs excellently!")
        return True
    elif accuracy >= 80:
        print("⚠️  VALIDATION WARNING: Model performs moderately well")
        return True
    else:
        print("❌ VALIDATION FAILED: Model performance is poor")
        return False

if __name__ == '__main__':
    success = validate_model()
    sys.exit(0 if success else 1)