【问题标题】:Extract one hot encoding from a file into a dataset从文件中提取一个热编码到数据集中
【发布时间】:2018-11-15 13:37:59
【问题描述】:

我有一个数据集图像和相应的标签,每个图像文件都有一个 .txt 文件,其中包含一个热编码:

0
0
0
0
1
0

我的代码如下所示:

imageString = tf.read_file('image.jpg')
imageDecoded = tf.image.decode_jpeg(imageString)

labelString = tf.read_file(labelPath)
# decode csv string

但 labelString 看起来像这样:

tf.Tensor(b'0\n0\n0\n0\n1\n', shape=(), dtype=string)

有没有办法将其转换为 tensorflow 中的数字数组?

【问题讨论】:

    标签: python tensorflow tensorflow-datasets


    【解决方案1】:

    这是一个执行此操作的函数。

    import tensorflow as tf
    
    def read_label_file(labelPath):
        # Read file
        labelStr = tf.io.read_file(labelPath)
        # Split string (returns sparse tensor)
        labelStrSplit = tf.strings.split([labelStr])
        # Convert sparse tensor to dense
        labelStrSplitDense = tf.sparse.to_dense(labelStrSplit, default_value='')[0]
        # Convert to numbers
        labelNum = tf.strings.to_number(labelStrSplitDense)
        return labelNum
    

    一个测试用例:

    import tensorflow as tf
    
    # Write file for test
    labelPath = 'labelData.txt'
    labelTxt = '0\n0\n0\n0\n1\n0'
    with open(labelPath, 'w') as f:
        f.write(labelTxt)
    # Test the function
    with tf.Session() as sess:
        label_data = read_label_file(labelPath)
        print(sess.run(label_data))
    

    输出:

    [0. 0. 0. 0. 1. 0.]
    

    注意这个函数,正如我写的那样,使用了一些新的 API 端点,你也可以像下面这样编写它以获得更多的向后兼容性,含义几乎相同(tf.strings.split 和 @ 之间存在细微差别987654322@):

    import tensorflow as tf
    
    def read_label_file(labelPath):
        labelStr = tf.read_file(labelPath)
        labelStrSplit = tf.string_split([labelStr], delimiter='\n')
        labelStrSplitDense = tf.sparse_to_dense(labelStrSplit.indices,
                                                labelStrSplit.dense_shape,
                                                labelStrSplit.values, default_value='')[0]
        labelNum = tf.string_to_number(labelStrSplitDense)
        return labelNum
    

    【讨论】:

      【解决方案2】:

      您可以使用基本的 python 命令并将其转换为张量。试试……

      with open(labelPath) as f:
          lines = f.readlines()
          lines = [int(l.strip()) for l in lines if l.strip()]
      labelString = tf.convert_to_tensor(lines, dtype='int32')
      

      【讨论】:

      • 在python中有很多方法可以做到,我想知道是否有使用tensorflow框架的方法。
      • 我不知道单行类型的操作可以做到这一点。 Tensorflow 的字符串处理设置不好,但如果你真的需要使用 TF,看看这篇文章...stackoverflow.com/questions/47022987/…
      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2020-06-25
      • 2021-01-16
      • 2019-05-02
      • 2021-07-05
      • 2014-10-15
      相关资源
      最近更新 更多