diff --git a/src/rbm/image.py b/src/rbm/image.py new file mode 100644 index 0000000..6884603 --- /dev/null +++ b/src/rbm/image.py @@ -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 diff --git a/src/tests/test_linear.py b/src/tests/test_linear.py index 597c183..1796eb7 100644 --- a/src/tests/test_linear.py +++ b/src/tests/test_linear.py @@ -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() diff --git a/src/tests/test_sub_image.py b/src/tests/test_sub_image.py new file mode 100644 index 0000000..0fc0885 --- /dev/null +++ b/src/tests/test_sub_image.py @@ -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]")