I have 2 numpy 3D arrays: A of shape (X, Y, Z) and B of shape (X, Y, 1). I need to perform dot product of each column of A with the single column of B, obtaining another array C of shape (X, Z).
I managed do achieve the results by allocating C, iterating over the 1st shape (X) and saving the results during the loop.
Here is a sample code:
import numpy as np
np.random.seed(10)
x, y, z = 7, 2048, 10
a = np.random.randint(0, 10, (x, y, z))
b = np.random.randint(0, 10, (x, y, 1))
c = np.zeros((x, z))
for i in range(x):
c[i] = np.dot(b[i].T, a[i])
print(c)
With the output:
[[40223. 42505. 41040. 40772. 41213. 40311. 41813. 41632. 40578. 40859.]
[40984. 42119. 41512. 40948. 40725. 40222. 41182. 42255. 41916. 41948.]
[41824. 41908. 42118. 39690. 40537. 41394. 42446. 41598. 40710. 42171.]
[41664. 41949. 40847. 39915. 41888. 41565. 40992. 41354. 41227. 41948.]
[42766. 41490. 41291. 42317. 40691. 41544. 41440. 41111. 42395. 40857.]
[41714. 40661. 41421. 42129. 42115. 42189. 41941. 41541. 41957. 42574.]
[41236. 40527. 41599. 40372. 40897. 41287. 41953. 40968. 41700. 42033.]]
For low values of (X, Y, Z) the process is quite fast, but usually I work with large sample sets, which makes the solution poorly optimized.
So, despite the fact the code above is working for me, I believe there is another (better) way to get the same results, maybe using matmul or tensordot, but I couldn't figure out how to properly use those functions.