interaction.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the 'License');
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an 'AS IS' BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. #
  16. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
  17. #
  18. # Licensed under the Apache License, Version 2.0 (the "License");
  19. # you may not use this file except in compliance with the License.
  20. # You may obtain a copy of the License at
  21. #
  22. # http://www.apache.org/licenses/LICENSE-2.0
  23. #
  24. # Unless required by applicable law or agreed to in writing, software
  25. # distributed under the License is distributed on an "AS IS" BASIS,
  26. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27. # See the License for the specific language governing permissions and
  28. # limitations under the License.
  29. #
  30. import tensorflow as tf
  31. class DotInteractionGather(tf.keras.layers.Layer):
  32. def __init__(self, num_features):
  33. super(DotInteractionGather, self).__init__()
  34. self.num_features = num_features
  35. self.indices = []
  36. for i in range(self.num_features):
  37. for j in range(i):
  38. self.indices.append(i * num_features + j)
  39. def call(self, features, bottom_mlp_out=None):
  40. interactions = tf.matmul(features, features, transpose_b=True)
  41. interactions = tf.reshape(interactions, shape=[-1, self.num_features * self.num_features])
  42. x = tf.gather(params=interactions, indices=self.indices, axis=1)
  43. if bottom_mlp_out is not None:
  44. x = tf.concat([bottom_mlp_out, x], axis=1)
  45. return x