将文件中的一个热编码提取到数据集中



我有一个数据集图像和相应的标签,每个图像文件都有一个.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'0n0n0n0n1n', shape=(), dtype=string)

有没有办法把它转换成tensorflow中的一组数字?

这里有一个函数可以做到这一点。

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 = '0n0n0n0n1n0'
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.splittf.string_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

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

最新更新