Files
pyRBM/cifar_test.ipynb
T
2026-01-10 14:13:18 +01:00

1.8 MiB

In [1]:
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from rbm.model import Model
from rbm.entity import Entity, EntityParams, TrainingParams
from rbm.matrix import Mat, np, rms_error_accu, sample_gaussian
from rbm.torch import Optimizer
import math
import random
In [2]:
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))                            
])                              
In [3]:
train_data = torchvision.datasets.CIFAR10(root='./data', train=True, transform=transform, download=True)
test_data = torchvision.datasets.CIFAR10(root='./data', train=False, transform=transform, download=True)

train_loader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True, num_workers=2)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=32, shuffle=True, num_workers=2)
In [4]:
print(train_data)
Dataset CIFAR10
    Number of datapoints: 50000
    Root location: ./data
    Split: Train
    StandardTransform
Transform: Compose(
               ToTensor()
               Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
           )
In [5]:
N = 1000
n_side = 10
N_VIS = 3072
image, label = train_data[0]
size = len(torch.flatten(image))
train_images = np.zeros(shape=(N, size))
train_images_tensor = torch.Tensor(N, size)
for i in range(N):
    image, label = train_data[i]
    flat_array = torch.flatten(image)
    train_images[i, :] = np.asarray(flat_array.numpy())
    train_images_tensor[i, :] = flat_array
In [6]:
image_indices = np.array(random.sample(range(min(N, n_side*n_side)), n_side*n_side))
print(f"len(train_images):{len(train_images)}")
mean_training_batch = np.reshape(np.repeat(np.mean(train_images, axis=1), N_VIS, axis=0), train_images.shape)
var_training_batch = np.reshape(np.repeat(np.std(train_images, axis=1), N_VIS, axis=0), train_images.shape)
#print(f"mean_training_batch:{mean_training_batch}")
#print(f"var_training_batch:{var_training_batch}")
train_images_norm = (train_images - mean_training_batch) / var_training_batch
len(train_images):1000
In [7]:
fig, axes = plt.subplots(n_side, n_side, figsize=(30,30))
index = 0             
for x in range(n_side):
    for y in range(n_side):
        inp = train_images[image_indices[index]]
        img = (1+np.reshape(inp, (3, 32, 32)))/2
        img = img.transpose((1,2,0))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
In [41]:
class TestModel(Model):
    def __init__(self, name: str, work_dir: str = '.'):
        super().__init__(name, work_dir)
        #self.unit1 = Entity((3072, 125), EntityParams(do_gaussian_visible=True, do_gaussian_hidden=True), TrainingParams(learning_rate=0.0001, momentum=0.9, num_epochs=1000, mini_batch_size=0, weight_decay=0.0, l2_lambda=0.0))
        self.unit1 = Entity((3072, 1000), EntityParams(do_gaussian_visible=True, do_gaussian_hidden=False), TrainingParams(learning_rate=0.005, momentum=0.9, num_epochs=20000, mini_batch_size=1000, weight_decay=0.0, l2_lambda=0.00))
    
    def forward(self, x: Mat):
        x = self.unit1.forward(x)
        return x
    
    def backward(self, x: Mat):
        x = self.unit1.reconstruct(x)
        return x
In [42]:
work_dir = "results"
prj_name = "cifar_test"
prj_root = "/home/jens/work/repos/Rbm"

# Create model
model = TestModel(prj_name, "results")

# Init state
model.init(0.01)

# load state
model.load()

# Train
model.train(train_images)
# save state
model.save()
results/cifar_test-0-state.npz loaded successfully!
-------------------------------------------
Entity-3072x1000: progress              : 0%
Entity-3072x1000: err_rms              : 0.02784882633172159
Entity-3072x1000: l2_norm              : 0.5158487503598633
-------------------------------------------
Entity-3072x1000: progress              : 10%
Entity-3072x1000: err_rms              : 0.018624930194273078
Entity-3072x1000: l2_norm              : 0.8234904823932595
-------------------------------------------
Entity-3072x1000: progress              : 20%
Entity-3072x1000: err_rms              : 0.014180109763117368
Entity-3072x1000: l2_norm              : 1.0976451939335818
-------------------------------------------
Entity-3072x1000: progress              : 30%
Entity-3072x1000: err_rms              : 0.011876559197415674
Entity-3072x1000: l2_norm              : 1.3298721625913608
-------------------------------------------
Entity-3072x1000: progress              : 40%
Entity-3072x1000: err_rms              : 0.01058841405113503
Entity-3072x1000: l2_norm              : 1.5288169639238387
-------------------------------------------
Entity-3072x1000: progress              : 50%
Entity-3072x1000: err_rms              : 0.00986726957642972
Entity-3072x1000: l2_norm              : 1.7029699264232399
-------------------------------------------
Entity-3072x1000: progress              : 60%
Entity-3072x1000: err_rms              : 0.009504170593046151
Entity-3072x1000: l2_norm              : 1.8587403623954033
-------------------------------------------
Entity-3072x1000: progress              : 70%
Entity-3072x1000: err_rms              : 0.00937478017210766
Entity-3072x1000: l2_norm              : 2.001294366568918
-------------------------------------------
Entity-3072x1000: progress              : 80%
Entity-3072x1000: err_rms              : 0.009445592954505021
Entity-3072x1000: l2_norm              : 2.136575538987471
-------------------------------------------
Entity-3072x1000: progress              : 90%
Entity-3072x1000: err_rms              : 0.009670874959303808
Entity-3072x1000: l2_norm              : 2.2696919260061494
-------------------------------------------
Entity-3072x1000: progress              : 100%
Entity-3072x1000: err_rms              : 0.010008802861072641
Entity-3072x1000: l2_norm              : 2.4032857438010122
-------------------------------------------
Entity-3072x1000: progress              : 100%
Entity-3072x1000: err_rms_total              : 0.01003508439875138
Entity-3072x1000: l2_norm              : 2.4098625439188455
results/cifar_test-0-state.npz saved successfully!
In [45]:
# Plot reconstructions
fig, axes = plt.subplots(n_side, n_side, figsize=(30,30))
index = 0             
for x in range(n_side):
    for y in range(n_side):
        inp = train_images[image_indices[index]]
        recon = model.backward(model.forward(inp))
        recon -= np.min(recon)
        recon = recon / np.max(recon)
        img = np.reshape(recon, (3, 32, 32))
        img = img.transpose((1,2,0))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
In [46]:
# Plot weights
weights = model.unit1.state.w_hv
n, n_hid = weights.shape
weight_indices = np.array(random.sample(range(n_hid), n_side*n_side))
w = np.reshape(weights, (3, 32, 32, n_hid))
print(w.shape)
fig, axes = plt.subplots(n_side, n_side, figsize=(30,30))

index = 0
for x in range(n_side):
    for y in range(n_side):
        inp = np.asnumpy(w[:,:,:, weight_indices[index]])
        inp -= np.min(inp)
        inp = inp / np.max(inp)
        img = inp.transpose((1,2,0))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
(3, 32, 32, 1000)
In [ ]:
In [ ]: