tensorflow 2.0系列(3):eager execution和计算图

2023-05-16

目录

  • tf 2.0 的新特性:eager execution
    • 开启eager模式
    • 关闭eager模式
  • 构建图
    • 默认图
    • 创建多个计算图
    • 启动会话
  • 从公式到计算图
    • 绘制心形曲线
    • 开根号
    • 线性回归

tf 2.0 的新特性:eager execution

tensorflow经典的方式是需要构建计算图,启动会话后,张量在图中流动进行计算。在tf 2.0最大的特色之一就在于eager execution,大大简化了之前这个繁琐的定义和计算过程。

eager execution提供了一种命令式的编程环境,简单地说就是不需要构建图,直接可以运行。在老版本中,需要先构建计算图,然后再执行。在r1.14之后,tensorflow引入了eager execution,为快速搭建和测试算法模型提供了便利。

开启eager模式

tf 2.0 中,默认情况下,Eager Execution 处于启用状态。可以用tf.executing_eargerly()查看Eager Execution当前的启动状态,返回True则是开启,False是关闭。可以用tf.compat.v1.enable_eager_execution()启动eager模式。

import tensorflow.compat.v1 as tf

tf.enable_eager_execution()
print('eager execution ? '+ str(tf.executing_eagerly()))       # => True

x = [[1.]]
m = tf.add(x, x)
print("\nhello, tensorflow r%.1f"%m)  # => "hello, [[4.]]"

关闭eager模式

关闭eager模式的函数是 tf.compat.v1.disable_eager_execution()

构建图

graph是tf非常重要的一个概念,在图中定义了整个网络的计算过程,图也对模型做了某种意义上的封装和隔离,使得多个模型可以独立互不影响地运行。首先我们来看看默认图,再看看如何自定义图。

默认图

在tensorflow中,系统会维护一个默认的计算图,通过tf.get_default_graph()函数可以获取当前默认的计算图,计算图中所有的节点都可以视为运算操作op或tensor。在定义好计算图后,tf语句不会立即执行;而是必须等到开启会话session的时候,才会执行session.run()中的语句。如果run中涉及到其他的节点,也会执行到。
通过tf.get_default_graph()函数可以获取当前默认的计算图,为了向默认的计算图中添加一个操作,我们只需要简单的调用一个函数:
** 例1: 默认图 **


c = tf.constant(3.0) 
assert c.graph == tf.get_default_graph() 

with tf.Session(graph=c.graph) as sess:
    print(sess.run(c))

得到输出3.0

创建多个计算图

还可以用 tf.compat.v1.Graph( ) 函数生成新的计算图。在不同的计算图中,张量和运算都不会共享,彼此是独立的。
** 例2: 创建两个计算图 **

g1 = tf.Graph()
    # 在图g1中定义初始变量c, 并设置初始值为0
    v = tf.get_variable("v", shape=[3], initializer = tf.zeros_initializer(dtype=tf.float32))

g2 = tf.Graph()
with g2.as_default():
    # 在图g1中定义初始变量c, 并设置初始值为1
    v = tf.get_variable("v", shape=[4], initializer = tf.ones_initializer(dtype=tf.float32))

with tf.Session(graph=g1) as sess:
    sess.run(tf.global_variables_initializer())
    with tf.variable_scope('', reuse=True):
        # 输出值为0
        print(sess.run(tf.get_variable("v")))

with tf.Session(graph=g2) as sess:
    sess.run(tf.global_variables_initializer())
    with tf.variable_scope('', reuse=True):
       # 输出值为1
       print(sess.run(tf.get_variable('v')))

输出:

[0. 0. 0.]
[1. 1. 1. 1.]

启动会话

例3: 用tensorflow实现一个累加器,依次输出1,2,3,4,5

import tensorflow.compat.v1 as tf

if ~tf.executing_eagerly():
    tf.disable_eager_execution()
