В Tensorflow получите имена всех тензоров в графе
Я создаю нейронные сети с Tensorflow
и skflow
; по какой-то причине я хочу получить значения некоторых внутренних тензоров для данного ввода, поэтому я использую myClassifier.get_layer_value(input, "tensorName")
, myClassifier
как skflow.estimators.TensorFlowEstimator
.
Однако мне трудно найти правильный синтаксис имени тензора, даже зная его имя (и меня путают между операцией и тензорами), поэтому я использую тензограмму для построения графика и поиска имя.
Есть ли способ перечислить все тензоры на графике без использования тензорной карты?
Ответы
Ответ 1
Вы можете сделать
[n.name for n in tf.get_default_graph().as_graph_def().node]
Кроме того, если вы прототипируете в ноутбуке IPython, вы можете показать график непосредственно в записной книжке, см. функцию show_graph
в Alexander Deep Dream записная книжка
Ответ 2
Есть способ сделать это немного быстрее, чем в ответе Ярослава, используя 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))
Ответ 3
tf.all_variables()
может получить необходимую информацию.
Кроме того, этот коммит, сделанный сегодня в TensorFlow Learn, предоставляет функцию оценки get_variable_names
в get_variable_names
которую вы можете использовать для простого извлечения всех имен переменных.
Ответ 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()]
Ответ 5
Я думаю, что это тоже будет делать:
print(tf.contrib.graph_editor.get_tensors(tf.get_default_graph()))
Но по сравнению с ответами Сальвадо и Ярослава я не знаю, какой из них лучше.
Ответ 6
Предыдущие ответы хороши, я просто хотел бы поделиться функцией полезности, которую я написал, чтобы выбрать Тензор из графика:
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']
Ответ 7
Это сработало для меня:
for n in tf.get_default_graph().as_graph_def().node:
print('\n',n)
Ответ 8
Поскольку 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]