You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow 1.x解码CSV报错求助:字段不匹配与队列元素不足

解决TensorFlow 1.x读取波士顿房价数据集的错误问题

嘿,刚看了你的问题,这两个错误其实是连锁反应,根源出在数据集格式不匹配上,咱们一步步来解决:

错误原因分析

  1. Expect 14 fields but have 1 in record 0:
    你用的波士顿原始数据集不是标准逗号分隔的CSV,而是用空格分隔的文本文件,而且开头还有好几行注释。你的代码用tf.decode_csv默认按逗号分割,就会把整行数据当成1个字段,自然和你设定的14个字段不匹配。
  2. OutOfRangeError: RandomShuffleQueue...:
    这是因为第一个错误导致队列里没有正确加载有效数据,当你尝试从队列取10条数据时,队列是空的,就抛出了这个错误。

具体解决步骤

第一步:预处理数据集(最稳妥的方式)

先把原始的空格分隔文本转成标准CSV,同时去掉开头的注释行。可以加个预处理脚本:

import csv

# 替换成你的原始数据集路径和想要生成的CSV路径
RAW_DATA_PATH = "boston_housing_raw.txt"
PROCESSED_CSV_PATH = "boston_housing.csv"

with open(RAW_DATA_PATH, 'r') as raw_file, open(PROCESSED_CSV_PATH, 'w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    for line in raw_file:
        stripped_line = line.strip()
        # 跳过注释行和空行,只处理数据行
        if not stripped_line.startswith('#') and stripped_line:
            # 处理多个连续空格的情况,分割成单个数据项
            data_items = stripped_line.split()
            csv_writer.writerow(data_items)

第二步:调整TensorFlow代码

针对预处理后的CSV,修改几处细节:

import tensorflow as tf
import csv

# Global Parameters
RAW_DATA_FILE = 'boston_housing_raw.txt'
DATA_FILE = 'boston_housing.csv'
BATCH_SIZE = 10
NUM_FEATURES = 14

# 先执行预处理
def preprocess_raw_data(raw_path, csv_path):
    with open(raw_path, 'r') as raw_file, open(csv_path, 'w', newline='') as csv_file:
        writer = csv.writer(csv_file)
        for line in raw_file:
            stripped_line = line.strip()
            if not stripped_line.startswith('#') and stripped_line:
                data_parts = stripped_line.split()
                writer.writerow(data_parts)

preprocess_raw_data(RAW_DATA_FILE, DATA_FILE)

def data_generator(filename):
    '''Generates Tensors in batches of size BATCH_SIZE.'''
    f_queue = tf.train.string_input_producer(filename)
    # 预处理后的文件没有表头,所以skip_header_lines设为0
    reader = tf.TextLineReader(skip_header_lines=0)
    _, value = reader.read(f_queue)
    
    record_defaults = [[0.0] for _ in range(NUM_FEATURES)]
    data = tf.decode_csv(value, record_defaults=record_defaults)
    # 你选的RM(索引5)、PTRATIO(索引10)、LSTAT(索引12)是对的
    features = tf.stack(tf.gather_nd(data, [[5], [10], [12]]))
    label = data[-1]
    
    min_after_dequeue = 10 * BATCH_SIZE
    capacity = 20 * BATCH_SIZE
    feature_batch, label_batch = tf.train.shuffle_batch(
        [features, label], 
        batch_size=BATCH_SIZE, 
        capacity=capacity, 
        min_after_dequeue=min_after_dequeue
    )
    return feature_batch, label_batch

def generate_data(feature_batch, label_batch):
    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        try:
            for _ in range(5):
                features, labels = sess.run([feature_batch, label_batch])
                print("特征批次:\n", features)
                print("标签批次:\n", labels)
                print("---")
        except tf.errors.OutOfRangeError:
            print("没有更多数据了")
        finally:
            coord.request_stop()
            coord.join(threads)

if __name__ == '__main__':
    feature_batch, label_batch = data_generator([DATA_FILE])
    generate_data(feature_batch, label_batch)

关键修改点说明

  • 新增了预处理函数,把原始空格分隔数据转成逗号分隔的CSV
  • 把TextLineReader的skip_header_lines改成0,因为预处理后的文件没有表头行
  • 在generate_data里加了异常捕获,避免极端情况下的崩溃(解决数据问题后大概率不会触发)

这样运行代码应该就能正常生成批次数据啦~

内容的提问来源于stack exchange,提问作者Euler_Salter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:51:36