serengil / LightPHE

A Lightweight Partially Homomorphic Encryption Library for Python
https://bit.ly/46vWz9w
MIT License
59 stars 6 forks source link

Support multi-dimensional vectors (tensors) #15

Open serengil opened 10 months ago

serengil commented 10 months ago

Currently, tensor operations support just 1D vectors. We need to change the following methods.

Instead of a one depth for loop, element wise operations can be calculated as:

def element_wise_multiply(tensor1, tensor2):
    # Make sure both tensors have the same dimensions
    if len(tensor1) == len(tensor2) and all(len(row1) == len(row2) for row1, row2 in zip(tensor1, tensor2)):
        rows = len(tensor1)
        cols = len(tensor1[0])

        result = [[0 for _ in range(cols)] for _ in range(rows)]

        # Perform element-wise multiplication using nested for loop
        for i in range(rows):
            for j in range(cols):
                result[i][j] = tensor1[i][j] * tensor2[i][j]

        return result
    else:
        raise ValueError("Tensors must have the same dimensions for element-wise multiplication.")

# Example usage
tensor1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

tensor2 = [
    [9, 8, 7],
    [6, 5, 4],
    [3, 2, 1]
]

result = element_wise_multiply(tensor1, tensor2)