Files
pyRBM/cifar_test.ipynb
T
jens 9f72c1f253 - added cifar_test as jupiter lab
- started torch version of RBM
- enable CUDA in matrix
2026-01-04 18:30:01 +01:00

1.2 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
from rbm.torch import Optimizer
import math
In [2]:
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (1.0, 1.0, 1.0))                            
])                              
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]:
image, label = train_data[0]
In [5]:
print(label)
6
In [6]:
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=(1.0, 1.0, 1.0))
           )
In [7]:
dim = image.size()
print(dim)
torch.Size([3, 32, 32])
In [ ]:
In [8]:
N = 100
image, label = train_data[0]
size = len(torch.flatten(image))
train_images = np.zeros(shape=(N, size))
train_images_tensor = torch.Tensor(N, size)
#train_labels = np.zeros(shape=(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
#    train_labels[i, :] = torch.flatten(label).numpy()
In [9]:
print(len(train_images))
100
In [10]:
n_side = int(math.sqrt(len(train_images)))
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[index]
        img = (0.5 + np.reshape(inp, (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]:
class TestModel(Model):
	def __init__(self, name: str, work_dir: str = '.'):
		super().__init__(name, work_dir)
		self.unit1 = Entity((3072, 96), EntityParams(do_gaussian_visible=True, do_gaussian_hidden=True), TrainingParams(do_rao_blackwell=True, learning_rate=0.00004, momentum=0.9, num_epochs=1000, do_batch_sample=False, mini_batch_size=100))

	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 [28]:
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!
-------------------------------------------
progress              : 0%
err_rms              : 6.39629894725141e-05
-------------------------------------------
progress              : 10%
err_rms              : 6.396054836124522e-05
-------------------------------------------
progress              : 20%
err_rms              : 6.395780753128475e-05
-------------------------------------------
progress              : 30%
err_rms              : 6.395504820323911e-05
-------------------------------------------
progress              : 40%
err_rms              : 6.395229806888158e-05
-------------------------------------------
progress              : 50%
err_rms              : 6.394955707973693e-05
-------------------------------------------
progress              : 60%
err_rms              : 6.394682518781539e-05
-------------------------------------------
progress              : 70%
err_rms              : 6.394410234560418e-05
-------------------------------------------
progress              : 80%
err_rms              : 6.39413614129685e-05
-------------------------------------------
progress              : 90%
err_rms              : 6.393865661883024e-05
-------------------------------------------
progress              : 100%
err_rms              : 6.393596073417932e-05
-------------------------------------------
progress              : 100%
err_rms_total              : 6.393587999481262e-05
results/cifar_test-0-state.npz saved successfully!
In [29]:
n_side = int(math.sqrt(len(train_images)))
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[index]
        recon = model.backward(model.forward(inp))
        recon -= np.min(recon)
        recon = recon / np.max(recon) - 0.5
        img = (0.5 + 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 [14]:
# torch style
In [27]:
optimizer = Optimizer(model.unit1)
report_interval = 1000
next_ep = report_interval
for epoch in range(6000):
    running_loss = 0.0

    optimizer.zero_grad()
    optimizer.step(train_images)

    if epoch >= next_ep:
        print(f'Training epoch {epoch}...')
        next_ep += report_interval
        # Update final status
        err_rms = rms_error_accu(train_images - model.unit1.reconstruct(model.unit1.forward(train_images)))
        print(err_rms)

model.save()
Training epoch 1000...
6.397701150028974e-05
Training epoch 2000...
6.397418812761233e-05
Training epoch 3000...
6.397137429020308e-05
Training epoch 4000...
6.39685699360804e-05
Training epoch 5000...
6.396577501381398e-05
results/cifar_test-0-state.npz saved successfully!
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: