tensorflow - 为什么我们需要 tf.convert_to_tensor?

标签 tensorflow

我在(https://www.tensorflow.org/guide/eager)中看到了以下代码:

def fizzbuzz(max_num):
  counter = tf.constant(0)
  max_num = tf.convert_to_tensor(max_num)
  for num in range(1, max_num.numpy()+1):
    num = tf.constant(num)
    if int(num % 3) == 0 and int(num % 5) == 0:
      print('FizzBuzz')
    elif int(num % 3) == 0:
      print('Fizz')
    elif int(num % 5) == 0:
      print('Buzz')
    else:
      print(num.numpy())
    counter += 1


fizzbuzz(15)

为什么max_num需要转换张量?

最佳答案

在这个例子中,它仅用于一个简单的演示目的(即展示 Eager 如何工作) - 否则,它是多余的。如果问题是“为什么使用张量是 Eager?” - TensorFlow 操作只能在张量实例上运行(例如 TensorEagerTensor) - 即使在 Eager 执行中也是如此。 Eager 实际上并不缺乏图表 - 它主要是图表,“执行图表”。

至于“为什么”——很长的问题,但简短的答案是“优化”;在实际执行之前,TensorFlow 会智能地组织输入并进行类型转换,这样做需要输入具有某些属性和方法,这些属性和方法在转换为张量后会被继承。当使用高级操作时,这是自动完成的,但如果编写自定义功能(例如优化器),您可能需要手动转换。

关于tensorflow - 为什么我们需要 tf.convert_to_tensor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897927/

相关文章:

python-3.x - Keras 播种 ImageDataGenerator 与序列

python-3.x - Tensorflow v2 alpha 中的投影仪

Tensorflow 摘要标量未显示在 tensorboard 中

python - tensorflow - 输入到 StringToHashBucketFast 操作类型错误

python - 如何保存 Keras 回归模型?

python - 即使没有正则化,Keras Loss 和 Metric 中的相同函数也会给出不同的值

python - tensorflow :cannot be accessed here: it is defined in another function or code block

python - 如何屏蔽张量中每一行的特定切片

python - 值错误 : Input 0 of node incompatible with expected float_ref. **

python - 在 tensorflow 中使用一个批量大小?