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

tf.keras.Sequential预测年份序列异常:结果全为1,求模型适配分析

问题根源与解决方案
  • 输出层激活函数错误
    你用sigmoid作为输出层激活函数,它的输出范围仅为(0,1),但目标是预测1990这类大整数年份,模型只能将输出压缩到0-1区间,最终全部趋近于1.0,完全不符合需求。需移除输出层的激活函数(默认线性激活),或显式指定activation="linear",让模型能输出任意实数。

  • 损失函数与任务不匹配
    binary_crossentropy是二分类任务专用损失,而年份预测属于回归任务,应使用mean_squared_error(均方误差)或mean_absolute_error(平均绝对误差)这类回归损失。同时accuracy指标不适合回归场景,需替换为mae或mse这类回归指标。

  • 未做数据归一化
    年份数值(如1990)属于较大的连续值,直接输入会导致模型训练不稳定、梯度更新异常。必须先对输入和目标年份做归一化处理,比如缩放到0-1区间或标准化(减均值除以标准差)。

修改后的示例代码

import tensorflow as tf
from tensorflow.keras.layers import Dense

# 数据归一化:将年份缩放到0-1区间
max_year = max(self.x_train["year"].max(), self.y_train["year"].max())
x_train_norm = self.x_train["year"] / max_year
y_train_norm = self.y_train["year"] / max_year
p_norm = self.p["year"] / max_year

modelsq = tf.keras.Sequential(
    [
        Dense(64, activation="relu", input_shape=(1,)),
        Dense(32, activation="relu"),
        Dense(1)  # 移除sigmoid,使用默认线性激活
    ]
)
modelsq.compile(
    optimizer="adam", 
    loss="mean_squared_error",  # 回归任务损失
    metrics=["mean_absolute_error"]  # 回归任务指标
)
modelsq.fit(x_train_norm, y_train_norm, epochs=50, batch_size=32)  # 可适当增加训练轮数

# 预测后反归一化得到真实年份
predictions_norm = modelsq.predict(p_norm)
predictions = predictions_norm * max_year
print("predictions:", predictions)

补充说明

年份预测本质是连续值回归任务,只要调整模型配置和数据预处理,Sequential模型完全适用。如果你的数据是按时间顺序的序列(比如基于历史年份序列预测下一年),也可以考虑使用LSTM等序列模型,但调整后的全连接模型也能完成基础的回归预测。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:22:12