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

737 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 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 = 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 [7]:
print(len(train_images))
image_indices = np.random.randint(0, N-1, n_side*n_side)
60000
In [8]:
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 [9]:
class TestModel(Model):
	def __init__(self, name: str, work_dir: str = '.'):
		super().__init__(name, work_dir)
		self.unit1 = Entity((28*28, 2000), EntityParams(do_gaussian_visible=False, do_gaussian_hidden=False), TrainingParams(learning_rate=0.1, momentum=0.9, num_epochs=10, mini_batch_size=1000, l2_lambda=0.000001, 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 [14]:
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-784x2000: progress              : 0%
Entity-784x2000: err_rms              : 0.011345658688025525
Entity-784x2000: l2_norm              : 0.8204909314316488
-------------------------------------------
Entity-784x2000: progress              : 10%
Entity-784x2000: err_rms              : 0.01116823356353982
Entity-784x2000: l2_norm              : 0.8326780556851139
-------------------------------------------
Entity-784x2000: progress              : 20%
Entity-784x2000: err_rms              : 0.011005319056239424
Entity-784x2000: l2_norm              : 0.8452525335038596
-------------------------------------------
Entity-784x2000: progress              : 30%
Entity-784x2000: err_rms              : 0.010847796952849377
Entity-784x2000: l2_norm              : 0.8577021550750525
-------------------------------------------
Entity-784x2000: progress              : 40%
Entity-784x2000: err_rms              : 0.010695956999553493
Entity-784x2000: l2_norm              : 0.8699861630331949
-------------------------------------------
Entity-784x2000: progress              : 50%
Entity-784x2000: err_rms              : 0.010549322218651411
Entity-784x2000: l2_norm              : 0.8821295630296148
-------------------------------------------
Entity-784x2000: progress              : 60%
Entity-784x2000: err_rms              : 0.010407674711569347
Entity-784x2000: l2_norm              : 0.8941347578912914
-------------------------------------------
Entity-784x2000: progress              : 70%
Entity-784x2000: err_rms              : 0.01027079836476334
Entity-784x2000: l2_norm              : 0.9060038495748082
-------------------------------------------
Entity-784x2000: progress              : 80%
Entity-784x2000: err_rms              : 0.010138479205967674
Entity-784x2000: l2_norm              : 0.917738744359132
-------------------------------------------
Entity-784x2000: progress              : 90%
Entity-784x2000: err_rms              : 0.010010506099681684
Entity-784x2000: l2_norm              : 0.9293412422976973
-------------------------------------------
Entity-784x2000: progress              : 100%
Entity-784x2000: err_rms              : 0.009886671703490845
Entity-784x2000: l2_norm              : 0.9408131110877473
-------------------------------------------
Entity-784x2000: progress              : 100%
Entity-784x2000: err_rms_total              : 0.00989524439729295
Entity-784x2000: l2_norm              : 0.9412544234072597
results/mnist_test-0-state.npz saved successfully!
In [15]:
# 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 [16]:
# 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, 2000)
In [ ]: