Inner Product between a Tensor and a Vector
This is an example of how to use the csdl inner function to compute the inner product between a tensor and a vector.
from csdl_om import Simulatorfrom csdl import Modelimport csdlimport numpy as np
class ExampleTensorVector(Model):
def define(self):
m = 3 n = 4 p = 5
# Shape of the vectors vec_shape = (m, )
# Shape of the tensors ten_shape = (m, n, p)
# Values for the two vectors vec1 = np.arange(m)
# Number of elements in the tensors num_ten_elements = np.prod(ten_shape)
# Values for the two tensors ten1 = np.arange(num_ten_elements).reshape(ten_shape)
# Adding the vector and tensor to csdl vec1 = self.declare_variable('vec1', val=vec1) ten1 = self.declare_variable('ten1', val=ten1)
# Tensor-Vector Inner Product specifying the first axis for # Vector and Tensor self.register_output( 'TenVecInner', csdl.inner(ten1, vec1, axes=([0], [0])), )
sim = Simulator(ExampleTensorVector())sim.run()
print('vec1', sim['vec1'].shape)print(sim['vec1'])print('ten1', sim['ten1'].shape)print(sim['ten1'])print('TenVecInner', sim['TenVecInner'].shape)print(sim['TenVecInner'])
[0. 1. 2.]ten1 (3, 4, 5)[[[ 0. 1. 2. 3. 4.] [ 5. 6. 7. 8. 9.] [10. 11. 12. 13. 14.] [15. 16. 17. 18. 19.]]
[[20. 21. 22. 23. 24.] [25. 26. 27. 28. 29.] [30. 31. 32. 33. 34.] [35. 36. 37. 38. 39.]]
[[40. 41. 42. 43. 44.] [45. 46. 47. 48. 49.] [50. 51. 52. 53. 54.] [55. 56. 57. 58. 59.]]]TenVecInner (4, 5)[[100. 103. 106. 109. 112.] [115. 118. 121. 124. 127.] [130. 133. 136. 139. 142.] [145. 148. 151. 154. 157.]]