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

TensorFlow创建feature_column传入Estimator触发ValueError问题求助

问题解决方法

错误核心原因

tf.estimator的feature_columns入参要求传入tf.feature_column系列接口生成的特征列对象,而非你提前通过DenseFeatures转换得到的特征值数组。你写的demo函数仅用于调试查看特征转换后的输出结果,其返回的numpy数组不能作为特征列传入模型。

代码修正方案

# 仅定义特征列对象,无需提前调用demo计算特征值
age = tf.feature_column.numeric_column('Age')
age_bucket = tf.feature_column.bucketized_column(age, boundaries = [30, 40, 50, 60, 70, 80, 90])

gender = tf.feature_column.categorical_column_with_vocabulary_list('Gender', ['F', 'M'])
gender_one_hot = tf.feature_column.indicator_column(gender)

smoking = tf.feature_column.categorical_column_with_vocabulary_list('Smoking', ['Y', 'N'])
smoking_one_hot = tf.feature_column.indicator_column(smoking)

# icd9code字段同理,传入其对应的特征列对象即可,不要传入提前计算的数组
model = tf.estimator.LinearClassifier( 
  n_classes = 2,
  model_dir = "ongoing/train6",
  feature_columns = [age_bucket, gender_one_hot, icd9code_feat_obj, smoking_one_hot]
)

# 训练逻辑无需修改
model.train( 
  input_fn = get_input_fn(csv_data, 5000, 10, True),
  steps = 1000
)

补充说明

Estimator运行时会自动根据传入的特征列对象,从input_fn返回的特征字典中读取对应字段、完成特征转换流程,不需要手动提前计算特征值。如果需要隐藏版本兼容类的WARNING提示,可以在代码开头加入以下配置:

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

内容的提问来源于stack exchange,提问作者RA.IBOY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:54:04