Created
August 14, 2018 16:03
-
-
Save airalcorn2/c7846d6fcb58a30b25ea6d97e16fe025 to your computer and use it in GitHub Desktop.
Replicating TensorFlow's scatter_nd function in PyTorch.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See: https://www.tensorflow.org/api_docs/python/tf/scatter_nd. | |
# TensorFlow | |
import tensorflow as tf | |
sess = tf.InteractiveSession() | |
indices = tf.constant([[0, 1], [2, 3]]) | |
updates = tf.constant([[5, 5, 5, 5], | |
[6, 6, 6, 6]]) | |
shape = tf.constant([4, 4, 4]) | |
scatter = tf.scatter_nd(indices, updates, shape) | |
print("TensorFlow") | |
print(sess.run(scatter), end = "\n\n") | |
# PyTorch | |
import torch | |
indices = torch.tensor([[0, 1], [2, 3]]) | |
updates = torch.tensor([[5, 5, 5, 5], | |
[6, 6, 6, 6]]) | |
result = torch.zeros((4, 4, 4), dtype = torch.int64) | |
result[indices[:, 0], indices[:, 1]] = updates | |
print("PyTorch") | |
print(result.numpy()) |
this also works:
result[indices.t().numpy()]=updates
do not need torch.Tensor.scatter_()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use index_add_