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

Keras训练报错:维度不匹配(30与5)求解决方案

问题分析

报错核心是模型输出维度与目标数据维度不匹配:

  • 模型最后一层Dense(30)输出30维特征,而目标数据y_train/y_valid是5维的(每个样本对应5个数值),导致计算MSE损失时维度无法对齐,触发ValueError。
修复方案
  1. 修正模型输出层
    将模型的最后一层改为输出5个神经元,匹配目标数据的维度:

    model = keras.models.Sequential([
        keras.layers.Dense(30, activation='relu', input_shape=X_train.shape[1:]),
        keras.layers.Dense(5)  # 输出维度与目标一致,回归任务无需激活函数
    ])
    
  2. 修正代码中的拼写/命名问题

    • obiect改为object(拼写错误)
    • X_vaild/y_vaild改为X_valid/y_valid(拼写错误)
    • 避免类名与字典名重复(原代码中array1既是字典又是类名,会导致逻辑混乱),直接用数组拆分数据:
      data_array = np.array([[2.5, 3, 3.5, 4, 4.5], [3, 3.5, 4, 4.5, 5], [3.5, 4, 4.5, 5, 5.5], [4, 4.5, 5, 5.5, 6], [4.5, 5, 5.5, 6, 6.5]])
      target_array = np.array([[3, 3.5, 4, 4.5,5], [3.5, 4, 4.5, 5, 5.5], [4, 4.5, 5, 5.5, 6], [4.5, 5, 5.5, 6, 6.5], [5, 5.5, 6, 6.5, 7]])
      
      X_train, X_valid, y_train, y_valid = train_test_split(data_array, target_array)
      
  3. 完整修正后的代码

    import numpy as np
    from sklearn.model_selection import train_test_split
    import tensorflow as tf
    from tensorflow import keras
    
    data_array = np.array([[2.5, 3, 3.5, 4, 4.5], [3, 3.5, 4, 4.5, 5], [3.5, 4, 4.5, 5, 5.5], [4, 4.5, 5, 5.5, 6], [4.5, 5, 5.5, 6, 6.5]])
    target_array = np.array([[3, 3.5, 4, 4.5,5], [3.5, 4, 4.5, 5, 5.5], [4, 4.5, 5, 5.5, 6], [4.5, 5, 5.5, 6, 6.5], [5, 5.5, 6, 6.5, 7]])
    
    X_train, X_valid, y_train, y_valid = train_test_split(data_array, target_array)
    
    model = keras.models.Sequential([
        keras.layers.Dense(30, activation='relu', input_shape=X_train.shape[1:]),
        keras.layers.Dense(5)
    ])
    
    model.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer="Adam")
    
    history = model.fit(X_train, y_train, epochs=30, validation_data=(X_valid, y_valid))
    
关键说明
  • 多变量回归任务中,输出层的神经元数量必须与目标变量的维度一致,即样本对应的目标值数量。
  • 避免类名与变量名重复,否则会覆盖原有变量,导致数据读取异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:10:35