programing

Tensorflow에서 그래프의 모든 Tensor의 이름을 가져옵니다.

minimums 2023. 10. 30. 20:52
반응형

Tensorflow에서 그래프의 모든 Tensor의 이름을 가져옵니다.

저는 신경망을 만들고 있습니다.Tensorflow그리고.skflow; 어떤 이유에서인지 나는 주어진 입력에 대해 몇몇 내부 텐서들의 값을 얻고 싶어서 나는 다음을 사용하고 있습니다.myClassifier.get_layer_value(input, "tensorName"),myClassifier가 되는 것skflow.estimators.TensorFlowEstimator.

그러나 텐서 이름을 알고도 텐서 이름의 정확한 구문을 찾기가 어려워(그리고 연산과 텐서를 혼동하고 있습니다) 텐서보드를 사용하여 그래프를 그리고 이름을 찾고 있습니다.

텐서보드를 사용하지 않고 그래프의 텐서를 모두 열거할 수 있는 방법이 있습니까?

할수있습니다

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

또한 IPython 노트북에서 프로토타이핑을 하는 경우 노트북에서 직접 그래프를 표시할 수 있습니다.show_graphAlexander의 Deep Dream 노트북에 있는 기능

답변을 요약해 보겠습니다.

그래프의 모든 노드가져오려면: (입력)tensorflow.core.framework.node_def_pb2.NodeDef)

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

그래프에서 모든 ops가져오려면: (입력)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()

그래프의 모든 텐서얻으려면: (type)tensorflow.python.framework.ops.Tensor)

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

그래프의 모든 자리 표시자를 가져오려면: (입력)tensorflow.python.framework.ops.Tensor)

all_placeholders = [placeholder for op in tf.get_default_graph().get_operations() if op.type=='Placeholder' for placeholder in op.values()]

텐서플로 2

대신 텐서플로우 2에서 그래프를 얻으려면tf.get_default_graph()당신은 a를 인스턴스화할 필요가 있습니다.tf.function먼저 접속하고,graph속성: 예:

graph = func.get_concrete_function().graph

어디에functf.function

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

tf.all_variables()원하는 정보를 얻을 수 있습니다.

또한 이 커밋은 오늘 텐서플로우 학습에서 함수를 제공합니다.get_variable_names모든 변수 이름을 쉽게 검색하는 데 사용할 수 있는 in estimator.

이것으로도 충분할 것 같습니다.

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

하지만 살바도와 야로슬라프의 대답과 비교하면 어느 쪽이 더 나은지 모르겠습니다.

승인된 답변은 이름이 포함된 문자열 목록만 제공합니다.텐서에 직접적으로 접근할 수 있는 다른 접근 방식을 선호합니다.

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

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]

이전 답변은 좋습니다. 그래프에서 텐서를 선택하기 위해 작성한 유틸리티 기능을 공유하고자 합니다.

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

TensorFlow 2.3에서는 다음과 같은 솔루션을 사용할 수 있습니다.

def load_pb(path_to_pb):
    with tf.io.gfile.GFile(path_to_pb, 'rb') as f:
        graph_def = tf.compat.v1.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name='')
        return graph
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())

어디에MODEL_FILE는 동결 그래프의 경로입니다.

여기서 찍었습니다.

효과가 있었습니다.

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

언급URL : https://stackoverflow.com/questions/36883949/in-tensorflow-get-the-names-of-all-the-tensors-in-a-graph

반응형