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()) |
Yes, the behavior of tf.scatter_nd when there is duplication in index is accumulating, while the fancy indexing in pytorch will just replace the value.
Does anyone know how to achieve the same as tf.scatter_nd using torch.Tensor.scatter_add_ ?
I already ask in this thread: https://discuss.pytorch.org/t/how-to-implement-tf-scatter-nd-function-of-tensorflow-in-pytorch/18358/5
You can use index_add_
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
Thas has a mistake. Test with indices = ([[0, 1], [0, 1]])