Home > database >  Tensorflow gives 0 results
Tensorflow gives 0 results

Time:02-20

I am learning Tensorflow from this github https://colab.research.google.com/github/instillai/TensorFlow-Course/blob/master/codes/ipython/1-basics/tensors.ipynb#scrollTo=TKX2U0Imcm7d Here is an easy tutorial

import numpy as np
import tensorflow as tf


x = tf.constant([[1, 1],
                 [1, 1]])
y = tf.constant([[2, 4],
                 [6, 8]])

# Add two tensors
print(tf.add(x, y), "\n")

# Add two tensors
print(tf.matmul(x, y), "\n")

What I expect is

tf.Tensor(
[[3 5]
 [7 9]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[ 8 12]
 [ 8 12]], shape=(2, 2), dtype=int32) 

However, the results are

Tensor("Add_3:0", shape=(2, 2), dtype=int32) 
Tensor("MatMul_3:0", shape=(2, 2), dtype=int32) 

CodePudding user response:

It does not mean that the values of the tensors are zero. Add_3:0 and MatMul_3:0 are just names of the tensors and you can only use print in Eager Execution to see the values of the tensors. In Graph mode you should use tf.print and you should see the results:

import tensorflow as tf

x = tf.constant([[1, 1],
                [1, 1]])
y = tf.constant([[2, 4],
                [6, 8]])

print(tf.add(x, y), "\n")
print(tf.matmul(x, y), "\n")

# Graph mode
@tf.function
def calculate():
  x = tf.constant([[1, 1],
                  [1, 1]])
  y = tf.constant([[2, 4],
                  [6, 8]])

  tf.print(tf.add(x, y), "\n")

  tf.print(tf.matmul(x, y), "\n")
  return x, y
_, _ = calculate()
tf.Tensor(
[[3 5]
 [7 9]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[ 8 12]
 [ 8 12]], shape=(2, 2), dtype=int32) 

[[3 5]
 [7 9]] 

[[8 12]
 [8 12]] 

Without tf.print, you will see the your output from the function calculate:

Tensor("Add:0", shape=(2, 2), dtype=int32) 

Tensor("MatMul:0", shape=(2, 2), dtype=int32) 

See this guide for more information.

  • Related