Skip to main content
 首页 » 编程设计

python之从 CSV 初始化字符串生成器

2025年05月04日30luoye11

我有一个 CSV 文件,其中包含成对的图像文件名和一个标签。我想加载这些图像。

# Queue for reading input pairs 
filename_queue = tf.train.string_input_producer([MY_CSV_FILE]) 
 
# Read CSV input pairs and label 
pair_list_reader = tf.TextLineReader() 
pair_list_key, pair_list_value = pair_list_reader.read(filename_queue) 
record_defaults = [[''], [''], [-1]] 
img1_path, img2_path, label = tf.decode_csv(pair_list_value, record_defaults=record_defaults) 
 
# Load image 1 
img1_filename_queue = tf.train.string_input_producer(img1_path) 

如您所见,我逐行读取 CSV 文件,然后尝试使用从 CSV 解码器获得的文件名初始化第二个输入生成器。

不过,我在最后一行遇到错误:

  File "tensorflow/python/training/input.py", line 138, in string_input_producer 
    "fraction_of_%d_full" % capacity) 
  File "tensorflow/python/training/input.py", line 106, in _input_producer 
    enq = q.enqueue_many([input_tensor]) 
  File "tensorflow/python/ops/data_flow_ops.py", line 192, in enqueue_many 
    batch_dim = ret.inputs[1].get_shape()[0] 
  File "tensorflow/python/framework/tensor_shape.py", line 427, in __getitem__ 
    return self._dims[key] 
IndexError: list index out of range 

这是为什么?

提前谢谢你。

请您参考如下方法:

这是一个错误,因为 img1_path 的shapes(0-D,或标量,Tensor)和预期的 string_tensor tf.train.string_input_producer 的参数(一维或矢量张量)。

幸运的是,解决方案很简单,使用 tf.expand_dims将 img1_path 转换为(单元素)向量:

# Convert img1_path from a scalar to a 1-element vector. 
img1_path = tf.expand_dims(img1_path, 0) 

跟踪张量的形状可能很棘手,因此 TensorFlow 提供了 Tensor.get_shape()方法,您可以调用它来获取有关任何张量对象形状的信息。例如:

print img1_path.get_shape() 
# ==> "TensorShape([])" (a 0-dimensional tensor, or scalar) 
img1_path = tf.expand_dims(img1_path, 0) 
print img1_path.get_shape() 
# ==> "TensorShape([Dimension(1)])" (a 1-dimensional tensor with length 1)