Matrices (or tensors) of different dimensions can be added to numpy and tensorflow if the shape of the smaller matrix is ββthe suffix of the larger matrix. This is an example:
x = np.ndarray(shape=(10, 7, 5), dtype = float) y = np.ndarray(shape=(7, 5), dtype = float)
For these two matrices, the operation x+y is a shortcut for:
for a in range(10): for b in range(7): for b in range(5): result[a,b,c] = x[a,b,c] + y[b,c]
In my case, however, I have form matrices (10,7,5) and (10,5) , and I would also like to perform the + operation using the same logic:
for a in range(10): for b in range(7): for b in range(5): result[a,b,c] = x[a,b,c] + y[a,c] ^
In this case, however, the operation x+y fails because neither numpy nor tensorflow understand what I want to do. Is there a way I can efficiently perform this operation (don't write the python loop itself)?
So far, I realized that I can introduce a temporal matrix z form (10,7,5) using einsum as follows:
z = np.einsum('ij,k->ikj', y, np.ones(7)) x + z
but this creates an explicit three-dimensional matrix (or tensor), and, if possible, I would rather avoid this.