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!
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()