CNN SVM
CNN SVM
CNN SVM
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
from sklearn.svm import SVC
import joblib
import os
import numpy as np
# Parameters
dropoutfactor = 0.5
maxepoch = 100
batchsize = 128
learning_rate = 0.001
optimizer_fn = optim.Adam
running_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
# Calculate accuracy
accuracy = 100 * correct / total
# Print epoch, loss, and accuracy
print(f"Epoch [{epoch+1}/{max_epoch}], Loss: {running_loss /
len(train_loader):.4f}, Accuracy: {accuracy:.2f}%")
with torch.no_grad():
for inputs, target_labels in loader:
inputs = inputs.to(device) # Move to GPU
outputs = model(inputs)
features.append(outputs.cpu().numpy())
labels.append(target_labels.cpu().numpy())
# Load data
dataloaders, class_names = load_data(data_dir, batchsize)
# Fine-tune MobileNetV2 model for maxepoch epochs and save best model
mobilenet_v2_model = train_mobilenetv2(mobilenet_v2_model, dataloaders, maxepoch,
learning_rate, optimizer_fn)
### test
import torch
import numpy as np
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
import joblib
import os
from sklearn.metrics import f1_score, confusion_matrix
with torch.no_grad():
for inputs, target_labels in loader:
inputs = inputs.to(device) # Move to GPU
outputs = model(inputs)
features.append(outputs.cpu().numpy())
labels.append(target_labels.cpu().numpy())
# Calculate metrics
accuracy = np.sum(predictions == test_labels) / len(test_labels)
tn, fp, fn, tp = confusion_matrix(test_labels, predictions).ravel()
# Print results
print(f'Accuracy: {accuracy:.4f}')
print(f'F-measure: {f_measure:.4f}')
print(f'Sensitivity: {sensitivity:.4f}')
print(f'Specificity: {specificity:.4f}')