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. from __future__ import absolute_import,division,print_function的作用

    绪论: 最近看多的项目中都文件的开头都带引入了三个模块,特地去查了下其作用(注:验证需要在python2的环境下) absolute_import :绝对导入,其作用是导入模块的时候如果在当前项目目录 ...

  2. 031.[转] 从类状态看Java多线程安全并发

    从类状态看Java多线程安全并发 pphh发布于2018年9月16日 对于Java开发人员来说,i++的并发不安全是人所共知,但是它真的有那么不安全么? 在开发Java代码时,如何能够避免多线程并发出 ...

  3. Linux下使用 github+hexo 搭建个人博客04-next主题优化

    上篇我们说了 hexo 的优化,针对的站点的优化. 本篇讲解 next 主题的优化,包括:使用语言.前端页面显示宽度.菜单.侧栏.头像.添加或取消动画效果.打赏功能等等. 让页面排版更符合我们所要的功 ...

  4. python获取指定文件夹下的文件和文件夹

    import os filepaths = []; dirpaths = []; pathName = r'C:\anfei\json\20191128' for root, dirs, files ...

  5. sqlite数据类型与c#数据类型对应表

    SQLite 数据类型 C# 数据类型   BIGINT Int64   BIGUINT UInt64   BINARY Binary   BIT Boolean 首选 BLOB Binary 首选 ...

  6. 使用java代码操作Redis

    1导入pom.xml依赖 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis ...

  7. cartographer 3D运行录制rosbag包

    目录: 1.运行多线激光雷达: 2.运行IMU: 3.录制rosbag包: 4.配置cartographer: 5.查看地图: 1.运行多线激光雷达: 主要是测试雷达是否正在运行,确认雷达点云topi ...

  8. Codeforces Round #602 (Div. 2, based on Technocup 2020 Elimination Round 3) B. Box 贪心

    B. Box Permutation p is a sequence of integers p=[p1,p2,-,pn], consisting of n distinct (unique) pos ...

  9. nui-app 笔记

    https://uniapp.dcloud.io

  10. Sql Server 判断表是否存在方法总结

    #使用场景: 1.在创建表之前,需要先判断该表是否已经存在: 2.在删除表之前,需要先判断该表是否已经存在: #方法总结: 1.判断实体表是否存在的方法: 1).方法一: * from sysObje ...