import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms from torchvision.datasets import USPS from torch.utils.data import DataLoader
defforward(self, x): x = nn.functional.relu(self.conv1(x)) x = nn.functional.max_pool2d(x, 2) x = nn.functional.relu(self.conv2(x)) x = nn.functional.max_pool2d(x, 2) x = x.view(x.size(0), -1) x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = self.fc3(x) return x
# Model, Loss, and Optimizer model = LeNet() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate)
Train
1 2 3 4 5 6 7 8 9 10 11 12 13
# Training for epoch inrange(num_epochs): for i, (images, labels) inenumerate(train_loader): outputs = model(images) loss = criterion(outputs, labels)
from sklearn import svm from sklearn.metrics import accuracy_score import numpy as np
# Flatten the dataset and convert to numpy arrays X_train = np.array([x[0].numpy().ravel() for x in train_dataset]) y_train = np.array([x[1] for x in train_dataset])
X_test = np.array([x[0].numpy().ravel() for x in test_dataset]) y_test = np.array([x[1] for x in test_dataset])
# Define and train the SVM clf = svm.SVC() clf.fit(X_train, y_train)