python - 顺序模型在每次运行时给出不同的结果

标签 python keras lstm

我有一个用于构建 keras 顺序模型的 python 脚本。每次我得到不同的结果而脚本没有任何变化。请看一下脚本。我哪里错了请帮忙。

thedata = pandas.read_csv("C:/User/Downloads/LSTM/data.csv", sep=', ', delimiter=',', header='infer', names=None)

np.random.seed(1337)

x = thedata['Review']
y = thedata['Polarity_Numeral']
x = x.iloc[:].values
y = y.iloc[:].values

tk = Tokenizer(num_words=40000, lower=True, split=" ")
tk.fit_on_texts(x)
x = tk.texts_to_sequences(x)    
max_len = 120
x = pad_sequences(x, maxlen=max_len)
max_features = 40000
testx = x[51000:52588]
print (testx)
testy = y[51000:52588]
x = x[0:50999]
y = y[0:50999]


model = Sequential()
model.add(Embedding(max_features, 128, input_length=max_len))
model.add(SpatialDropout1D(0.3))
model.add(GaussianNoise(0.2))
model.add(LSTM(128 , dropout_W=0.3, dropout_U=0.3, return_sequences=False))
model.add(Dense(1, W_regularizer=l2(0.2)))
model.add(Activation('sigmoid'))
model.summary()
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.00)
model.compile(loss='binary_crossentropy', optimizer=adam,metrics = ['accuracy'] )
model_history = model.fit(x, y=y, batch_size=64, epochs=1, verbose=1,validation_split = 0.2)
model.save('C:/User/Downloads/model.h5')
model.save_weights('C:/User/Downloads/weight_model.h5')

predictions = model.predict(testx)
print (predictions)

第一次运行时,我得到了 57% 第二次运行 .. 53% 第三.. 55% 每次它都是随机变化的。 感谢您的帮助!

最佳答案

This code is for tensorflow backend

这是因为权重是使用随机数初始化的,因此每次都会得到不同的结果。这是预期的行为。要获得可重现的结果,您需要将随机种子设置为:

import tensorflow as tf
import random as rn

os.environ['PYTHONHASHSEED'] = '0'

# Setting the seed for numpy-generated random numbers
np.random.seed(37)

# Setting the seed for python random numbers
rn.seed(1254)

# Setting the graph-level random seed.
tf.set_random_seed(89)

from keras import backend as K

session_conf = tf.ConfigProto(
      intra_op_parallelism_threads=1,
      inter_op_parallelism_threads=1)

#Force Tensorflow to use a single thread
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)

K.set_session(sess)

# Rest of the code follows from here on ...

关于python - 顺序模型在每次运行时给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44305760/

相关文章:

python - Keras LSTM 的输入转换

python - LSTM 预处理 : Build 3d arrays from pandas data frame based on ID

python - 无法导入名称 util

python - 类自定义 __eq__ 作为哈希值的比较

python - tf.data 与 tf.keras.preprocessing.image.ImageDataGenerator

tensorflow - Keras h5将于2019年在Tensorflow上服?

python - 短文本情感分类任务所需的最小训练集大小是多少

python - 在 Atom 上运行 Python 代码时获取 "EOFError"

python - 一种改变 asyncio 任务应该如何从调用 cancel() 的地方被取消的 Pythonic 方法

python - 注意层抛出 TypeError : Permute layer does not support masking in Keras