TensorFlow简单分类器输入函数报错,我遗漏了哪些配置?
问题原因
该错误是TensorFlow尝试把字符串类型数据强制转换为浮点型计算时触发的。你在代码中直接将所有特征都定义为numeric_column(数值特征列),但数据集中存在字符串类型的字段,导致转换失败。仅靠查看.head()无法确认底层数据类型,部分看起来是数字的字段可能实际为object类型(比如带空格、特殊字符的字符串)。
解决步骤
- 第一步:确认所有字段的实际数据类型
运行print(train.dtypes)查看每列的真实类型,排查是否存在object类型的列。 - 第二步:分类型处理特征
如果存在字符串类型的分类特征,不能直接用numeric_column处理,需要按分类特征规则转换:
my_feature_columns = [] # 1. 处理数值特征(dtype为int/float的列) numeric_cols = ['GroupNumber', 'ProjectNumber'] # 替换为你实际的数值列名 for key in numeric_cols: my_feature_columns.append(tf.feature_column.numeric_column(key=key)) # 2. 处理字符串分类特征(dtype为object的列) categorical_cols = ['GroupUnit', 'GroupSkill1', 'GroupSkill2', 'GroupSkill3', 'GroupSkill4', 'GroupPreference1', 'GroupPreference2', 'GroupPreference3', 'ProjectUnit', 'ProjectSkill1', 'ProjectSkill2', 'ProjectSkill3', 'ProjectSkill4', 'ProjectPreference1', 'ProjectPreference2', 'ProjectPreference3'] # 替换为你实际的分类列名 for key in categorical_cols: # 提取该列所有唯一值作为词汇表 vocab = train[key].unique() # 定义分类特征列 cat_col = tf.feature_column.categorical_column_with_vocabulary_list(key=key, vocabulary_list=vocab) # 转换为DNN可接收的密集表示,类别少用indicator_column(one-hot),类别多用embedding_column my_feature_columns.append(tf.feature_column.indicator_column(cat_col)) # 类别数量大于10时推荐用embedding,示例: # my_feature_columns.append(tf.feature_column.embedding_column(cat_col, dimension=8))
- 第三步:检查标签列类型
确认train_y和test_y的类型为int/float,如果是字符串格式的'0'/'1',需要先转换为数值:
train_y = train_y.astype(int) test_y = test_y.astype(int)
- 可选:强制转换所有字段为数值(如果你确认数据无分类特征)
如果你的数据本就没有分类特征,只是读取时字符串被误识别,运行以下代码强制转换所有特征为数值,处理转换失败的异常值:
for col in train.columns: train[col] = pd.to_numeric(train[col], errors='coerce') test[col] = pd.to_numeric(test[col], errors='coerce') # 填充转换产生的空值 train = train.fillna(0) test = test.fillna(0)
内容的提问来源于stack exchange,提问作者Nick T
相关产品推荐
相关产品推荐

