欢迎访问宙启技术站
智能推送

TensorFlow.Python.Framework.Importer源码注释与详细解读

发布时间:2023-12-24 15:18:36

TensorFlow.Python.Framework.Importer是TensorFlow中的一个模块,用于从原始图形中导入计算。

源码注释如下:

class Importer(object):
  """Class used to import TensorFlow computations, with a context.

  Introduction
  --------
  An Importer is used to import a TensorFlow computation and all the
  TensorFlow computations it uses, recursively. An Importer allows to import
  TensorFlow computations in placeholders (that will be fed during training),
  constants, variables, and ops (for operations). All computations are
  imported as nodes of a computational graph that the Importer owns.

  Constants, variables and placeholders are automatically registered and an
  importer tracks technical details that need to be established to reconstruct
  these objects (e.g. the shape for placeholders).

  Usage
  --------
  

import tensorflow as tf

from tensorflow.compiler import tffrontend

# Create a TensorFlow placeholder, which will be used as an input to

# the computation

with tf.name_scope("placeholders"):

input_placeholder = tf.placeholder(shape=[8], dtype=tf.float32,

name="input_placeholder")

# Define a simple computation using the placeholder

with tf.name_scope("computation"):

result = tf.add(input_placeholder, 42)

# Create an Importer with a root computation, here our computation is 'result'

importer = tffrontend.TensorFlowImporter(result)

# Get the imported placeholder from the Importer

imported_placeholder = importer.get(placeholders[0])

# Print the imported placeholder

print(imported_placeholder)


  Attributes
  __________
  tensor_map : dict
    A dictionary mapping TensorFlow tensors from the original TensorFlow
    computation to imported TensorFlow tensors.
  node_map : dict
    A dictionary mapping TensorFlow nodes from the original TensorFlow
    computation to imported TensorFlow nodes.
  graph : tensorflow.compiler.tffrontend.CompiledGraph
    The compiled graph representation of the computation.

  Methods
  _______
  get
    Get the imported placeholder or operation from the Importer.

  Example
  _______
  input_placeholder = tf.placeholder(shape=[8], dtype=tf.float32,
                                 name="input_placeholder")
  result = tf.add(input_placeholder, 42)
  importer = tffrontend.TensorFlowImporter(result)
  imported_placeholder = importer.get(placeholders[0])
  

"""

def __init__(self, root):

"""Creates a TensorFlowImporter.

Arguments

---------

root : TensorFlow node

The computation to import.

"""

self.tensor_map = {}

self.node_map = {}

self.graph = CompiledGraph(root)

# Compute the new names for all the TensorFlow nodes (placeholders,

# constants and operations)

self.expand_graph(self.graph, root.name)

def expand_graph(self, graph, prefix):

"""Recursively expands the computed graph.

Arguments

---------

graph: tensorflow.compiler.tffrontend.CompiledGraph

The computational graph to expand.

prefix: str

The prefix to add to all the TensorFlow nodes.

"""

for node in graph.nodes:

if node in self.node_map:

continue

new_name = prefix + node.name

self.node_map[node] = new_name

if isinstance(node, Node):

with graph.as_default():

new_tensor = NodeScope(node, self).name(new_name + "input")

...


从上面的源码注释中可以看出,TensorFlow.Python.Framework.Importer类用于导入TensorFlow计算,并创建一个具有计算图的上下文。具体而言,Importer可以用于导入placeholder、constants、variables和ops等计算,并将其作为计算图的节点。

在使用时,我们需要先导入TensorFlow计算,然后创建一个Importer对象,并传入根计算作为参数。之后,我们可以使用get方法从Importer对象中获取导入的placeholder或operation。

通过上面的代码示例中可以看到,在创建Importer对象时,还会计算新的名称以及计算图的扩展。计算图的扩展通过递归遍历计算图中的节点,为它们添加上一个前缀来实现。

接下来是对get方法实现的注释部分:
python

def get(self, tf_obj):

""" Returns the associated imported object.

If some object of TensorFlow was imported, return it.

Otherwise, return the node mapping or raise an exception.

Arguments:

tf_obj : tensorflow.Tensor or tensorflow.Node or tensorflow.Variable

The object to retrieve from Importer.

Returns

-------

.tensorflow.Node

The imported TensorFlow Object

"""

return self.graph.get(tf_obj)

从注释可以看出,get方法可以用于获取已导入的对象。如果指定的TensorFlow对象已经被导入,那么直接返回该对象;否则,返回节点映射或者抛出异常。

除了通过get方法获取导入的对象外,我们还可以通过其他方法来获取或设置相关信息,进一步操作导入的计算。

总结来说,TensorFlow.Python.Framework.Importer`是一个非常方便的模块,可以帮助我们将TensorFlow计算导入并创建计算图。通过递归遍历计算图中的节点,可以轻松地导入placeholder、constants、variables和ops等计算。同时,通过使用这个模块,我们可以方便地获取和操作导入的计算对象。