1.3 MiB
1.3 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, sample_gaussian
from rbm.torch import Optimizer
import math
import randomIn [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, 400), 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 [14]:
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! ------------------------------------------- Entity-3072x400: progress : 0% Entity-3072x400: err_rms : 0.03860637172744221 Entity-3072x400: l2_norm : 2.1753148860508387 ------------------------------------------- Entity-3072x400: progress : 10% Entity-3072x400: err_rms : 0.03823344006740969 Entity-3072x400: l2_norm : 2.1992568184130117 ------------------------------------------- Entity-3072x400: progress : 20% Entity-3072x400: err_rms : 0.037882774965523176 Entity-3072x400: l2_norm : 2.221242814009932 ------------------------------------------- Entity-3072x400: progress : 30% Entity-3072x400: err_rms : 0.03757602260910126 Entity-3072x400: l2_norm : 2.242895171223946 ------------------------------------------- Entity-3072x400: progress : 40% Entity-3072x400: err_rms : 0.03730573575081962 Entity-3072x400: l2_norm : 2.2626610706425287 ------------------------------------------- Entity-3072x400: progress : 50% Entity-3072x400: err_rms : 0.03702085760998354 Entity-3072x400: l2_norm : 2.2831975750000013 ------------------------------------------- Entity-3072x400: progress : 60% Entity-3072x400: err_rms : 0.036773336659912774 Entity-3072x400: l2_norm : 2.30196740798763 ------------------------------------------- Entity-3072x400: progress : 70% Entity-3072x400: err_rms : 0.0365572258948186 Entity-3072x400: l2_norm : 2.320117957253243 ------------------------------------------- Entity-3072x400: progress : 80% Entity-3072x400: err_rms : 0.03635707657082305 Entity-3072x400: l2_norm : 2.3369796772827143 ------------------------------------------- Entity-3072x400: progress : 90% Entity-3072x400: err_rms : 0.03617011045486411 Entity-3072x400: l2_norm : 2.353752597680696 ------------------------------------------- Entity-3072x400: progress : 100% Entity-3072x400: err_rms : 0.03599139976234781 Entity-3072x400: l2_norm : 2.370133915171288 ------------------------------------------- Entity-3072x400: progress : 100% Entity-3072x400: err_rms_total : 0.03597156477259298 Entity-3072x400: l2_norm : 2.3722468859257866 results/cifar_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, (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, 400)
In [11]:
In [ ]:
In [ ]: