[英]Keras model predicts different results using the same input
我在简单数据集上构建了一个 Keras 序列 model。 我能够训练 model,但是每次我尝试对同一输入进行预测时,我都会得到不同的值。 任何人都知道为什么? I read through different Stackoverflow here ( Why the exactly identical keras model predict different results for the same input data in the same env , Keras saved model predicting different values on different session , different prediction after load a model in keras ), but couldn't找到答案。 我尝试设置 Tensorflow 种子,但仍然得到不同的结果。 这是我的代码
from pandas import concat
from pandas import DataFrame
# create sequence
length = 10
sequence = [i/float(length) for i in range(length)]
# create X/y pairs
df = DataFrame(sequence)
df = concat([df, df.shift(1)], axis=1)
df.dropna(inplace=True)
print(df)
# convert to LSTM friendly format
values = df.values
X, y = values[:, 0], values[:, 1]
X = X.reshape(len(X), 1, 1)
print(X.shape, y.shape)
output 是:
0 0
1 0.1 0.0
2 0.2 0.1
3 0.3 0.2
4 0.4 0.3
5 0.5 0.4
6 0.6 0.5
7 0.7 0.6
8 0.8 0.7
9 0.9 0.8
(9, 1, 1) (9,)
然后开始构建 model
#configure network
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
tf.random.set_seed(1337)
n_batch = len(X)
n_neurons = 10
#design network
model = Sequential()
model.add(LSTM(n_neurons, batch_input_shape=(n_batch, X.shape[1], X.shape[2]), stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X,y,epochs=2,batch_size=n_batch,verbose=1,shuffle=False)
现在,每次我运行以下代码来获得预测时,我都会得到不同的结果,如您在此处所见
model.predict(X)
********output**************
array([[0.03817442],
[0.07164046],
[0.10493257],
[0.13797525],
[0.17069395],
[0.20301574],
[0.23486984],
[0.26618803],
[0.29690543]], dtype=float32)
model.predict(X)
********output**************
array([[0.04415776],
[0.08242793],
[0.12048437],
[0.15823033],
[0.19556962],
[0.2324073 ],
[0.26865062],
[0.3042098 ],
[0.33899906]], dtype=float32)
问题是在 LSTM 层中设置stateful=True
,因为这会在预测调用之间保留 state,因此每个预测都取决于之前的预测。
因此,作为解决方案,设置stateful=False
。
我认为这个库和它所附的文档对您的工作会很有趣。
基于上述库,在我最近与 Keras 的合作中,我开始编写如下代码:
import os
import numpy as np
from numpy.random import seed
seed(42)
rng = np.random.RandomState(42)
import tensorflow
tensorflow.random.set_seed(42)
os.environ['TF_DETERMINISTIC_OPS'] = '1'
结果中似乎有很多确定性,这对我当时的工作来说已经足够好了。
基于@Dr.Snoopy,问题是设置 stateful = True。 将其设置为 False 可解决此问题。 “布尔值(默认为 False)。如果为真,则批次中索引 i 处每个样本的最后 state 将用作下一批中索引 i 样本的初始 state。” 我的误解是这只适用于培训。
感谢@Dr.Snoopy 指出这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.