В Tensorflow получите имена всех тензоров в графе


118

Я создаю нейронные сети с помощью Tensorflowи skflow; по какой-то причине я хочу получить значения некоторых внутренних тензоров для заданного ввода, поэтому я использую myClassifier.get_layer_value(input, "tensorName"), myClassifierбудучи skflow.estimators.TensorFlowEstimator.

Однако мне трудно найти правильный синтаксис имени тензора, даже зная его имя (и я путаюсь между операцией и тензорами), поэтому я использую тензорную доску для построения графика и поиска имени.

Есть ли способ перечислить все тензоры на графике без использования тензорной доски?

Ответы:


189

Ты можешь сделать

[n.name for n in tf.get_default_graph().as_graph_def().node]

Кроме того, если вы создаете прототип в блокноте IPython, вы можете показать график прямо в блокноте, см. show_graphФункцию в блокноте Alexander's Deep Dream.


2
Вы можете отфильтровать это, например, по переменным, добавив if "Variable" in n.opв конце понимания.
— Radu

Есть ли способ получить конкретный узел, если вы знаете его имя?
— Rocket Pingu

Чтобы узнать больше об узлах графа: tensorflow.org/extend/tool_developers/#nodes
— Иван Талалаев

3
Приведенная выше команда дает имена всех операций / узлов. Чтобы получить имена всех тензоров, выполните: tensors_per_node = [node.values ​​() для узла в graph.get_operations ()] tensor_names = [tensor.name для тензоров в tensors_per_node для тензора в тензорах]
— gebbissimo

24

Есть способ сделать это немного быстрее, чем в ответе Ярослава, с помощью get_operations . Вот краткий пример:

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))

2
Вы не можете получить тензор, используя tf.get_operations(). Только операцию можно получить.
— Soulduck

14

Попробую обобщить ответы:

Чтобы получить все узлы (введите tensorflow.core.framework.node_def_pb2.NodeDef):

all_nodes = [n for n in tf.get_default_graph().as_graph_def().node]

Чтобы получить все операции (введите tensorflow.python.framework.ops.Operation):

all_ops = tf.get_default_graph().get_operations()

Чтобы получить все переменные (введите tensorflow.python.ops.resource_variable_ops.ResourceVariable):

all_vars = tf.global_variables()

Чтобы получить все тензоры (введите tensorflow.python.framework.ops.Tensor) :

all_tensors = [tensor for op in tf.get_default_graph().get_operations() for tensor in op.values()]

11

tf.all_variables() может предоставить вам необходимую информацию.

Кроме того, этот коммит, сделанный сегодня в TensorFlow Learn, предоставляет функцию get_variable_namesв оценщике, которую вы можете использовать для легкого получения всех имен переменных.


Эта функция устарела
— CAFEBABE

8
... и его преемникtf.global_variables()
— bluenote10

11
это выбирает только переменные, а не тензоры.
— Раджарши Митра 04

В Tensorflow 1.9.0 это показываетall_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02
— stackoverYC

5

Думаю, это тоже подойдет:

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

Но по сравнению с ответами Сальвадо и Ярослава не знаю, какой из них лучше.


Этот работал с графиком, импортированным из файла frozen_inference_graph.pb, используемого в API обнаружения объектов tensorflow. Спасибо
— simo23

4

Принятый ответ дает вам только список строк с именами. Я предпочитаю другой подход, который дает (почти) прямой доступ к тензорам:

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

list_of_tuplesтеперь содержит каждый тензор, каждый в кортеже. Вы также можете адаптировать его для прямого получения тензоров:

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

4

Поскольку 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]

3

Предыдущие ответы хороши, я просто хотел бы поделиться служебной функцией, которую я написал для выбора тензоров из графика:

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)
        ]

Итак, если у вас есть график с операциями:

['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']

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.