【问题标题】:How to convert tf.int64 to tf.float32?如何将 tf.int64 转换为 tf.float32?
【发布时间】:2016-02-24 08:13:17
【问题描述】:

我试过了:

test_image = tf.convert_to_tensor(img, dtype=tf.float32)

然后出现如下错误:

ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("test/ArgMax:0", shape=TensorShape([Dimension(None)]), dtype=int64)'

【问题讨论】:

    标签: tensorflow int64


    【解决方案1】:

    您通常可以使用以下方式进行投射:

    tf.cast(my_tensor, tf.float32)
    

    将 tf.float32 替换为您想要的类型。


    编辑:至少目前看来,tf.cast 不会转换为无符号数据类型(例如tf.uint8)。要解决此问题,您可以转换为已签名的等价物并使用 tf.bitcast 一直到。例如

    tf.bitcast(tf.cast(my_tensor, tf.int8), tf.uint8)
    

    【讨论】:

    • 需要注意的是,tf 不能计算这些操作的梯度,所以不能用来模拟量化权重。
    【解决方案2】:

    糟糕,我在 API 中找到了函数...

     tf.to_float(x, name='ToFloat')
    

    【讨论】:

    • tf.to_float() 现已弃用,应使用 tf.cast()
    【解决方案3】:

    您可以使用tf.cast(x, tf.float32)tf.to_float(x),两者都转换为float32。

    例子:

    sess = tf.Session()
    
    # Create an integer tensor.
    tensor = tf.convert_to_tensor(np.array([0, 1, 2, 3, 4]), dtype=tf.int64)
    sess.run(tensor)
    # array([0, 1, 2, 3, 4])
    
    # Use tf.cast()
    tensor_float = tf.cast(tensor, tf.float32)
    sess.run(tensor_float)
    # array([ 0.,  1.,  2.,  3.,  4.], dtype=float32)
    
    # Use tf.to_float() to cast to float32
    tensor_float = tf.to_float(tensor)
    sess.run(tensor_float)
    # array([ 0.,  1.,  2.,  3.,  4.], dtype=float32)
    

    【讨论】:

    • 当我将一个类型为tf.uint8 的法师施放为tf.float32,并使用matplotlib 显示它们时,tf.float32 发生了变化。怎么才能显示主图?
    【解决方案4】:

    imagetype cast 您可以使用tf.image.convert_image_dtype() 将图像范围[0 255] 转换为[0 1]

    img_uint8 = tf.constant([1,2,3], dtype=tf.uint8)
    img_float = tf.image.convert_image_dtype(img_uint8, dtype=tf.float32)
    with tf.Session() as sess:
        _img= sess.run([img_float])
        print(_img, _img.dtype)
    

    输出:

    [0.00392157 0.00784314 0.01176471] float32
    

    如果您只想转换类型并保持值范围,请使用 tf.casttf.to_float 作为 @stackoverflowuser2010 和 @Mark McDonald 回答

    【讨论】:

      【解决方案5】:

      如果您的数据实际上是 Pandas 数据框,我们可以首先使用以下方法检查数据类型:

      print(dataset.dtypes)
      

      要将所有条目转换为float32(例如),

      # Typecast
      dataset = dataset.astype('float32')
      
      #print them to verify
      print(dataset.dtypes)
      

      【讨论】:

        猜你喜欢
        • 2020-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-17
        • 2010-09-08
        • 2013-09-21
        • 2011-05-14
        • 1970-01-01
        相关资源
        最近更新 更多