# 逐个输出1,2,3,4,5
# 定义变量节点x,常量节点one,op节点x_new
x = tf.Variable(0, name='counter')  
one = tf.constant(1)
x_new = tf.add(x, one)
# 赋值操作,更新 x
update = tf.assign(x, x_new)

# 计算图初始化
init = tf.initialize_all_variables()
# 启动会话
with tf.Session() as sess:
    sess.run(init)
    for _ in range(5):
        sess.run(update)
        print(sess.run(x))

从公式到计算图

理解了tensor的定义和计算图的构建方法后,我们会发现,其实tensorflow不仅仅是一个神经网络深度学习的算法库,其实也是一个数据流(DFP)的工具。例如在tensorflow中,tensor可以支持各类基本数学计算,构建图可以实现各种函数/方程,用c或者matlab实现的算法都可以用tensorflow实现。我们先举一个简单的例子,绘制心形曲线。

绘制心形曲线

我们试着用两种不同的方法绘制心形曲线。常见的两种心形曲线的公式为:
在这里插入图片描述

我们用变量型和占位符型两种方式定义张量,构建tf计算图。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan  6 10:04:01 2020

@author: lxy_alex@outlook.com

"""

import tensorflow as tf


if ~tf.compat.v1.executing_eagerly():
    tf.compat.v1.disable_eager_execution()
    
import numpy as np
import matplotlib.pyplot as plt

# 变量型张量   
def variable_tensor(x):

    vx = tf.Variable(x)
    y_part1 = 0.618*tf.math.abs(vx)
    y_part2 = 0.8*tf.math.sqrt(64-tf.math.square(vx))
    
    part1 = tf.math.add(y_part1, y_part2)
    part2 = tf.math.subtract(y_part1, y_part2)
    
    init_op = tf.compat.v1.global_variables_initializer()
    
    with tf.compat.v1.Session() as sess:
        sess.run(init_op)
        y1 = sess.run(part1)
        y2 = sess.run(part2)
    return y1, y2


# 占位符型张量
def placeholder_tensor(data):
    t = tf.compat.v1.placeholder(tf.float32, shape=(100,))
    tx = 2*tf.math.cos(t) - tf.math.cos(2*t)
    ty = 2*tf.math.sin(t) - tf.math.sin(2*t)
    
    with tf.compat.v1.Session() as sess:
        y = sess.run(tx, feed_dict={t:data})
        x = sess.run(ty, feed_dict={t:data})    
    return x,y

if __name__ == "__main__":
    # 心形曲线1
    x = np.linspace(-8,8,100)
    y1, y2 = variable_tensor(x)
    plt.subplot(1,2,1),plt.plot(x, y1, color = 'r')
    plt.subplot(1,2,1),plt.plot(x, y2, color = 'r')
    plt.axis('equal')

    # 心形曲线2
    data = np.linspace(0, 2*np.pi, 100)
    x, y = placeholder_tensor(data)
    plt.subplot(1,2,2),plt.plot(x, y, color = 'r')
    plt.axis('equal')
    plt.show()

得到:
在这里插入图片描述

开根号

开根号是一道常见的算法面试题。题目是:给定数字a,在不调用sqrt()函数的情况下求的该数的开方。这道题的经典做法是用牛顿迭代法,当然,也可以用tensorflow来实现(最小二乘法)。


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan  6 13:50:45 2020

@author: lxy_alex@outlook.com
"""


import tensorflow as tf

if ~tf.compat.v1.executing_eagerly():
    tf.compat.v1.disable_eager_execution()

# 牛顿迭代法
def solve_root(a):  
    x0 = a
    while (x0*x0-a)>1e-5:
        x0 = (x0+a/x0)/2
        
    return x0

# 
def tf_solve_root(a):
    x = tf.Variable(a,dtype=tf.float32)
    x = tf.compat.v1.placeholder(shape=(None,10), dtype=tf.float32)
    x2 = tf.math.multiply(x,x)
    loss = tf.math.square(x2-a)
    opt = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1)
    train = opt.minimize(loss)

    with tf.compat.v1.Session() as sess:
        sess.run(x.initializer)
        for step in range(200):
            sess.run(train, feed_dict={x:a})
            root_a = sess.run(x)
            
    return root_a
            

