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

Keras搭建MLP使用多数据集训练时传入数据集报ValueError如何解决?

错误原因

  • 模型编译和训练顺序颠倒:Keras要求必须先完成模型编译(model.compile),再调用fit方法训练,你当前代码先执行训练循环,最后才做编译,完全不符合执行逻辑。
  • 输入数据类型不匹配:你传入fit的X_train是pandas DataFrame格式,你使用的Keras版本不支持直接接收DataFrame作为输入,需要转换为numpy数组格式。
  • 参数兼容问题:nb_epoch是Keras 1.x的旧参数,2.x版本统一用epochs参数指定训练轮次。

修正后的代码

import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout

file1 = "/home/Documents/t1.csv"
file2 = "/home/Documents/t2.csv"
files = [file1,file2]

model = Sequential()
# 显式指定输入维度,避免隐式推断出错,也可省略
model.add(Dense(64, activation='relu', input_shape=(3,)))
model.add(Dropout(0.2))
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# 调整顺序:先编译模型再训练
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

def BatchGenerator(files):
    for file in files:
        df = pd.read_csv(file)
        # 加.values将DataFrame/Series转为numpy数组
        X_train = df.drop(["output"],axis=1).values
        y_train = df["output"].values
        yield (X_train, y_train)

n_epochs = 100
for epoch in range(n_epochs):
    for (X_train, y_train) in BatchGenerator(files):
        # 替换旧参数nb_epoch为epochs
        model.fit(X_train, y_train, batch_size = 32, epochs = 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:36:03