从文件中提取一种热编码到数据集中

时间:2018-11-15 13:37:59

标签: python tensorflow tensorflow-datasets

我有一个数据集图像和相应的标签,其中每个图像文件都有一个.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)

是否可以将其转换为张量流中的数字数组?

2 个答案:

答案 0 :(得分: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端点,您也可以如下所示编写它,以实现向后兼容,其含义几乎相同({{3}之间存在细微差异和tf.strings.split):

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

答案 1 :(得分:0)

您可以使用基本的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')
相关问题