【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 ...
随机推荐
- Data Management Technology(4) -- 关系数据库理论
规范化问题的提出 在规范化理论出现以前,层次和网状数据库的设计只是遵循其模型本身固有的原则,而无具体的理论依据可言,因而带有盲目性,可能在以后的运行和使用中发生许多预想不到的问题. 在关系数据库系统中 ...
- idea安装以及使用
1. 简介1.1 IDEA 全称 IntelliJ IDEA,是java语言开发的集成环境,IntelliJ在业界被公认为最好的java开发工具之一,尤其在智能代码助手.代码自动提示.重构. J2EE ...
- SPA项目开发之动态树以及数据表格和分页
首先我们来看下数据库 t_vue_user t_vue_tree_node t_vue_articles 2. 动态生成NavMenu导航菜单(只支持2级菜单) <el-menu key=&qu ...
- 物理像素[设备像素] & 逻辑像素[CSS像素];
为什么移动端CSS里面写了1px,实际上看起来比1px粗 了解设备物理像素和逻辑像素的同学应该很容易理解,其实这两个px的含义其实是不一样的, UI设计师要求的1px是指设备的物理像素1px,而CSS ...
- python(leetcode)498. 对角线遍历
这题难度中等,记录下思路 第一个会超时, 第二个:思想是按斜对角线行进行右下左上交替遍历, def traverse(matrix): n=len(matrix)-1 m=len(matrix[0]) ...
- Python:程序练习题(二)
Python:程序练习题(二) 2.1温度转换程序. 代码如下: t=input("请输入带符号的温度值(如:32C):") if t[-1] in ["C", ...
- 【MySQL报错】ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot exec ...
- url中拼接中文参数,后台接收为乱码的问题
遇到在URL中拼接中文的参数,后台拿到的数据为乱码的问题,这里来说一下问题出现的原因与解决方法. 大家比较关心的应该是解决的方法,因此先说解决方法. 解决方法 解决的方法是在客户端对这个中文参数进行编 ...
- 在IDEA中用Maven打包大项目时失败问题
今天在完成公司里某项功能开发时,准备用Maven打包,后来在打包的过程中报错:OutOfMemoryError.如下图: 后来经过查找资料,发现可以配置一下Maven的参数即可解决此问题. 配置参数为 ...
- MySQL学习——操作表
MySQL学习——操作表 摘要:本文主要学习了使用DDL语句操作表的方法. 创建表 语法 create table 表名 [表定义选项] [表选项]; 表定义选项 用来创建定义表的结构,由列名(col ...