Files
pyRBM/cifar_test.ipynb
T
2026-06-02 08:55:16 +02:00

1.4 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 model.model import Model
from rbm.entity import Entity, EntityParams, TrainingParams
from rbm.matrix import Mat, np, rms_error_accu, sample_gaussian
from compat.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 = 5000
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):5000
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 [8]:
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, 200), EntityParams(do_gaussian_visible=True, do_gaussian_hidden=False), TrainingParams(learning_rate=0.005, momentum=0.9, num_epochs=1000, mini_batch_size=1000, weight_decay=0, l1_lambda=0.02))
    
    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 [9]:
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()
-------------------------------------------
Entity-3072x200: progress              : 0%
Entity-3072x200: err_rms              : 0.2541102937994406
Entity-3072x200: l2_norm              : 0.024174341281485913
-------------------------------------------
Entity-3072x200: progress              : 10%
Entity-3072x200: err_rms              : 0.06635407861368535
Entity-3072x200: l2_norm              : 2.3192755385110697
-------------------------------------------
Entity-3072x200: progress              : 20%
Entity-3072x200: err_rms              : 0.06097187709936713
Entity-3072x200: l2_norm              : 3.1144125642656233
-------------------------------------------
Entity-3072x200: progress              : 30%
Entity-3072x200: err_rms              : 0.05931387383730886
Entity-3072x200: l2_norm              : 3.430847521112783
-------------------------------------------
Entity-3072x200: progress              : 40%
Entity-3072x200: err_rms              : 0.05853244563938955
Entity-3072x200: l2_norm              : 3.5877739680199676
-------------------------------------------
Entity-3072x200: progress              : 50%
Entity-3072x200: err_rms              : 0.05803562652932604
Entity-3072x200: l2_norm              : 3.6786742248948707
-------------------------------------------
Entity-3072x200: progress              : 60%
Entity-3072x200: err_rms              : 0.05772415958242122
Entity-3072x200: l2_norm              : 3.7343293957160792
-------------------------------------------
Entity-3072x200: progress              : 70%
Entity-3072x200: err_rms              : 0.05749520925703035
Entity-3072x200: l2_norm              : 3.7695801659754604
-------------------------------------------
Entity-3072x200: progress              : 80%
Entity-3072x200: err_rms              : 0.057303607969140566
Entity-3072x200: l2_norm              : 3.796484573426704
-------------------------------------------
Entity-3072x200: progress              : 90%
Entity-3072x200: err_rms              : 0.05717210018448185
Entity-3072x200: l2_norm              : 3.815633488607796
-------------------------------------------
Entity-3072x200: progress              : 100%
Entity-3072x200: err_rms              : 0.05703341954237235
Entity-3072x200: l2_norm              : 3.833724872236307
-------------------------------------------
Entity-3072x200: progress              : 100%
Entity-3072x200: err_rms_total              : 0.05702366237948212
Entity-3072x200: l2_norm              : 3.8328360678830236
In [10]:
# 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 [11]:
# 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, 200)
In [11]:
In [11]:
In [11]: