|
|
import os
|
|
|
import shutil
|
|
|
import torch
|
|
|
import torch.nn as nn
|
|
|
import torchvision.transforms as transforms
|
|
|
import torchvision.models as models
|
|
|
from torchvision import datasets
|
|
|
from torch.utils.data import DataLoader
|
|
|
import numpy as np
|
|
|
import matplotlib.pyplot as plt
|
|
|
import seaborn as sns
|
|
|
from sklearn.metrics import confusion_matrix, classification_report
|
|
|
|
|
|
|
|
|
structured_dataset_path = "C:\\Users\\srira\\OneDrive\\Desktop\\AI_PROJ\\structured_data"
|
|
|
test_dir = os.path.join(structured_dataset_path, "test")
|
|
|
|
|
|
|
|
|
transform = transforms.Compose([
|
|
|
transforms.Resize((224, 224)),
|
|
|
transforms.ToTensor(),
|
|
|
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
|
|
])
|
|
|
|
|
|
|
|
|
test_dataset = datasets.ImageFolder(root=test_dir, transform=transform)
|
|
|
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
|
|
|
|
|
|
|
|
|
model = models.resnet50(pretrained=False)
|
|
|
num_ftrs = model.fc.in_features
|
|
|
model.fc = nn.Linear(num_ftrs, len(test_dataset.classes))
|
|
|
|
|
|
|
|
|
model.load_state_dict(torch.load("smart_recycling_model1.pth"))
|
|
|
model.eval()
|
|
|
|
|
|
def evaluate_model(model, test_loader):
|
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
model.to(device)
|
|
|
all_preds = []
|
|
|
all_labels = []
|
|
|
|
|
|
with torch.no_grad():
|
|
|
for images, labels in test_loader:
|
|
|
images, labels = images.to(device), labels.to(device)
|
|
|
outputs = model(images)
|
|
|
_, preds = torch.max(outputs, 1)
|
|
|
|
|
|
all_preds.extend(preds.cpu().numpy())
|
|
|
all_labels.extend(labels.cpu().numpy())
|
|
|
|
|
|
|
|
|
cm = confusion_matrix(all_labels, all_preds)
|
|
|
plt.figure(figsize=(8, 6))
|
|
|
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=test_dataset.classes, yticklabels=test_dataset.classes)
|
|
|
plt.xlabel('Predicted')
|
|
|
plt.ylabel('Actual')
|
|
|
plt.title('Confusion Matrix')
|
|
|
plt.show()
|
|
|
|
|
|
|
|
|
print("Classification Report:")
|
|
|
print(classification_report(all_labels, all_preds, target_names=test_dataset.classes))
|
|
|
|
|
|
evaluate_model(model, test_loader) |