【tf.keras】tf.keras模型复现
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模型复现的更多相关文章
- python 3.7 安装 sklearn keras(tf.keras)
# 1 sklearn 一般方法 网上有很多教程,不再赘述. 注意顺序是 numpy+mkl ,然后 scipy的环境,scipy,然后 sklearn # 2 anoconda ana ...
- Python机器学习笔记:深入学习Keras中Sequential模型及方法
Sequential 序贯模型 序贯模型是函数式模型的简略版,为最简单的线性.从头到尾的结构顺序,不分叉,是多个网络层的线性堆叠. Keras实现了很多层,包括core核心层,Convolution卷 ...
- Keras Sequential顺序模型
keras是基于tensorflow封装的的高级API,Keras的优点是可以快速的开发实验,它能够以TensorFlow, CNTK, 或者 Theano 作为后端运行. 模型构建 最简单的模型是 ...
- 使用C++部署Keras或TensorFlow模型
本文介绍如何在C++环境中部署Keras或TensorFlow模型. 一.对于Keras, 第一步,使用Keras搭建.训练.保存模型. model.save('./your_keras_model. ...
- keras训练cnn模型时loss为nan
keras训练cnn模型时loss为nan 1.首先记下来如何解决这个问题的:由于我代码中 model.compile(loss='categorical_crossentropy', optimiz ...
- keras中的模型保存和加载
tensorflow中的模型常常是protobuf格式,这种格式既可以是二进制也可以是文本.keras模型保存和加载与tensorflow不同,keras中的模型保存和加载往往是保存成hdf5格式. ...
- 使用keras导入densenet模型
从keras的keras_applications的文件夹内可以找到内置模型的源代码 Kera的应用模块Application提供了带有预训练权重的Keras模型,这些模型可以用来进行预测.特征提取和 ...
- Keras实践:模型可视化
Keras实践:模型可视化 安装Graphviz 官方网址为:http://www.graphviz.org/.我使用的是mac系统,所以我分享一下我使用时遇到的坑. Mac安装时在终端中执行: br ...
- matlab调用keras深度学习模型(环境搭建)
matlab没有直接调用tensorflow模型的接口,但是有调用keras模型的接口,而keras又是tensorflow的高级封装版本,所以就研究一下这个……可以将model-based方法和le ...
随机推荐
- s3c2440裸机-内存控制器(一、内存控制器的原理)
1.内存接口概念 S3C2440是个片上系统,有GPIO控制器(接有GPIO管脚(GPA-GPH)),有串口控制器 (接有TXD RXD引脚),有memory controller内存控制器,有Nan ...
- 201871010102-常龙龙《面向对象程序设计(java)》第十四周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 题解:SPOJ1026 Favorite Dice
原题链接 题目大意 给你一个n个面的骰子,每个面朝上的几率相等,问每个面都被甩到的期望次数 题解 典型的赠券收集问题. 我们考虑当你手上已有\(i\)种不同的数,从集合中任选一个数得到新数的概率,为\ ...
- 一天两道PAT(1)
其实是从昨天开始刷的,备战一下PAT(乙级,菜鸡不解释,希望几个月下来能有长进吧),做了一下,发现自己的算法功底好差啊..... 先上题目 1. 字符串中必须仅有P, A, T这三种字符,不可以包含其 ...
- 《3D_Deep_Learning_for_Robot_Perception.pdf》
https://github.com/PrincetonVision/marvin
- 【洛谷5299】[PKUWC2018] Slay the Spire(组合数学)
点此看题面 大致题意: 有\(n\)张强化牌\(a_i\)和\(n\)张攻击牌\(b_i\),每张牌有一个权值(强化牌的权值大于\(1\)),每张强化牌能使所有攻击牌的权值乘上这张强化牌的权值,每张攻 ...
- 【转】Java 浅拷贝和深拷贝的理解和实现方式
Java中的对象拷贝(Object Copy)指的是将一个对象的所有属性(成员变量)拷贝到另一个有着相同类类型的对象中去.举例说明:比如,对象A和对象B都属于类S,具有属性a和b.那么对对象A进行拷贝 ...
- Pytorch创建模型的多种方法
目录 Method 1 Method 2 Method 3 Method 4 Reference 网络结构: conv --> relu --> pool --> FC -- > ...
- js获取url参数值的方法总结
1.方式一:通过字符串截取的方式获取参数值: 1).函数一:获取URL中的参数名及参数值的集合 /** * [获取URL中的参数名及参数值的集合] * 示例URL:http://htmlJsTest/ ...
- Python变量与内存管理
Python变量与内存管理 –与C语言中的变量做对比,更好的理解Python的变量. 变量 变量在C语言中 全局变量:其存放在内存的静态变量区中. 局部变量:代码块中存放在内存的代码区当中,当被调 ...