Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Tensorflow中,获取图形中所有张量的名称_Python_Tensorflow_Tensorboard_Skflow - Fatal编程技术网

Python 在Tensorflow中,获取图形中所有张量的名称

Python 在Tensorflow中,获取图形中所有张量的名称,python,tensorflow,tensorboard,skflow,Python,Tensorflow,Tensorboard,Skflow,我正在用Tensorflow和skflow创建神经网络;出于某种原因,我想获得给定输入的一些内张量的值,因此我使用了myClassifier.get_layer\u value(输入,“tensorName”),myClassifier作为skflow.estimators.tensorflowsestimator 然而,我发现很难找到张量名称的正确语法,即使知道它的名称(我对操作和张量感到困惑),所以我使用tensorboard绘制图形并查找名称 有没有办法不用tensorboard来枚举一个

我正在用
Tensorflow
skflow
创建神经网络;出于某种原因,我想获得给定输入的一些内张量的值,因此我使用了
myClassifier.get_layer\u value(输入,“tensorName”)
myClassifier
作为
skflow.estimators.tensorflowsestimator

然而,我发现很难找到张量名称的正确语法,即使知道它的名称(我对操作和张量感到困惑),所以我使用tensorboard绘制图形并查找名称

有没有办法不用tensorboard来枚举一个图中的所有张量?

你可以这样做

[n.name for n in tf.get_default_graph().as_graph_def().node]
此外,如果您正在IPython笔记本中进行原型设计,您可以直接在笔记本中显示图形,请参阅Alexander's Deep Dream中的
show\u graph
函数。所有变量()都可以为您提供所需的信息


此外,今天在TensorFlow学习中制作,它在估计器中提供了一个函数
get_variable_names
,您可以使用该函数轻松检索所有变量名

有一种方法比雅罗斯拉夫的答案稍微快一点,就是使用。下面是一个简单的例子:

import tensorflow as tf

a = tf.constant(1.3, name='const_a')
b = tf.Variable(3.1, name='variable_b')
c = tf.add(a, b, name='addition')
d = tf.multiply(c, a, name='multiply')

for op in tf.get_default_graph().get_operations():
    print(str(op.name))

我认为这也可以:

print(tf.contrib.graph_editor.get_tensors(tf.get_default_graph()))

但与Salvado和Yaroslav的答案相比,我不知道哪一个更好。

接受的答案只给出了一个带名称的字符串列表。我更喜欢另一种方法,它可以(几乎)直接访问张量:

graph = tf.get_default_graph()
list_of_tuples = [op.values() for op in graph.get_operations()]
元组列表现在包含元组中的每个张量。您还可以调整它以直接获得张量:

graph = tf.get_default_graph()
list_of_tuples = [op.values()[0] for op in graph.get_operations()]

前面的答案很好,我只想分享我编写的一个实用函数,用于从图形中选择张量:

def get_graph_op(graph, and_conds=None, op='and', or_conds=None):
    """Selects nodes' names in the graph if:
    - The name contains all items in and_conds
    - OR/AND depending on op
    - The name contains any item in or_conds

    Condition starting with a "!" are negated.
    Returns all ops if no optional arguments is given.

    Args:
        graph (tf.Graph): The graph containing sought tensors
        and_conds (list(str)), optional): Defaults to None.
            "and" conditions
        op (str, optional): Defaults to 'and'. 
            How to link the and_conds and or_conds:
            with an 'and' or an 'or'
        or_conds (list(str), optional): Defaults to None.
            "or conditions"

    Returns:
        list(str): list of relevant tensor names
    """
    assert op in {'and', 'or'}

    if and_conds is None:
        and_conds = ['']
    if or_conds is None:
        or_conds = ['']

    node_names = [n.name for n in graph.as_graph_def().node]

    ands = {
        n for n in node_names
        if all(
            cond in n if '!' not in cond
            else cond[1:] not in n
            for cond in and_conds
        )}

    ors = {
        n for n in node_names
        if any(
            cond in n if '!' not in cond
            else cond[1:] not in n
            for cond in or_conds
        )}

    if op == 'and':
        return [
            n for n in node_names
            if n in ands.intersection(ors)
        ]
    elif op == 'or':
        return [
            n for n in node_names
            if n in ands.union(ors)
        ]
