In Tensorflow, ottieni i nomi di tutti i tensori in un grafico


118

Sto creando reti neurali con Tensorfloweskflow ; per qualche motivo voglio ottenere i valori di alcuni tensori interni per un dato input, quindi sto usando myClassifier.get_layer_value(input, "tensorName"), myClassifieressendo a skflow.estimators.TensorFlowEstimator.

Tuttavia, trovo difficile trovare la sintassi corretta del nome del tensore, anche conoscendone il nome (e mi sto confondendo tra operazione e tensori), quindi sto usando tensorboard per tracciare il grafico e cercare il nome.

C'è un modo per enumerare tutti i tensori in un grafico senza usare il tensore?

Risposte:


189

Tu puoi fare

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

Inoltre, se stai prototipando in un notebook IPython, puoi mostrare il grafico direttamente nel notebook, vedi la show_graphfunzione nel notebook Deep Dream di Alexander


2
Puoi filtrarlo per es. Variabili aggiungendo if "Variable" in n.opalla fine della comprensione.
— Radu

C'è un modo per ottenere un nodo specifico se ne conosci il nome?
— Rocket Pingu

Per saperne di più sui nodi grafici: tensorflow.org/extend/tool_developers/#nodes
— Ivan Talalaev

3
Il comando precedente fornisce i nomi di tutte le operazioni / nodi. Per ottenere i nomi di tutti i tensori, fai: 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

24

C'è un modo per farlo leggermente più velocemente rispetto alla risposta di Yaroslav usando get_operations . Ecco un rapido esempio:

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
Non puoi far usare i tensori tf.get_operations(). L'unica operazione che puoi ottenere.
— Soulduck

14

Cercherò di riassumere le risposte:

Per ottenere tutti i nodi (tipo tensorflow.core.framework.node_def_pb2.NodeDef):

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

Per ottenere tutte le operazioni (digita tensorflow.python.framework.ops.Operation):

all_ops = tf.get_default_graph().get_operations()

Per ottenere tutte le variabili (tipo tensorflow.python.ops.resource_variable_ops.ResourceVariable):

all_vars = tf.global_variables()

Per ottenere tutti i tensori (digitare 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() può darti le informazioni che desideri.

Inoltre, questo commit fatto oggi in TensorFlow Learn che fornisce una funzione get_variable_namesnello stimatore che puoi usare per recuperare facilmente tutti i nomi delle variabili.


Questa funzione è obsoleta
— CAFEBABE

8
... e il suo successore ètf.global_variables()
— bluenote10

11
questo recupera solo variabili, non tensori.
— Rajarshee Mitra

In tensorflow 1.9.0 mostra cheall_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02
— stackoverYC

5

Penso che andrà bene anche questo:

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

Ma rispetto alle risposte di Salvado e Yaroslav, non so quale sia la migliore.


Questo ha funzionato con un grafico importato da un file frozen_inference_graph.pb utilizzato nell'API di rilevamento degli oggetti tensorflow. Grazie
— simo23

4

La risposta accettata fornisce solo un elenco di stringhe con i nomi. Preferisco un approccio diverso, che ti dà accesso (quasi) diretto ai tensori:

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

list_of_tuplesora contiene ogni tensore, ciascuno all'interno di una tupla. Puoi anche adattarlo per ottenere direttamente i tensori:

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

4

Poiché l'OP ha chiesto la lista dei tensori invece della lista delle operazioni / nodi, il codice dovrebbe essere leggermente diverso:

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

Le risposte precedenti sono buone, vorrei solo condividere una funzione di utilità che ho scritto per selezionare i tensori da un grafico:

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

Quindi, se hai un grafico con 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']

Poi in esecuzione

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

ritorna:

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

0

Questo ha funzionato per me:

for n in tf.get_default_graph().as_graph_def().node:
    print('\n',n)
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.