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

带DenseFeatures层的TensorFlow Sequential模型predict方法调用报错如何解决

错误原因

你模型的第一层使用了tf.keras.layers.DenseFeatures,该层要求输入必须是和你定义的feature_columns键名完全匹配的字典格式,不能直接传入numpy数组。你训练阶段的输入就是dict(df)格式,预测阶段也要保持相同的输入规范。

解决方案

列表输入预测示例

首先要保证你的测试列表顺序和数据集heart.csv的列顺序完全匹配,示例代码如下:

import pandas as pd
import numpy as np

# 替换为你自己数据集的实际列名,顺序和读入的csv列顺序完全一致
COL_NAMES = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal', 'target']
test_row = [57, 1,  0,  140, 192, 0, 1, 148, 0, 0.4, 1, 0, 1, 1]

# 转换为字典并去掉target列
test_series = pd.Series(test_row, index=COL_NAMES)
test_dict = test_series.drop('target').to_dict()

# 分类特征转字符串,和训练时的预处理逻辑保持一致
test_dict['cp'] = str(test_dict['cp'])
test_dict['restecg'] = str(test_dict['restecg'])
test_dict['slope'] = str(test_dict['slope'])

# 增加batch维度(单条预测也需要符合批量输入要求)
input_dict = {k: [v] for k, v in test_dict.items()}

# 执行预测
result = model.predict(input_dict)
# 输出结果为0-1区间的二分类概率
print("预测概率:", result[0][0])

现有start_predic函数修改

你现有函数的问题在于键名不匹配、输入格式错误,修改后代码如下:

def start_predic(input_to_predict):
    # 键名映射:将传入的val1~val13对应到数据集的实际特征列名,顺序要和你前端传入的参数顺序完全匹配
    col_mapping = {
        "val1": "age",
        "val2": "sex",
        "val3": "cp",
        "val4": "trestbps",
        "val5": "chol",
        "val6": "fbs",
        "val7": "restecg",
        "val8": "thalach",
        "val9": "exang",
        "val10": "oldpeak",
        "val11": "slope",
        "val12": "ca",
        "val13": "thal"
    }
    formatted_input = {}
    for key, val in input_to_predict.items():
        if key not in col_mapping or val is None:
            continue
        # 转换为数值类型
        formatted_input[col_mapping[key]] = float(val)
    
    # 分类特征转字符串,和训练逻辑一致
    formatted_input["cp"] = str(int(formatted_input["cp"]))
    formatted_input["restecg"] = str(int(formatted_input["restecg"]))
    formatted_input["slope"] = str(int(formatted_input["slope"]))
    
    # 增加batch维度
    formatted_input = {k: [v] for k, v in formatted_input.items()}
    
    # 预测
    result = model.predict(formatted_input)
    return result[0][0]

注意事项

  • 所有预处理逻辑必须和训练阶段完全一致,不能遗漏分类特征转字符串的操作
  • 字典的键名必须和你定义feature_columns时使用的列名完全匹配
  • 预测输入必须带有batch维度,单条数据也需要将每个特征的值包裹在列表中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:36:06