tensorflow计算图

fanhaha fanhaha     2023-04-17     539

关键词:

tensorflow计算图

      计算图是对有向图的表示,主要包含点和边;tensorflow使用计算图计算,计算图的点对应于ops,variables,constant,placeholder等,边对应于Tensors。因此tensorflow主要包含两个部分:构建计算图和runtime运行计算图。

 为什么要用计算图?

  1. 并行化,因为计算图是对计算的一种抽象,点之间的关系取决其依赖关系。因此,互相不依赖的计算可以并行计算,在多集群环境下可以进行分布式计算。
  2. 可移植性性,因为图是一种语言无关的表示方式,tensorflow 中使用protobuf来存储图,可以使用C++,python,jave等语言来解析图。 

总结一下,tensorflow 中要进行计算主要进行两个步骤: 1. 构建graph; 2. session evaluate tensor

假如要实现一个类似tensorflow框架,需要如何操作?

  • node 节点的实现:
class Node():
    def __init__(self, input_nodes):
        self.input_nodes=input_nodes
        self.output=Node
    
    def forward(self):
        pass
    def backward(self):
        pass
技术图片

 

class add(Node):
    def forward(self, a,b):
        return a+b
    def backward(self,upstream_grad):
        NotImpl

class multiple(Node):
    def forward(self, a,b):
        return a*b
    def backward(self,upstream_grad):
        NotImpl
技术图片

 

  • graph 实现
class Graph():
    def __init__(self):
        self.nodes = []
    def as_default(self):
        global _default_graph

    def add_node(self,node):
        _default_graph.append(node)
技术图片
  • session 实现
# session 接受要run的operation,要得到输出要拓扑排序所有的node,在session run的时候,按正确顺序执行。 可以表示为DAG(directed acyclic graph) 
#  将要执行的node作为unvisited node加入栈中,利用深度优先搜索的方式递归遍历所有的node,当node没有其他输入时,将node标记为visited出栈。出栈的顺序就是拓扑排序。 

class Session():
    def run(self, node, feed_dict=):
        nodes_sorted=topology_sort(node)
        for node in nodes_sorted:
            if type(node)==Placeholder:
                node.output=feed_dict[node]
            elif type(node)==Variable or type(node)==Constant:
                node.output=node.value
            else:
                inputs=[node.output for node in node.input_nodes]
                node.output=node.forward(*inputs)
        return node.output          
技术图片

 

完整的code:

import numpy as np

class Graph():
  def __init__(self):
    self.operations = []
    self.placeholders = []
    self.variables = []
    self.constants = []

  def as_default(self):
    global _default_graph
    _default_graph = self

class Operation():
  def __init__(self, input_nodes=None):
    self.input_nodes = input_nodes
    self.output = None
    
    # Append operation to the list of operations of the default graph
    _default_graph.operations.append(self)

  def forward(self):
    pass

  def backward(self):
    pass

class BinaryOperation(Operation):
  def __init__(self, a, b):
    super().__init__([a, b])

class add(BinaryOperation):
  """
  Computes a + b element-wise
  """
  def forward(self, a, b):
    return a + b

  def backward(self, upstream_grad):
    raise NotImplementedError

class multiply(BinaryOperation):
  """
  Computes a * b, element-wise
  """
  def forward(self, a, b):
    return a * b

  def backward(self, upstream_grad):
    raise NotImplementedError

class divide(BinaryOperation):
  """
  Returns the true division of the inputs, element-wise
  """
  def forward(self, a, b):
    return np.true_divide(a, b)

  def backward(self, upstream_grad):
    raise NotImplementedError

class matmul(BinaryOperation):
  """
  Multiplies matrix a by matrix b, producing a * b
  """
  def forward(self, a, b):
    return a.dot(b)

  def backward(self, upstream_grad):
    raise NotImplementedError

class Placeholder():
  def __init__(self):
    self.value = None
    _default_graph.placeholders.append(self)

