- added image module with sub image and normalize

- improved tests
This commit is contained in:
2026-01-10 14:12:29 +01:00
parent b6a511e33c
commit f7e3693f45
3 changed files with 68 additions and 4 deletions
+46
View File
@@ -0,0 +1,46 @@
from rbm.matrix import Mat, np
def normalize(image: Mat):
image_shape = image.shape
mean_training_batch = np.reshape(np.repeat(np.mean(image, axis=1), image_shape[1], axis=0), image_shape)
var_training_batch = np.reshape(np.repeat(np.std(image, axis=1), image_shape[1], axis=0), image_shape)
result = (image - mean_training_batch) / var_training_batch
return result
class SubImage:
def __init__(self, sx: int, sy: int, px: int, py: int):
self.sx = sx
self.sy = sy
self.px = px
self.py = py
self.x = 0
self.y = 0
def check(self, image: Mat):
nx = (image.shape[0] - self.sx)
ny = (image.shape[1] - self.sy)
if nx % self.px:
raise ValueError
if ny % self.py:
raise ValueError
nx = int(nx / self.px) + 1
ny = int(ny / self.py) + 1
return nx, ny
def __call__(self, images: Mat):
return self.process_image(images)
def process_image(self, image: Mat):
nx, ny = self.check(image[0, 0, :, :])
result = np.zeros((image.shape[0]*nx*ny, image.shape[1], self.sx, self.sy))
k = 0
for n in range(image.shape[0]):
for x in range(0, image.shape[2] - self.sx + 1, self.px):
for y in range(0, image.shape[3] - self.sy + 1, self.py):
for c in range(image.shape[1]):
si = image[n, c, x:x+self.sx, y:y+self.sy]
result[k, c] = si
k += 1
return result
+3 -4
View File
@@ -1,6 +1,7 @@
from rbm.matrix import Mat, np
from rbm.entity import Entity, EntityParams, TrainingParams
from rbm.model import Model
from rbm.image import normalize
WORK_DIR = "../../results"
USE_OPTIMIZER = True
@@ -45,12 +46,10 @@ def linear():
training_batch = np.random.randn(N_CASES, N_VIS, dtype=np.float64)
# Normalize training data
mean_training_batch = np.reshape(np.repeat(np.mean(training_batch, axis=1), N_VIS, axis=0), training_batch.shape)
var_training_batch = np.reshape(np.repeat(np.std(training_batch, axis=1), N_VIS, axis=0), training_batch.shape)
training_batch = (training_batch - mean_training_batch) / var_training_batch
training_batch_norm = normalize(training_batch)
# Train layer
model.train(training_batch)
model.train(training_batch_norm)
# Save weights
model.save()
+19
View File
@@ -0,0 +1,19 @@
from rbm.image import SubImage
from rbm.matrix import np
if __name__ == "__main__":
n = 2
c = 3
w = 8
h = 8
img = np.reshape(np.linspace(1, n*c*w*h, num=n*c*w*h, dtype=np.float64), (n, c, w, h))
# print(img)
sub = SubImage(4, 4, 1, 1)
images = sub(img)
print(images)
print("Test: [passed]")