Skip to main content
 首页 » 编程设计

python之从文件中提取一个热编码到数据集中

2024年12月31日10落叶无声

我有一个数据集图像和相应的标签,其中每个图像文件都有一个 .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中将其转换为数字数组?

请您参考如下方法:

这是执行此操作的函数。

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 和 tf.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