<jupyter_start><jupyter_text>Plot some images from the training set<jupyter_code>features, labels = next(iter(dataloader))
rows = int(len(features)/2) 
plt.figure(figsize=(16,16))
for i, (feature, label) in enumerate(zip(features, labels)):  
    plt.subplot(rows, rows, i+1)
    plt.axis("off")  
    plt.imshow(feature.permute(1, 2, 0).numpy(), cmap='gray')   

criteria = nn.CrossEntropyLoss()
model = Model().to(device)
lr = 0.001
n_epoch = 50
optimizer = Adam(model.parameters(), lr=lr)<jupyter_output><empty_output><jupyter_text>Train the model<jupyter_code>for epoch in range(n_epoch):
    train_error = 0
    for i, (train_data, y_true) in enumerate(dataloader):
        optimizer.zero_grad() # reinitialize the gradient

        y_pred = model(train_data) # fit the data

        error = criteria(y_pred, y_true) # compute the error
        error.backward() # back propagrade the gradient
        optimizer.step() # Updates model parameters
        train_error += error.item()
    print(f'Epoch {epoch} train error {train_error/len(dataloader)}')

torch.save(model, 'Trained_Model')
def check_accuracy(loader, model=model, is_training=False):
    model.eval()
    num_correct = 0 
    sample_size = 0
    with torch.no_grad():
        for img, label in loader:
            img = img.to(device)
            label = label.to(device)

            scores = model(img)
            _, predictions = scores.max(1) 
            num_correct += (predictions == label).sum()
            sample_size += predictions.shape[0] 
    print(f'{"Train" if is_training else "Test"} Correct classification {num_correct}/{sample_size} - accuracy {(num_correct/sample_size)*100:.2F}%')
check_accuracy(dataloader, model, True)
check_accuracy(test_dataloader, model)
def preprocess_image(image):
	# swap the color channels from BGR to RGB, resize it, and scale
	# the pixel values to [0, 1] range
	image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
	image = cv.resize(image, (64, 64))
	image = image.astype("float32") / 255.0
	# subtract ImageNet mean, divide by ImageNet standard deviation,
	# set "channels first" ordering, and add a batch dimension
	#image -= config.MEAN
	i#mage /= config.STD
	image = np.transpose(image, (2, 0, 1))
	image = np.expand_dims(image, 0)
	# return the preprocessed image
	return torch.from_numpy(image)
img = cv.imread(
    'Resources/Faces/Train/Happy/1632297411.6.jpg') 
print(img.shape) 
plt.subplot(121)
plt.imshow(img, cmap='gray') 
img_tensor = preprocess_image(img)  
plt.subplot(122)
plt.imshow(img_tensor[0].permute(1, 2, 0).numpy(), cmap='gray')
#plt.imshow(img_tensor[0], cmap='gray')
label = model.predict(img_tensor)
print(classes[label])<jupyter_output>Happy
StarcoderdataJupyterStructuredCleanDedup