if __name__=='__main__':
    print(solve_root(2))  
    print(tf_solve_root())
    

得到

1.4142156862745097
1.4142137

线性回归

tensorflow构建线性回归 linear regression model。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan  6 16:15:28 2020

@author: lxy_alex@outlook.com
"""

import tensorflow as tf
import numpy as np



if ~tf.compat.v1.executing_eagerly():
    tf.compat.v1.disable_eager_execution()
    
    
x_data = np.random.randn(2000,3)
w_real = [0.4, 0.5, 0.12]
b_real = 0.3

noise = np.random.randn(1,2000)*0.1
y_data = np.matmul(w_real,x_data.transpose())+b_real+noise

NUM_STEPS= 20

g  = tf.Graph()
wb_ = []
with g.as_default():
    x = tf.compat.v1.placeholder(tf.float64, shape=[None, 3])
    y_true = tf.compat.v1.placeholder(tf.float64, shape=None)
    
    w = tf.Variable([[0,0,0]], dtype = tf.float64)
    b = tf.Variable(0, dtype=tf.float64)
    y_pred = tf.matmul(w, tf.transpose(x))+b
    
    loss = tf.reduce_mean(tf.square(y_true-y_pred))
    
    optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.5)
    train = optimizer.minimize(loss)
    
    init = tf.compat.v1.global_variables_initializer()
    with tf.compat.v1.Session() as sess:
        sess.run(init)
        for step in range(NUM_STEPS):
            sess.run(train, {x:x_data, y_true:y_data})
            wb_.append(sess.run([w,b]))
            print(step,sess.run([w,b]))


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

tensorflow 2.0系列(3):eager execution和计算图 的相关文章

随机推荐

  • libjvm.so: ELF file OS ABI invalid

    Error dl failure on line 893 Error failed 某目录 jdk jre lib amd64 server libjvm so because 某目录 jdk jre lib amd64 server li
  • win11启用旧右键菜单(不折叠)的方案,亲测有效

    我电脑的winodws11版本如下 在以上win版本下 xff0c 测试网上说的以下几个办法都不行 1 权利与暗访时在终端运行 reg exe delete HKCU Software Classes CLSID 86ca1aa0 34aa
  • Android中的动画总结

    Android 动画 三种总结 xff1a 属性动画 xff1a 动态的改变属性产生动画效果 xff1b 改变动画的属性 xff0c 两个重要的类 xff1a 1 ValueAnimator 类是先改变值 xff0c 然后 手动赋值 给对象
  • ubuntu自动登录tty终端的最简方法

    背景 在嵌入式系统经常需要自动登录tty xff0c 以实现业务程序开机启动的效果 网上有篇文章ubuntu自动登录tty1 shell text 配置转发挺多 xff0c 但我弄明白原理后 xff0c 觉得可以进一步简化 xff0c 经测
  • git为指定项目设置用户名密码

    我们如果没有为项目设置用户名密码 xff0c 那么每次提交都会有提示账号和密码输入 xff1a 1 找到你项目的半隐藏文件 git文件夹 xff0c 通常只要git init 就会生成这样一个文件夹 xff0c 现在双击进入文件夹 xff1
  • JAVA 访问windows共享文件夹

    一 使用技术 JCIFS框架对Windows共享文件夹进行读写 xff0c 使用了SMB通信协议 xff0c 它为局域网内不同的计算机之间提供文件和打印机等资源共享服务 二 共享文件夹设置 测试共享文件夹机器windows版本为win10家
  • 前端代码调试:Webstorm调试js

    前言 目前前端开发 JavaScript的debug一般都是用chrome和firefox的开发者工具进行调试 xff0c 浏览器工具使用不方便 xff0c webstorm支持了在代码上打断点 xff0c 在编辑器里debug js代码
  • CV:基本概念和工具

    文章目录 计算机视觉像素 xff0c 颜色 xff0c 通道 xff0c 图像和颜色空间的概念图像文件后缀有损压缩和无损压缩 Python的计算机视觉库PIL xff1a python 图像处理类库载入PIL库基本操作命令 openCVop
  • OCR技术概览

    OCR技术概览 OCR Optical Character Recognition 光学字符识别技术主要分为手写体识别和印刷体识别两类 印刷体识别比手写体识别要简单 因为印刷体更规范 字体来自于计算机字库 尽管印刷过程中可能会发生不清晰 粘
  • CV:图像色彩空间及色彩处理

    文章目录 基本概念RGB空间HSV空间HSL空间 色彩变换灰度变换色彩反向 调整像素区间增强对比度直方图均衡化 图像平滑 减少噪声图像平均高斯滤波 图像梯度sobel算子 scharr算子prewitt算子Laplacian 算子 参考及更
  • OpenCV角点检测: Harris算子, ShiTomasi算子

    角点检测 角点的特征检测与匹配是Computer Vision 应用总重要的一部分 xff0c 这需要寻找图像之间的特征建立对应关系 点 xff0c 也就是图像中的特殊位置 xff0c 是很常用的一类特征 xff0c 点的局部特征也可以叫做
  • 集成学习:让算法和算法赛跑

    文章目录 集成学习的基本概念构建弱分类器 xff1a 决策树自助采样法bootstrappingbootstrapping的核心思想bootstrapping与permutation的区别 baggingboosting为何bagging会
  • backbone模型:FCN、SRN、STN

    文章目录 FCN网络CNN图像分割模型结构FCN github资源FCN的优缺点 SRN 网络什么是空间规整 spatial regularization xff09 SRN网络github资源 STN网络空间变换器localisation
  • docker部署机器学习/深度学习模型的容器化方案

    文章目录 什么是dockerdocker的优点 docker image镜像Dockerfile 文件Dockerfile配置例子 创建docker镜像 docker container 容器模型部署参考和更多阅读 docker部署机器学习
  • RNN模型训练经验总结

    文章目录 RNN模型训练经验总结数据准备 look at your data 小步试错 搭建模型设置端到端的训练评估框架 forward propagation设置激活函数dropout back propagation设置学习率 lear
  • 算法的时间复杂度和空间复杂度

    如何评价算法的性能 定义 一个算法中的语句执行次数称为 语句频度 或 时间频度 约定 检验算法的效率 xff0c 主要考虑 最坏时间复杂度 和 平均时间复杂度 一般不特别说明 xff0c 讨论的时间复杂度均是最坏情况下的时间复杂度 时间复杂
  • 【LeetCode】LCS最长公共子序列

    最长公共子序列 题目描述思路分析递归结构算法实现输出最长子序列算法实现 题目描述 思路分析 设A 61 a0 xff0c a1 xff0c xff0c am xff0c B 61 b0 xff0c b1 xff0c xff0c bn xff
  • 升级到tensorflow2.0

    目录 从tensorflow1 x升级到2 x方案一 xff1a 依然使用tf 1 x的脚本方案二 xff1a 升级项目代码到2 x tensorflow2 0推出以后 xff0c 全面拥抱keras xff0c 简化了API接口 xff0
  • tensorflow2.0系列(1):张量

    目录 tensor xff1a 张量张量的数据类型Dtype类函数tf as type xff1a 定义Dtype类型对象tf dtypes cast xff1a 将张量映射 投射为新的类型tf dtypes complex xff1a 将
  • tensorflow 2.0系列(3):eager execution和计算图

    目录 tf 2 0 的新特性 xff1a eager execution开启eager模式关闭eager模式 构建图默认图创建多个计算图启动会话 从公式到计算图绘制心形曲线开根号线性回归 tf 2 0 的新特性 xff1a eager ex