In my journey to create my own Tensor class (n-dimensional arrays) in typescript, I have devised a structure where the data is stored in a 1D array property, and the shape of the data is stored separately for indexing purposes.
My goal is to develop a function similar to numpy.array
, which takes in multi-dimensional array data, flattens it into a 1D array, and then extracts the shape.
However, it is crucial for this function to validate if the input array has a consistent shape throughout (often referred to as having a "homogeneous shape").
Example 1
For instance, giving the following input to the function:
data = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
]
the expected output would be a tensor with the shape (2, 2, 2) and a flat array of elements [1, 2, 3, ..., 8] representing the data inside the tensor.
Example 2
Conversely, if the input is:
data = [
[[1], [3, 4]],
[[5, 6], [7, 8]],
]
the function should fail to validate the input due to the inconsistent shape with a sub-array containing only the element 1.
Example 3
Similarly, when provided with:
data = [
[[1], 2],
[3, 4],
]
the function should fail for the same reason, as the sub-array containing 1 is inconsistent with the rest of the data.
While numpy.array
is capable of detecting such inconsistencies and raising errors, I am in search of an algorithm or method to achieve the same. Any guidance or assistance in this experimental project would be greatly appreciated.
Note: While I understand that utilizing an existing library for this task would be more efficient, my current endeavor is purely for educational purposes. As I lack extensive knowledge about tensors, any suggestions on where to start or what to learn beforehand would be highly valued.