【问题标题】:Why does "tf.Variable([.3], tf.float32)" work in tensorflow?为什么“tf.Variable([.3], tf.float32)”在张量流中工作?
【发布时间】:2017-03-20 07:17:54
【问题描述】:

标准用法应该是

tf.Variable([.3], dtype=tf.float32),不是吗?

我在官方文档中看到了tf.Variable([.3], tf.float32)tf.Variable的构造函数原型为

__init__(self, initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None)

如果我们传递参数tf.float32 而不是dtype=tf.float32(关键参数),它怎么知道tf.float32 用于dtype。 python解释器是否检查参数类型?

【问题讨论】:

  • @kaufmanu 给出了它为什么起作用的答案 - 只是为了澄清:这是 TF 文档 tensorflow.org/get_started/get_started 中的一个错误,并且只能在偶然情况下起作用,所以请随时打开错误报告.

标签: python python-2.7 tensorflow


【解决方案1】:

来自tf.Variable的文档:

dtype:如果设置,initial_value 将被转换为给定的类型。 如果None,则将保留数据类型(如果initial_value 是 张量)或convert_to_tensor 将决定。

还有来自convert_to_tensor(value, dtype=None, ...)的文档:

dtype:返回张量的可选元素类型。如果丢失,则 type 是从value 的类型推断出来的。

另外,convert_to_tensor 的文档中有一个示例:

import numpy as np

def my_func(arg):
    arg = tf.convert_to_tensor(arg, dtype=tf.float32)
    return tf.matmul(arg, arg) + arg

# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))

所以,回到您的问题 - Tensorflow 不知道您打算使用 tf.float32,它恰好是 convert_to_tensor 函数默认选择的数据类型。因此,返回的张量具有您期望的数据类型只是巧合。如果例如你调用 tf.Variable([.3], tf.float64) 得到的张量与调用 tf.Variable([.3], tf.float32) 时的 dtype 相同。

事实上,我相信tf.Variable([.3], tf.float32)tf.Variable([.3], tf.float64) 的调用是等价的,因为tf.Variable 的第二个参数是一个布尔值,因此tf.floatX 被转换为一个总是返回True 的布尔值。

【讨论】:

  • 得到它。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 2017-09-19
相关资源
最近更新 更多