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

搭建贷款资格预测TensorFlow模型时遇输入形状不兼容错误求助

问题分析与解决方案

核心错误原因

错误提示ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 614, 11), found shape=(None, 11),根源在于Input层的形状定义错误:

  • x.shape返回的是整个数据集的形状(样本数, 特征数)即(614,11),而Keras的Input(shape=...)需要的是单个样本的特征形状,应该是(11,)。

额外需要修复的问题

你的代码还忽略了两个关键步骤,即使修复Input形状后也会报错:

  1. 分类特征未编码:数据集中的Gender、Married、Dependents等是字符串类型,模型无法直接处理,需要转为数值。
  2. 缺失值未处理:数据集中存在NaN值,必须填充或删除后才能训练。

完整修复代码

import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer

# 加载数据集
dataset = pd.read_csv('/Users/XXX/loan-eligibility-predictor/loan-train.csv')
x = dataset.drop(columns=['Loan_Status'])
y = dataset['Loan_Status']

# 1. 处理分类特征编码
categorical_cols = ['Gender', 'Married', 'Dependents', 'Education', 'Self_Employed', 'Property_Area', 'Loan_ID']
le = LabelEncoder()
for col in categorical_cols:
    x[col] = le.fit_transform(x[col].astype(str))  # 转为字符串避免NaN报错

# 2. 处理缺失值
imputer = SimpleImputer(strategy='mean')
x = imputer.fit_transform(x)

# 3. 标签编码(Loan_Status是Y/N)
y = le.fit_transform(y)

# 构建模型:修复Input层形状
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(x.shape[1],)))  # 单个样本的特征数:11
model.add(tf.keras.layers.Dense(256, activation='sigmoid'))
model.add(tf.keras.layers.Dense(256, activation='sigmoid'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x, y, epochs=1000)

关键修改点说明

  • Input层形状:用x.shape[1]获取单个样本的特征数,确保输入形状匹配。
  • 分类特征编码:使用LabelEncoder将字符串特征转为数值,注意先把列转为字符串处理缺失的分类值。
  • 缺失值处理:用SimpleImputer以均值填充数值型缺失值,也可根据需求选择中位数、众数等策略。
  • 标签编码:将Loan_Status的Y/N转为1/0,适配二元交叉熵损失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:18:45