Recently in the process of doing a summary of the project to generate a lot of small problems encountered from the Internet access to many other people to solve different problems, their own jupyter notebook on the side of the open to engage in some small experiments, here is a summary of some of the problems encountered.
A big reason why Tensorflow doesn't work so well is that tensors aren't as intuitive as arrays or lists, and you can only see the Tensor(...) prompt if you print it directly. For example, in the following problem, we want to change a value at a specific position in a tensor, which is a bit tricky to do. Like arrays, tensors can be read in segments, for example, tensor[1:10], tensor[:3], this kind of operation is supported, but tensors can't modify values directly.
For example, in the case of an array, a single assignment statement can change the value of an element, but if you use the same method with a tensor, you'll get an error:
import tensorflow as tf tensor_1 = ([x for x in range(1,10)]) # tensor_1 is a tensor with values from 1 to 9, would like to change the fifth value in the middle to 0 tensor_1[4] = 0
This is when an error is reported with the error type:
TypeError: 'Tensor' object does not support item assignment
So the tensor can be read in segments, but not modified directly, kind of like a "read-only" mode. How to solve it? I summarized a method from other blogs, and then thought of another one myself:
# Method 1: Utilize the concat function tensor_1 = ([x for x in range(1,10)]) # Split the original tensor into 3 parts, the part before modifying the position, the part to be modified and the part after modifying the position i = 4 part1 = tensor_1[:i] part2 = tensor_1[i+1:] val = ([0]) new_tensor = ([part1,val,part2], axis=0)
At this point, go back to print, and you can see that the fifth number has become 0.
# Method 2: Use one_hot to add and subtract operations tensor_1 = ([x for x in range(1,10)]) i = 4 # Generate a one_hot tensor with the same length as tensor_1 and modified position 1 shape = tensor_1.get_shape().as_list() one_hot = tf.one_hot(i,shape[0],dtype=tf.int32) # Do a subtraction operation that changes one_hot to one by subtracting the value of the original tensor at that position. new_tensor = tensor_1 - tensor_1[i] * one_hot
Of course, tensor has a function for assign, but he can't target the relative position with each update, but rather it amounts to a reassignment of the whole variable, which doesn't seem to work too well with this self-contained function in certain specific situations.
Above this Tensorflow implementation of the method to modify the value of a specific element of the tensor is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.