ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【tf.keras】tf.keras模型复现

2019-05-17 21:54:56  阅读:397  来源: 互联网

标签:keras 模型 random seed 复现 tf import


keras 构建模型很简单,上手很方便,同时又是 tensorflow 的高级 API,所以学学也挺好。

模型复现在我们的实验中也挺重要的,跑出了一个模型,虽然我们可以将模型的 checkpoint 保存,但再跑一遍,怎么都得不到相同的结果,对我而言这是不能接受的。

用 keras 实现模型,想要能够复现,需要将设置各个可能的随机过程的 seed;而且,代码不要在 GPU 上跑,而是在 CPU 上跑。(也就是说,GPU 上得到的 keras 模型没办法再复现。)

我的 tensorflow+keras 版本:

print(tf.VERSION)    # '1.10.0'
print(tf.keras.__version__)    # '2.1.6-tf'

keras 模型可复现的配置:

import numpy as np
import tensorflow as tf
import random as rn

import os
# run on CPU only
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ["PYTHONHASHSEED"] = '0'

# The below is necessary for starting Numpy generated random numbers
# in a well-defined initial state.

np.random.seed(42)

# The below is necessary for starting core Python generated random numbers
# in a well-defined state.

rn.seed(12345)

# Force TensorFlow to use single thread.
# Multiple threads are a potential source of non-reproducible results.
# For further details, see: https://stackoverflow.com/questions/42022950/

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

from keras import backend as K

# The below tf.set_random_seed() will make random number generation
# in the TensorFlow backend have a well-defined initial state.
# For further details, see:
# https://www.tensorflow.org/api_docs/python/tf/set_random_seed

tf.set_random_seed(1234)

sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)

# Rest of code follows ...

References

How can I obtain reproducible results using Keras during development? -- Keras Documentation
具有Tensorflow后端的Keras可以随意使用CPU或GPU吗?

标签:keras,模型,random,seed,复现,tf,import
来源: https://www.cnblogs.com/wuliytTaotao/p/10883749.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有