TensorFlow能否自动将CSV中封闭列表取值的列转为二进制独热列
解决方案
TensorFlow自带原生工具可直接实现你需要的固定取值分类列自动转独热二进制列的需求,无需提前用Pandas手动拆分列,而且预处理逻辑可嵌入模型,避免训练和推理阶段的预处理不一致问题。
方案1:Keras预处理层(官方推荐)
用tf.keras.layers.StringLookup层直接完成字符串取值到独热编码的转换,适合自定义程度高的场景:
import tensorflow as tf # 1. 提前整理每个分类列的所有可选取值 categorical_vocab = { "Smoking": ["never smoked", "tried smoking", "current smoker"], # 其余分类列按照相同格式补充即可 } # 2. 为每个分类列创建对应的预处理层 preprocess_layers = {} for col, vocab in categorical_vocab.items(): preprocess_layers[col] = tf.keras.layers.StringLookup( vocabulary=vocab, output_mode="one_hot", # 可选:如果存在超出词汇表的取值,可设置num_oov_indices=1分配默认占位 num_oov_indices=0 ) # 测试效果 test_value = tf.constant(["current smoker"]) print(preprocess_layers["Smoking"](test_value)) # 输出结果为 tf.Tensor([[0. 0. 1.]], shape=(1, 3), dtype=float32)
方案2:特征列API(适合批量处理CSV)
如果用tf.data直接加载CSV数据集训练,可使用tf.feature_column系列API批量处理所有分类列:
import tensorflow as tf # 同方案1提前整理分类列的取值字典 categorical_vocab = { "Smoking": ["never smoked", "tried smoking", "current smoker"], # 其余分类列按需补充 } # 批量生成独热特征列配置 feature_columns = [] for col_name, vocab in categorical_vocab.items(): # 定义分类词汇列 cat_col = tf.feature_column.categorical_column_with_vocabulary_list( key=col_name, vocabulary_list=vocab ) # 转为独热二进制列 one_hot_col = tf.feature_column.indicator_column(cat_col) feature_columns.append(one_hot_col) # 封装为模型输入层,可直接对接后续的TensorFlow模型层 input_feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
两种方案均支持批量处理所有符合固定取值规则的分类列,不需要逐列手动做拆分映射。
内容的提问来源于stack exchange,提问作者ido kahana
相关产品推荐
相关产品推荐