因此,如果您有一个带有ops的图:

['model/classifier/dense/kernel',
'model/classifier/dense/kernel/Assign',
'model/classifier/dense/kernel/read',
'model/classifier/dense/bias',
'model/classifier/dense/bias/Assign',
'model/classifier/dense/bias/read',
'model/classifier/dense/MatMul',
'model/classifier/dense/BiasAdd',
'model/classifier/ArgMax/dimension',
'model/classifier/ArgMax']
然后跑

get_graph_op(tf.get_default_graph(), ['dense', '!kernel'], 'or', ['Assign'])
返回:

['model/classifier/dense/kernel/Assign',
'model/classifier/dense/bias',
'model/classifier/dense/bias/Assign',
'model/classifier/dense/bias/read',
'model/classifier/dense/MatMul',
'model/classifier/dense/BiasAdd']
这对我很有用:

for n in tf.get_default_graph().as_graph_def().node:
    print('\n',n)

由于OP要求的是张量列表而不是操作/节点列表,因此代码应该略有不同:

graph = tf.get_default_graph()    
tensors_per_node = [node.values() for node in graph.get_operations()]
tensor_names = [tensor.name for tensors in tensors_per_node for tensor in tensors]

我将尝试总结一下答案:

获取图形中的所有节点:(键入
tensorflow.core.framework.node\u def\u pb2.nodededef

all_nodes=[n代表tf中的n.get_default_graph().as_graph_def().node]
获取图形中的所有操作:(键入
tensorflow.python.framework.ops.Operation

all_ops=tf.get_default_graph().get_operations()
获取图形中的所有变量:(键入
tensorflow.python.ops.resource\u variable\u ops.resource variable

all_vars=tf.global_variables()
获取图形中的所有张量:(键入
tensorflow.python.framework.ops.Tensor

all_tensors=[tf.get_default_graph()中op的张量。op.values()中的张量的get_operations()]
获取图形中的所有占位符:(键入
tensorflow.python.framework.ops.Tensor

all_placeholder=[tf.get_default_graph()中op的占位符。如果op.type=='op.values()中的占位符,则get_operations()]
Tensorflow 2

要在Tensorflow 2中获取图形,而不是
tf.get\u default\u graph()
您需要先实例化
tf.function
并访问
graph
属性,例如:

graph=func.get\u concrete\u function().graph

其中
func
是一个
tf.function

以下解决方案在TensorFlow 2.3中适用-

def load_-pb(路径到路径):
将tf.io.gfile.gfile(路径_到_-pb,'rb')作为f:
graph_def=tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
将tf.Graph()作为\u default()作为图形:
tf.import_graph_def(graph_def,name='')
返回图
其中
MODEL_FILE
是指向冻结图形的路径


摘自。

此函数已弃用。。。它的后继者是
tf.global_variables()
这只获取变量,而不是张量。在Tensorflow 1.9.0中显示
所有_变量(来自Tensorflow.python.ops.variables)都已弃用,并将在2017-03-02之后删除
您可以通过添加
if“Variable”来过滤变量在理解结束时的n.op
中。如果您知道某个节点的名称,是否有办法获取该节点?阅读更多关于图形节点的信息:上面的命令将生成所有操作/节点的名称。要获取所有张量的名称,请执行以下操作:tensors_per_node=[node.values()(用于图形中的节点)get_operations()]tensor_names=[tensor.name(用于张量中的张量)tensors(用于张量中的张量)per_node(用于张量中的张量)]此操作使用从tensorflow对象检测API中使用的冻结的\u推断图.pb文件导入的图形。感谢您无法使用
tf.get\u operations()
获取张量。您只能获得一个操作。请注意TF2版本!
tf_graph = load_pb(MODEL_FILE)
sess = tf.compat.v1.Session(graph=tf_graph)

# Show tensor names in graph
for op in tf_graph.get_operations():
    print(op.values())