class Constant():
  def __init__(self, value=None):
    self.__value = value
    _default_graph.constants.append(self)

  @property
  def value(self):
    return self.__value

  @value.setter
  def value(self, value):
    raise ValueError("Cannot reassign value.")

class Variable():
  def __init__(self, initial_value=None):
    self.value = initial_value
    _default_graph.variables.append(self)

def topology_sort(operation):
    ordering = []
    visited_nodes = set()

    def recursive_helper(node):
      if isinstance(node, Operation):
        for input_node in node.input_nodes:
          if input_node not in visited_nodes:
            recursive_helper(input_node)

      visited_nodes.add(node)
      ordering.append(node)

    # start recursive depth-first search
    recursive_helper(operation)

    return ordering

class Session():
  def run(self, operation, feed_dict=):
    nodes_sorted = topology_sort(operation)

    for node in nodes_sorted:
      if type(node) == Placeholder:
        node.output = feed_dict[node]
      elif type(node) == Variable or type(node) == Constant:
        node.output = node.value
      else:
        inputs = [node.output for node in node.input_nodes]
        node.output = node.forward(*inputs)

    return operation.output






import tf_api as tf

# create default graph
tf.Graph().as_default()

# construct computational graph by creating some nodes
a = tf.Constant(15)
b = tf.Constant(5)
prod = tf.multiply(a, b)
sum = tf.add(a, b)
res = tf.divide(prod, sum)

# create a session object
session = tf.Session()

# run computational graph to compute the output for ‘res‘
out = session.run(res)
print(out)

技术图片

《30天吃掉那只tensorflow2.0》2-2三种计算图

...的构建方式:静态计算图,动态计算图,以及Autograph.在TensorFlow1.0时代,采用的是静态计算图,需要先使用TensorFlow的各种算子创建计算图,然后再开启一个会话Session,显式执行计算图。而在TensorFlow2.0时代,采用的是动态计算图... 查看详情

tensorflow实战google深度学习框架(代码片段)

第3章TensorFlow入门3.1TensorFlow计算模型-计算图3.1.1计算图的概念Tensorflow中所有计算都会被转化成计算图的一个节点,计算图上的边表示了他们之间的相互依赖关系。3.1.2计算图的使用Tensorflow的程序可以分成两个阶段:定义计算、... 查看详情

tensorflow计算模型--计算图(代码片段)

TensorFlow是一个通过计算图的形式表述计算机的编程系统TensorFlow程序一般分为两个阶段,第一个阶段需要定义计算图中所有的计算(变量)第二个阶段为执行计算如以下代码importtensorflowastf#第一阶段定义所有的计算a=tf.constant([1,2]... 查看详情

第3章tensorflow入门

...”,它直观地表达了张量之间通过计算相互转化的过程。TensorFlow是一个通过计算图的形式来表达计算的编程系统。TensorFlow中的每一个计算都是计算图上的一个节点,而节点之间的边描述了计算之间的依赖关系。  每一个节点... 查看详情

tensorflow框架(代码片段)

TensorFlowTensorFlow核心程序由2个独立部分组成:   a:Building thecomputationalgraph构建计算图   b:Running thecomputationalgraph运行计算图1.一个computationalgraph(计算图)是一系列的TensorFlow操作排列成一个节点图。  1.1构建计... 查看详情

tensorflow_fold计算图连接初探diamond计算图调试历程

...文章的Markdown前;哦第二篇我指的是名字类似是《【TensorFlow_Fold】深度探究BlocksforComposition(未完成)》的东西;进行到计算图不同的block间的连接这一部分,但是td中琳琅满目的函数对输入输出却有着千奇百怪的格式需求... 查看详情

tensorflow-新的计算图(代码片段)

