Files
pyRBM/mnist_test.ipynb
T
2026-01-06 20:20:43 +01:00

1.9 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()
])                              
In [3]:
train_data = torchvision.datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_data = torchvision.datasets.MNIST(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(len(train_data))
60000
In [5]:
print(list(train_data[1][0].size()[1:3]))
[28, 28]
In [6]:
N = 400
size = 784
train_images = np.zeros(shape=(N,size))
for i in range(N):
    image = train_data[i][0]
    flat_array = torch.flatten(image)
    train_images[i, :] = np.asarray(flat_array.numpy())
In [7]:
print(len(train_images))
400
In [45]:
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 = np.reshape(inp, (28, 28))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
In [78]:
class TestModel(Model):
	def __init__(self, name: str, work_dir: str = '.'):
		super().__init__(name, work_dir)
		self.unit1 = Entity((28*28, 256), EntityParams(do_gaussian_visible=False, do_gaussian_hidden=False), TrainingParams(learning_rate=0.01, momentum=0.9, num_epochs=1000, mini_batch_size=100, l2_lambda=0.001), True)
		self.unit2 = Entity((256, 64), EntityParams(do_gaussian_visible=False, do_gaussian_hidden=False), TrainingParams(learning_rate=0.04, momentum=0.9, num_epochs=1000, mini_batch_size=100, l2_lambda=0.01, do_rao_blackwell=True), True)

	def forward(self, x: Mat):
		x = self.unit1.forward(x)
		x = self.unit2.forward(x)
		return x

	def backward(self, x: Mat):
		x = self.unit2.reconstruct(x)
		x = self.unit1.reconstruct(x)
		return x
In [79]:
work_dir = "results"
prj_name = "mnist_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/mnist_test-0-state.npz loaded successfully!
results/mnist_test-1-state.npz loaded successfully!
-------------------------------------------
Entity-784x256: progress              : 0%
Entity-784x256: err_rms              : 0.015949393574587772
Entity-784x256: l2_norm            : 3.8615969789950464
-------------------------------------------
Entity-784x256: progress              : 10%
Entity-784x256: err_rms              : 0.015411270729369046
Entity-784x256: l2_norm            : 4.167718490826528
-------------------------------------------
Entity-784x256: progress              : 20%
Entity-784x256: err_rms              : 0.014926581427654819
Entity-784x256: l2_norm            : 4.456437830378319
-------------------------------------------
Entity-784x256: progress              : 30%
Entity-784x256: err_rms              : 0.0145076824384412
Entity-784x256: l2_norm            : 4.7164593538236925
-------------------------------------------
Entity-784x256: progress              : 40%
Entity-784x256: err_rms              : 0.01413643544283359
Entity-784x256: l2_norm            : 4.953451561969137
-------------------------------------------
Entity-784x256: progress              : 50%
Entity-784x256: err_rms              : 0.013809319218789529
Entity-784x256: l2_norm            : 5.172301309731615
-------------------------------------------
Entity-784x256: progress              : 60%
Entity-784x256: err_rms              : 0.013507247769801743
Entity-784x256: l2_norm            : 5.374835714867623
-------------------------------------------
Entity-784x256: progress              : 70%
Entity-784x256: err_rms              : 0.013233586762416512
Entity-784x256: l2_norm            : 5.563682055240251
-------------------------------------------
Entity-784x256: progress              : 80%
Entity-784x256: err_rms              : 0.012980008455386528
Entity-784x256: l2_norm            : 5.739721536791577
-------------------------------------------
Entity-784x256: progress              : 90%
Entity-784x256: err_rms              : 0.012741733003719852
Entity-784x256: l2_norm            : 5.9056127860458645
-------------------------------------------
Entity-784x256: progress              : 100%
Entity-784x256: err_rms              : 0.012522670121807392
Entity-784x256: l2_norm            : 6.06128298874133
-------------------------------------------
Entity-784x256: progress              : 100%
Entity-784x256: err_rms_total              : 0.01251268881635691
Entity-784x256: l2_norm            : 6.068525883956127
-------------------------------------------
Entity-256x64: progress              : 0%
Entity-256x64: err_rms              : 0.01704636653175391
Entity-256x64: l2_norm            : 19.59481491615667
-------------------------------------------
Entity-256x64: progress              : 10%
Entity-256x64: err_rms              : 0.019203550940033183
Entity-256x64: l2_norm            : 15.161709259381848
-------------------------------------------
Entity-256x64: progress              : 20%
Entity-256x64: err_rms              : 0.020990818880152418
Entity-256x64: l2_norm            : 13.323505862432542
-------------------------------------------
Entity-256x64: progress              : 30%
Entity-256x64: err_rms              : 0.021934798468177617
Entity-256x64: l2_norm            : 12.522822664891699
-------------------------------------------
Entity-256x64: progress              : 40%
Entity-256x64: err_rms              : 0.02243226253836121
Entity-256x64: l2_norm            : 12.136472536876186
-------------------------------------------
Entity-256x64: progress              : 50%
Entity-256x64: err_rms              : 0.022703640579269255
Entity-256x64: l2_norm            : 11.933299598650645
-------------------------------------------
Entity-256x64: progress              : 60%
Entity-256x64: err_rms              : 0.02285705365165851
Entity-256x64: l2_norm            : 11.817610650005442
-------------------------------------------
Entity-256x64: progress              : 70%
Entity-256x64: err_rms              : 0.022945356627977666
Entity-256x64: l2_norm            : 11.746815526655983
-------------------------------------------
Entity-256x64: progress              : 80%
Entity-256x64: err_rms              : 0.022994972693456753
Entity-256x64: l2_norm            : 11.700731614026497
-------------------------------------------
Entity-256x64: progress              : 90%
Entity-256x64: err_rms              : 0.023021146647383764
Entity-256x64: l2_norm            : 11.669168176009908
-------------------------------------------
Entity-256x64: progress              : 100%
Entity-256x64: err_rms              : 0.023031545097484445
Entity-256x64: l2_norm            : 11.646739137785838
-------------------------------------------
Entity-256x64: progress              : 100%
Entity-256x64: err_rms_total              : 0.023031560638845035
Entity-256x64: l2_norm            : 11.646252928225284
results/mnist_test-0-state.npz saved successfully!
results/mnist_test-1-state.npz saved successfully!
In [80]:
# Plot reconstructions
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)
        img = np.reshape(recon, (28, 28))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
In [81]:
# Plot weights
weights = model.unit1.state.w_hv
n, n_hid = weights.shape
w = np.reshape(weights, (28, 28, n_hid))
print(w.shape)
n_side = int(math.sqrt(n_hid))
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[:,:, index])
        axes[x,y].imshow(inp)
        axes[x,y].axis('off')
        index += 1

plt.show()
(28, 28, 256)
In [ ]:
In [ ]:
In [ ]: