Files
pyRBM/mnist_test.ipynb
T
2026-06-02 08:36:21 +02:00

681 KiB

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 compat.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 [89]:
N = 60000
size = 784
n_side = 10
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 [90]:
print(len(train_images))
image_indices = np.random.randint(0, N-1, n_side*n_side)
60000
In [91]:
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 = np.reshape(inp, (28, 28))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
In [92]:
class TestModel(Model):
	def __init__(self, name: str, work_dir: str = '.'):
		super().__init__(name, work_dir)
		self.unit1 = Entity((28*28, 100), EntityParams(do_gaussian_visible=False, do_gaussian_hidden=False), TrainingParams(learning_rate=0.1, momentum=0.9, num_epochs=10000, mini_batch_size=1000, l1_lambda=0.004, do_rao_blackwell=True), True)
#		self.unit2 = Entity((500, 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 [93]:
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!
-------------------------------------------
Entity-784x100: progress              : 0%
Entity-784x100: err_rms              : 0.014414508244480833
Entity-784x100: l2_norm              : 25.413601322380156
-------------------------------------------
Entity-784x100: progress              : 10%
Entity-784x100: err_rms              : 0.016305932137787714
Entity-784x100: l2_norm              : 18.362961748495835
-------------------------------------------
Entity-784x100: progress              : 20%
Entity-784x100: err_rms              : 0.01620548503399525
Entity-784x100: l2_norm              : 18.48548452029196
-------------------------------------------
Entity-784x100: progress              : 30%
Entity-784x100: err_rms              : 0.016206704015135853
Entity-784x100: l2_norm              : 18.482700817069272
-------------------------------------------
Entity-784x100: progress              : 40%
Entity-784x100: err_rms              : 0.016202401468158593
Entity-784x100: l2_norm              : 18.4855822431084
-------------------------------------------
Entity-784x100: progress              : 50%
Entity-784x100: err_rms              : 0.01620215643869973
Entity-784x100: l2_norm              : 18.486069147676194
-------------------------------------------
Entity-784x100: progress              : 60%
Entity-784x100: err_rms              : 0.016202034096700593
Entity-784x100: l2_norm              : 18.486323079421453
-------------------------------------------
Entity-784x100: progress              : 70%
Entity-784x100: err_rms              : 0.016201959457167476
Entity-784x100: l2_norm              : 18.486481204151325
-------------------------------------------
Entity-784x100: progress              : 80%
Entity-784x100: err_rms              : 0.01623254730225882
Entity-784x100: l2_norm              : 18.47969998768271
-------------------------------------------
Entity-784x100: progress              : 90%
Entity-784x100: err_rms              : 0.01623250724701853
Entity-784x100: l2_norm              : 18.47978577224968
-------------------------------------------
Entity-784x100: progress              : 100%
Entity-784x100: err_rms              : 0.016232475519207378
Entity-784x100: l2_norm              : 18.479853839350724
-------------------------------------------
Entity-784x100: progress              : 100%
Entity-784x100: err_rms_total              : 0.01627253394868903
Entity-784x100: l2_norm              : 18.477539124418225
results/mnist_test-0-state.npz saved successfully!
In [94]:
# 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, (28, 28))
        axes[x,y].imshow(np.asnumpy(img))
        axes[x,y].axis('off')
        index += 1

plt.show()
In [95]:
# Plot weights
weights = model.unit1.state.w_hv
n, n_hid = weights.shape
weight_indices = np.random.randint(0, N-1, n_hid)
w = np.reshape(weights, (28, 28, 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]])
        axes[x,y].imshow(inp)
        axes[x,y].axis('off')
        index += 1

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