生成新的计算图,并完成常量初始化,在新的计算图中完成加法计算importtensorflowastfg1=tf.Graph()withg1.as_default():???value=[1.,2.,3.,4.,5.,6.]???init=tf.constant_initializer(value)???x=tf.get_variable("x",initializer=init,shape=[2, 查看详情

人工智能深度学习入门练习之(21)tensorflow–创建计算图(代码片段)

...建计算图下面的代码在内存中创建一个默认计算图。importtensorflowastfx=tf.Variable(3,name="x")y=tf.Variable(4,name="y")f=x*x*y+y+2代码中声明了变量和函数,这将会在内存中创建一个默认计算图。默认计算图默认计算图是TensorFlow默认生成的计... 查看详情

tensorflow-新计算图(代码片段)

...算图,并完成常量初始化[代码1][email protected]"""import?tensorflow?as?tfg?=?tf.Graph()with?g.as_default():??c?=?tf.constant(5.0)??assert?c.graph?is?g??print?"ok"[代码2]#?-*-?coding:?utf-8?-*-"""Spyder?Editor生成新的计算图,并完成常量初始化[email protected]"""... 查看详情

tensorflow-计算图(代码片段)

...#-*-coding:utf-8-*-"""CreatedonSunDec2311:26:042018@author:myhaspl"""importtensorflowastf#创建图c=tf.constant(0.0)g=tf.Graph()withg.as_default():c1=tf.constant(0.1)print(c1.graph)print(g)print(c.graph)<tensorflow.python.framework.ops.Graphobjectat0xb1cd345c0><tensorflow.python.framework.... 查看详情

tensorflow

一 基本概念:  Tensorflow是一个计算密集型的编程系统,使用图(graphs)来表示计算任务,图(graphs)中的节点称之为op(operation),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。Tensor看作是一个n维的数组或列... 查看详情

tensorflow架构学习

0-TensorFlow  基于数据流图,节点表示某种抽象计算,边表示节点之间联系的张量。  Tensorflow结构灵活,能够支持各种网络模型,有良好的通用性和扩展性。            1-系统概述  TensorFlow以$CAPI$为界限,... 查看详情

tensorflow编程基础

•TensorFlow™是一个开放源代码软件库,用于进行高性能数值计算•借助其灵活的架构,用户可以轻松地将计算工作部署到多种平台(CPU、GPU、TPU)和设备(桌面设备、服务器集群、移动设备、边缘设备等)•TensorFlow&tr... 查看详情

说清楚tensorflow是什么(代码片段)

导读:在开始使用TensorFlow之前,必须了解它背后的理念。该库很大程度上基于计算图的概念,除非了解它们是如何工作的,否则无法理解如何使用该库。本文将简要介绍计算图,并展示如何使用TensorFlow实现简... 查看详情

说清楚tensorflow是什么(代码片段)

导读:在开始使用TensorFlow之前,必须了解它背后的理念。该库很大程度上基于计算图的概念,除非了解它们是如何工作的,否则无法理解如何使用该库。本文将简要介绍计算图,并展示如何使用TensorFlow实现简... 查看详情

tensorflow入门上(自用)

下文会出现的一些知识点:TensorFlow的计算模型、数据模型、运行模型,TensorFlow的工作原理。 两个重要概念——Tensor和Flow:  Tensor是张量,在TensorFlow中可以简单理解为多维数组。  Flow是流,表示张量之间通过计算相互... 查看详情

tensorflow核心概念及基本使用

TensorFlow核心概念  综述:TensorFlow中的计算可以表示为一个有向图,或称计算图,其中每一个运算操作将作为一个节点,节点间的链接叫做边。这个计算图描述了数据的计算流程,它也负责维护和更新状态,用户可以对计算图... 查看详情

tensorflow-计算图(代码片段)

...#-*-coding:utf-8-*-"""CreatedonSunDec2311:26:042018@author:myhaspl"""importtensorflowastf#创建图c=tf.constant(0.0)g=tf.Graph()withg.as_default():c1=tf.constant(0.1)g2=tf.get_default_graph()print(g2)tf.reset_default_graph()g3=tf.get_default_graph()print(g3)print(c1.name)<tensorflow.python.frame... 查看详情