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. 树莓派设置frpc开机启动

    1.复制frpc启动命令及配置文件到系统相应目录: $ sudo cp frpc /usr/local/bin/frpc $ sudo mkdir /etc/frpc $ sudo cp frpc.i ...

  2. 读书笔记_python网络编程3(5)

    5. 网络数据与网络错误 应该如何准备需要传输的数据? 应该如何对数据进行编码与格式化? Py程序需要提供哪些类型的错误? 5.1. 字节与字符串 PC与网卡都支持将字节作为通用传输单元.字节将8比特 ...

  3. D3力布图绘制--节点自己连自己的实现

    案例分析 先看下实现的效果图 实现方法 本篇是在之前写的博文 D3力布图绘制--节点间的多条关系连接线的方法 基础上加修改的,这里放上修改的代码,其他的一样 // DATA var nodes = [ ...

  4. pytorch_模型参数-保存,加载,打印

    1.保存模型参数(gen-我自己的模型名字) torch.save(self.gen.state_dict(), os.path.join(self.gen_save_path, 'gen_%d.pt ...

  5. webUploader的使用

    webUploader的使用记录 WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML ...

  6. windows 10使用vscode进行远程代码开发 | tutorial to use vscode for remote development using ssh on windows

    本文首发于个人博客https://kezunlin.me/post/c93b6ba6/,欢迎阅读最新内容! tutorial to use vscode for remote development ...

  7. jQuery 源码分析(十三) 数据操作模块 DOM属性 详解

    jQuery的属性操作模块总共有4个部分,本篇说一下第2个部分:DOM属性部分,用于修改DOM元素的属性的(属性和特性是不一样的,一般将property翻译为属性,attribute翻译为特性) DO ...

  8. 用Scriban进行模版解析

    前言 有些时候,我们需要根据模版去展示一些内容,通常会借助模版引擎来处理. 举个简单的例子,发短信. 短信肯定是有模版的,不同的场景对应不同的模版. 注册的, [xxx]恭喜您成功注册yyy平台,您的 ...

  9. php使用inotify扩展监控文件或目录的变化

    一.安装inotify扩展 1.下载inotify扩展源码 https://pecl.php.net/package/inotify 对于php7以上版本,请下载 inotify-2.0.0.tgz. ...

  10. 计时 答题 demo

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...