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

如何从TFRecord Dataset中删除指定列以实现特征选择

解决方案

你可以通过「解析阶段直接过滤保留目标特征,再重新序列化写入新TFRecord」的方式实现列剔除,不需要额外做删除操作,具体实现流程如下:

前置准备

你已经通过sklearn得到了最终选定的特征列表,记为selected_features;同时准备好原始TFRecord对应的特征描述字典original_feature_desc(即你原本用来解析tf.Example的字典,定义了每个特征的类型是FixedLenFeature/VarLenFeature)。

步骤1:过滤特征描述字典

只保留选定特征对应的描述项:

filtered_feature_desc = {
    k: v for k, v in original_feature_desc.items() 
    if k in selected_features
}

步骤2:读取并解析TFRecord数据集

解析时直接使用过滤后的特征描述,自然不会加载待剔除的特征:

# 原有读取逻辑
raw_dataset = tf.data.TFRecordDataset(train_uri, compression_type='GZIP')

def parse_example(example_proto):
    return tf.io.parse_single_example(example_proto, filtered_feature_desc)

parsed_dataset = raw_dataset.map(parse_example)

步骤3:序列化并写入输出TFRecord

将解析后仅保留目标特征的数据重新序列化为tf.Example格式,写入输出路径即可:

def serialize_example(features):
    feature = {}
    for feat_name, tensor_val in features.items():
        # 可根据你的实际特征类型调整适配逻辑
        if tensor_val.dtype == tf.int64:
            feature[feat_name] = tf.train.Feature(
                int64_list=tf.train.Int64List(value=tensor_val.numpy().tolist())
            )
        elif tensor_val.dtype == tf.float32:
            feature[feat_name] = tf.train.Feature(
                float_list=tf.train.FloatList(value=tensor_val.numpy().tolist())
            )
        elif tensor_val.dtype == tf.string:
            feature[feat_name] = tf.train.Feature(
                bytes_list=tf.train.BytesList(value=tensor_val.numpy().tolist())
            )
    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
    return example_proto.SerializeToString()

def tf_serialize_example(features):
    tf_string = tf.py_function(
        serialize_example,
        (features,),
        tf.string
    )
    return tf.reshape(tf_string, ())

serialized_dataset = parsed_dataset.map(tf_serialize_example)
writer = tf.data.experimental.TFRecordWriter(
    output_uri, # 你的OutputArtifact对应的存储路径
    compression_type='GZIP' # 保持和原始输入一致的压缩格式
)
writer.write(serialized_dataset)

注意事项

如果你的特征包含VarLenFeature(变长特征),需要将解析得到的SparseTensor先转换为稠密张量或者对应值列表,再做序列化适配即可。
最终输出的TFRecord和原始输入结构完全一致,仅缺少你要剔除的特征列,符合组件输出要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:48:03