【问题标题】:Is there difference between 1 and 1.0 in tensorflow?张量流中的1和1.0有区别吗?
【发布时间】:2020-01-03 18:45:05
【问题描述】:

我找到了有关自定义指标的摘要。

smooth = 0.001
dices = (2. * a + smooth) / (a+ b+ smooth)

ratio = a/ (K.sum(a) + smooth)
ratio = 1.0 - ratio

为什么作者更喜欢浮点数(如2.1.0)而不是整数(21)? 而且我发现很多人更喜欢使用浮点数而不是整数,我不知道为什么。

我猜this是不是原因?

【问题讨论】:

  • 我认为它们会被自动转换,但是如果你没有输入正确的类型,有些语言可能会引发问题。我还认为 Python 2 与 Python 3 的工作方式略有不同。所以为了安全起见,最好让它保持浮动。

标签: python tensorflow keras loss


【解决方案1】:

下面的代码将显示两者之间的区别。

t1 = tf.constant(value=1)
t1.dtype

输出 tf.int32

t2 = tf.constant(value=1.0)
t2.dtype

输出 tf.float32

现在添加这两个张量将引发错误,因为这两个张量的数据类型不同。

t3 = tf.add(x=t1, y=t2)

输出:

Traceback(最近一次调用最后一次): _apply_op_helper 中的文件“c:\ProgramData\Anaconda3\envs\tensorflow_cpu\lib\site-packages\tensorflow\python\framework\op_def_library.py”,第 527 行 首选dtype=default_dtype) 文件“c:\ProgramData\Anaconda3\envs\tensorflow_cpu\lib\site-packages\tensorflow\python\framework\ops.py”,第 1224 行,internal_convert_to_tensor ret = conversion_func(值,dtype=dtype,name=name,as_ref=as_ref) _TensorTensorConversionFunction 中的文件“c:\ProgramData\Anaconda3\envs\tensorflow_cpu\lib\site-packages\tensorflow\python\framework\ops.py”,第 1018 行 (dtype.name, t.dtype.name, str(t))) ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("Const_4:0", shape=(), dtype=float32)'

【讨论】:

  • 谢谢。我知道在 python 中,t1=1;t2=1.0;t3=t1+t2 是可以的,因为 python 会自动将整数转换为浮点数。但我不知道tensorflow不能做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多