Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TF 2.0 print tensor values

I'm learning the newest release of Tensorflow (2.0) and I have tried to run a simple code to slice a matrix. Using the decorator @tf.function I made the following class:

class Data:
def __init__(self):
    pass

def back_to_zero(self, input):
    time = tf.slice(input, [0,0], [-1,1])
    new_time = time - time[0][0]
    return new_time

@tf.function
def load_data(self, inputs):
    new_x = self.back_to_zero(inputs)
    print(new_x)

So, when run the code using a numpy matrix, I can't retrieve the numbers.

time = np.linspace(0,10,20)
magntiudes = np.random.normal(0,1,size=20)
x = np.vstack([time, magntiudes]).T


d = Data()
d.load_data(x)

Output:

Tensor("sub:0", shape=(20, 1), dtype=float64)

I need to get this tensor in a numpy format, but TF 2.0 has not the class tf.Session to use run() or eval() methods.

Thanks for any help that you can offer me!

like image 628
Cristóbal Rodrigo Donoso Oliva Avatar asked Mar 22 '19 15:03

Cristóbal Rodrigo Donoso Oliva


People also ask

How do I print tf tensor values?

[A]: To print the value of a tensor without returning it to your Python program, you can use the tf. print() operator, as Andrzej suggests in another answer. According to the official documentation: To make sure the operator runs, users need to pass the produced op to tf.

How do you print a tensor data type?

Print() for printing the type of a Tensor because the Tensor's type does not change during the session run. The Tensor type is determined when you build the graph, so just use print(x. dtype) .

How do you access values in a tensor?

We use Indexing and Slicing to access the values of a tensor. Indexing is used to access the value of a single element of the tensor, whereasSlicing is used to access the values of a sequence of elements. We use the assignment operator to modify the values of a tensor.


1 Answers

Inside the graph indicated by the decorator @tf.function, you can use tf.print to print the values of your tensor.

tf.print(new_x)

Here is how the code can be rewritten

class Data:
    def __init__(self):
        pass

    def back_to_zero(self, input):
        time = tf.slice(input, [0,0], [-1,1])
        new_time = time - time[0][0]
        return new_time

    @tf.function
    def load_data(self, inputs):
        new_x = self.back_to_zero(inputs)
        tf.print(new_x) # print inside the graph context
        return new_x

time = np.linspace(0,10,20)
magntiudes = np.random.normal(0,1,size=20)
x = np.vstack([time, magntiudes]).T

d = Data()
data = d.load_data(x)
print(data) # print outside the graph context

the tensor type outside the tf.decorator context is of type tensorflow.python.framework.ops.EagerTensor. To convert it to a numpy array, you can use data.numpy()

like image 168
edkeveked Avatar answered Oct 05 '22 04:10

edkeveked