首页 > 解决方案 > Tensorflow 无法正确将字符串(浮点数)转换为 Int

问题描述

例如我有这个string张量:

s = tf.constant('154.0', dtype=tf.string)

我想将其转换为tf.int32张量:

tf.strings.to_number(s, out_type=tf.int32)

但我收到以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: StringToNumberOp could not correctly convert string: 154.0 [Op:StringToNumber]

为什么会这样?是因为字符串 '154.0' 包含小数吗?

标签: python-3.xstringtensorflowfloating-point

解决方案


我的猜测是,您指定的字符串编号被视为浮点数,而您要求直接转换为 int。您可以尝试:

  • 传递一个表示 int 的字符串,看看它是否有效(它应该);或者
  • 让 tensorflow 在不指定 的情况下进行自动转换out_type,然后将输出张量转换为 int32,例如使用 tf.cast https://www.tensorflow.org/api_docs/python/tf/cast

推荐阅读