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

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

用 keras 实现模型,想要能够复现,首先需要设置各个可能的随机过程的 seed,如 np.random.seed(1),然后代码不要在 GPU 上跑,而是限制在 CPU 上跑

(当使用 conv2D 层时,似乎在 GPU 上跑没法复现,即使设置 batch_size=1,只在 CPU 上跑才能复现。)

我的 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, if you want to run code on GPU, you should delete the following line.
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 ...

对于 tensorflow low-level API,即用 tf.variable_scope() 和 tf.get_variable() 自行构建 layers,同样会出现这种问题。

keras 文档 对此的解释是:

Moreover, when using the TensorFlow backend and running on a GPU, some operations have non-deterministic outputs, in particular tf.reduce_sum(). This is due to the fact that GPUs run many operations in parallel, so the order of execution is not always guaranteed. Due to the limited precision of floats, even adding several numbers together may give slightly different results depending on the order in which you add them. You can try to avoid the non-deterministic operations, but some may be created automatically by TensorFlow to compute the gradients, so it is much simpler to just run the code on the CPU.

而 pytorch 是怎么保证可复现:(cudnn中对卷积操作进行了优化,牺牲了精度来换取计算效率。可以看到,下面的代码强制 cudnn 产生确定性的结果,但会牺牲效率。具体参见博客 PyTorch的可重复性问题 (如何使实验结果可复现)

from torch.backends import cudnn
cudnn.benchmark = False      # if benchmark=True, deterministic will be False
cudnn.deterministic = True

References

How can I obtain reproducible results using Keras during development? -- Keras Documentation

具有Tensorflow后端的Keras可以随意使用CPU或GPU吗?

PyTorch的可重复性问题 (如何使实验结果可复现)-- hyk_1996

【tf.keras】tf.keras模型复现的更多相关文章

  1. python 3.7 安装 sklearn keras(tf.keras)

    # 1   sklearn  一般方法 网上有很多教程,不再赘述. 注意顺序是 numpy+mkl     ,然后 scipy的环境,scipy,然后 sklearn # 2 anoconda ana ...

  2. Python机器学习笔记:深入学习Keras中Sequential模型及方法

    Sequential 序贯模型 序贯模型是函数式模型的简略版,为最简单的线性.从头到尾的结构顺序,不分叉,是多个网络层的线性堆叠. Keras实现了很多层,包括core核心层,Convolution卷 ...

  3. Keras Sequential顺序模型

    keras是基于tensorflow封装的的高级API,Keras的优点是可以快速的开发实验,它能够以TensorFlow, CNTK, 或者 Theano 作为后端运行. 模型构建 最简单的模型是  ...

  4. 使用C++部署Keras或TensorFlow模型

    本文介绍如何在C++环境中部署Keras或TensorFlow模型. 一.对于Keras, 第一步,使用Keras搭建.训练.保存模型. model.save('./your_keras_model. ...

  5. keras训练cnn模型时loss为nan

    keras训练cnn模型时loss为nan 1.首先记下来如何解决这个问题的:由于我代码中 model.compile(loss='categorical_crossentropy', optimiz ...

  6. keras中的模型保存和加载

    tensorflow中的模型常常是protobuf格式,这种格式既可以是二进制也可以是文本.keras模型保存和加载与tensorflow不同,keras中的模型保存和加载往往是保存成hdf5格式. ...

  7. 使用keras导入densenet模型

    从keras的keras_applications的文件夹内可以找到内置模型的源代码 Kera的应用模块Application提供了带有预训练权重的Keras模型,这些模型可以用来进行预测.特征提取和 ...

  8. Keras实践:模型可视化

    Keras实践:模型可视化 安装Graphviz 官方网址为:http://www.graphviz.org/.我使用的是mac系统,所以我分享一下我使用时遇到的坑. Mac安装时在终端中执行: br ...

  9. matlab调用keras深度学习模型(环境搭建)

    matlab没有直接调用tensorflow模型的接口,但是有调用keras模型的接口,而keras又是tensorflow的高级封装版本,所以就研究一下这个……可以将model-based方法和le ...

随机推荐

  1. 25个JavaScript数组方法代码示例

    摘要: 通过代码掌握数组方法. 原文:通过实现25个数组方法来理解及高效使用数组方法(长文,建议收藏) 译者:前端小智 Fundebug经授权转载,版权归原作者所有. 要在给定数组上使用方法,只需要通 ...

  2. iotop使用方法

    iotop 是一个用来监视磁盘 I/O 使用状况的 top 类工具.iotop 具有与 top 相似的 UI,其中包括 PID.用户.I/O.进程等相关信息.   安装 yum install iot ...

  3. Young and Beautiful 新红楼剪辑(by up)

    up剪辑的新红楼视频,配上Young and Beautiful 这首英文歌,很优美^_^

  4. xpath:

    from selenium import webdriverb = webdriver.Firefox()#路径读取方式一:# b.get(r"C:\我的代码\selenium自动化测试\t ...

  5. bzoj5219 [Lydsy2017省队十连测] 最长路径

    题意: 做法来自 首先竞赛图缩点后是一条链,\(1\)号节点在开头的那个\(SCC\)中,因此从\(1\)号节点出发的最长链即为\(1\)号节点所在的\(SCC\)的大小\(+1\)号节点拓扑序之后的 ...

  6. 第05组 Beta冲刺(2/4)

    第05组 Beta冲刺(2/4) 队名:天码行空 组长博客连接 作业博客连接 团队燃尽图(共享): GitHub当日代码/文档签入记录展示(共享): 组员情况: 组员1:卢欢(组长) 过去两天完成了哪 ...

  7. angularjs中ng-class常用写法,三元表达式、评估表达式与对象写法

     壹 ❀ 引 ng-class可以说在angularjs样式开发中使用频率特别高了,这不我想利用ng-class的三元运算符的写法来定义一个样式,结果怎么都想不起来正确写法,恼羞成怒还是整理一遍吧,那 ...

  8. #3145. 「APIO 2019」桥梁

    #3145. 「APIO 2019」桥梁 题目描述 圣彼得堡市内所有水路长度总和约 282 千米,市内水域面积占城市面积的 7%.--来自维基百科 圣彼得堡位于由 \(m\) 座桥梁连接而成的 \(n ...

  9. 跳出"低水平勤奋陷阱"

    "低水平勤奋陷阱":摘记更多的知识 读书是获得知识的最基本,最重要的方式,但读书需要方法 所谓"低水平勤奋陷阱",就是花费了大量的时间和精力,但得到的结果却微乎 ...

  10. selenium元素定位方法之轴定位

    一.轴运算名称 ancestor:祖先结点(包括父结点) parent:父结点 preceding:当前元素节点标签之前的所有结点(html页面先后顺序) preceding-sibling:当前元素 ...