Use tf.tensor_scatter_nd_min to copy element-wise minimum values from one tensor to another. # Convert the tensor into an identity matrix Similarly, use tf.tensor_scatter_nd_sub to subtract values from a tensor with pre-existing values. # Convert the tensor into a magic square by inserting numbers at appropriate indices To insert data into a tensor with pre-existing values, use tf.tensor_scatter_nd_add. # Convert the sparse tensor into a dense tensor This is similar to: t9 = tf.SparseTensor(indices=,, ], T8 = tf.scatter_nd(indices=new_indices, updates=t7, shape=tf.constant()) T7 = tf.gather_nd(t2, indices=new_indices) # Gather values from one tensor by specifying indices You can use tf.gather_nd and tf.scatter_nd to mimic the behavior of sparse tensor ops.Ĭonsider an example where you construct a sparse tensor using these two methods in conjunction. Methods like tf.scatter_nd which require zero-initialized tensors are similar to sparse tensor initializers. Note that the tensor into which you insert values is zero-initialized. Use tf.scatter_nd to insert data at specific slices/indices of a tensor. This is useful when you want to gather the elements of a matrix as opposed to just its rows or columns.
To extract slices from multiple axes of a tensor, use tf.gather_nd. alphabet = tf.constant(list('abcdefghijklmnopqrstuvwxyz')) Tf.gather does not require indices to be evenly spaced.
Use tf.gather to extract specific indices from a single axis of a tensor. You can also use tf.strided_slice to extract slices of tensors by 'striding' over the tensor dimensions. You can use tf.slice on higher dimensional tensors as well. print(t1)įor 2-dimensional tensors,you can use something like: t2 = tf.constant(, Note that tensor slices are evenly spaced over a start-stop range. Tf.Tensor(, shape=(3,), dtype=int32)Īlternatively, you can use a more Pythonic syntax. Perform NumPy-like tensor slicing using tf.slice. Read the indexing sections of the Tensor and TensorFlow NumPy guides before getting started with this guide. This guide assumes familiarity with tensor indexing. Insert data at specific indices in a tensor.
In this guide, you will learn how to use the TensorFlow APIs to: For example, you can generate training data from a list of sentences by choosing a word index to mask in each sentence, taking the word out as a label, and then replacing the chosen word with a mask token. In NLP applications, you can use tensor slicing to perform word masking while training. In this case, you could use tensor slicing ops to split the tensors up and put them back together in the right order. For example, if your model architecture includes routing, where one layer might control which training example gets routed to the next layer. When working on ML applications such as object detection and NLP, it is sometimes necessary to work with sub-sections (slices) of tensors.