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

Keras中全历史预测与实时预测结果不一致的原因探究

实时RNN预测与批量预测结果微小差异的原因分析

我希望实现实时预测,并验证其结果与一次性输入全部数据的预测结果一致。以下是测试代码:

import numpy as np
from keras.layers import Input, Dense, SimpleRNN
from keras.models import Model

#MODEL 1, for training
x = Input(shape=(None, 1))
h = SimpleRNN(30, return_sequences=True)(x)
out = Dense(1)(h)
model = Model(x, out)
model.compile(loss='mse', optimizer='adam')

X_train = np.random.rand(100, 50, 1)
y_train = np.random.rand(100, 50, 1)
model.fit(X_train, y_train, verbose = False)

#MODEL 1, for predictions in real time
x = Input(batch_shape=(1, None, 1))
h = SimpleRNN(30, stateful=True, return_sequences=True)(x)
out = Dense(1)(h)
predict_model = Model(x, out)
predict_model.set_weights(model.get_weights())

X = np.random.rand(2, 2, 1)
predictions = model.predict(X, verbose = False)
for sim in range(len(predictions)):
    for i in range(len(predictions[0])):
        pred = predict_model.predict(X[sim:(sim+1), i:(i + 1), :], verbose = False)
        print(pred[0][0]) #Predictions in real time
        print(predictions[sim][i]) #Predictions with MODEL 1
        print()
    predict_model.reset_states()

输出结果如下:

[0.09156141]
[0.09156139]

[-0.38076958]
[-0.38076955]

[0.12214336]
[0.12214339]

[-0.52013564]
[-0.5201356]

由于两个模型权重完全一致,理论上结果应完全相同,请问该现象的原因是什么?


原因分析

这种微小的数值差异是浮点数计算精度误差导致的,属于数值计算中的正常现象,具体原因包括:

  • 计算顺序差异:批量预测时对整个序列执行向量化矩阵运算,实时预测是逐步处理单步输入,两种路径的浮点数累加、乘法顺序不同,会产生极小的舍入误差积累。
  • 底层运算优化:Keras在批量处理时可能调用了专门的向量化加速库(如CuBLAS、MKL),这些库的优化逻辑和逐步处理的底层计算存在细微精度差异,但都符合IEEE 754浮点数标准。
  • 浮点数固有局限:IEEE 754标准的浮点数本身存在有效位数限制,超过精度范围的数值会被截断或舍入,不同计算流程会导致最终结果出现量级在1e-7~1e-8的微小偏差,完全不影响模型的实际使用。

内容的提问来源于stack exchange,提问作者Jose Gonzalez B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:50:17