Tensorflow implements a value method that modifies specific elements of a tensor

  • 2020-11-30 08:25:39
  • OfStack

Recently, I encountered a lot of minor problems in the process of a project to generate an abstract. I consulted many other people's solutions to different problems on the Internet, and I also opened a small experiment of jupyter notebook next to it. Here Is a summary of some problems I met in the following part.

Tensorflow doesn't work very well, largely because tensor isn't as intuitive as arrays or lists. print only sees Tensor. That's the hint. For example, if we want to change a value in a particular position of a tensor, it's a little bit more difficult to do 1. Like array1, tensors can also be read in sections, such as tensor[1:10] and tensor[:3]. Such operations are supported, but tensors cannot directly modify values.

For example, if array, one assignment statement can modify the value of an element, but if tensor is treated in the same way, an error will be reported:


import tensorflow as tf
tensor_1 = tf.constant([x for x in range(1,10)])
# tensor_1  is 1 A value for 1 to 9 I want to put the middle first 5 Change the number to 0 
tensor_1[4] = 0 

An error will be reported. The error type is:


TypeError: 'Tensor' object does not support item assignment

So tensor can be read piecemeal, but not directly modified, a bit like "read only" mode. How do you solve it? I've come up with one from other blogs, and then another for myself:


#  methods 1  :   using concat function 
tensor_1 = tf.constant([x for x in range(1,10)])
#  I'm going to break up the original tensor into 3 Section, the section before changing the location, the section to be changed, and the section after changing the location 
i = 4
part1 = tensor_1[:i]
part2 = tensor_1[i+1:]
val = tf.constant([0])
new_tensor = tf.concat([part1,val,part2], axis=0)

And then if I print this out, I can see that the fifth number has become a 0.


#  methods 2 Use: one_hot To add and subtract 
tensor_1 = tf.constant([x for x in range(1,10)])
i = 4
#  generate 1 a one_hot The tensors, the lengths and tensor_1 Same, change the position to 1
shape = tensor_1.get_shape().as_list()
one_hot = tf.one_hot(i,shape[0],dtype=tf.int32)
#  do 1 Minus one, minus two one_hot for 1 Theta becomes the original tensor and the value at that position is subtracted 
new_tensor = tensor_1 - tensor_1[i] * one_hot

Of course, tensor has one assign function, but each update is not for the relative position, but rather a re-assignment of the entire variable, and in some cases this native function doesn't seem to work very well.


Related articles: