2016-06-12 3 views
5

그래프가 텐서 흐름에서 작동하는 방법과 액세스하는 방법을 이해하는 데 어려움을 겪고 있습니다. 내 직관은 '그래프 사용 :'아래의 줄이 단일 엔티티로 그래프를 형성한다는 것입니다. 따라서 인스턴스화 될 때 그래프를 작성하고 다음과 같이 그래프를 실행할 함수를 소유하는 클래스를 작성하기로했습니다.Tensorflow : 클래스에서 그래프 만들기 및 실행 중

class Graph(object): 

    #To build the graph when instantiated 
    def __init__(self, parameters): 
     self.graph = tf.Graph() 
     with self.graph.as_default(): 
      ... 
      prediction = ... 
      cost  = ... 
      optimizer = ... 
      ... 
    # To launch the graph 
    def launchG(self, inputs): 
     with tf.Session(graph=self.graph) as sess: 
      ... 
      sess.run(optimizer, feed_dict) 
      loss = sess.run(cost, feed_dict) 
      ... 
     return variables 

다음 단계를 실행 한 후 그래프를 생성하는 클래스에 전달할 매개 변수를 조립하는 주요 파일을 만들 수 있습니다;

#Main file 
... 
parameters_dict = { 'n_input': 28, 'learnRate': 0.001, ... } 

#Building graph 
G = Graph(parameters_dict) 
P = G.launchG(Input) 
... 

이것은 나에게 매우 우아하지만 아주 (분명히) 작동하지 않습니다. 실제로, launchG 함수는 그래프에 정의 된 노드에 액세스 할 수 없어서 다음과 같은 오류가 발생합니다.

---> 26 sess.run(optimizer, feed_dict) 

NameError: name 'optimizer' is not defined 

아마도 너무 제한되어 내 파이썬 (그리고 tensorflow) 이해하지만, 내가 만든 그래프 (G)와,이 그래프와 세션을 실행하는 인수가 액세스 권한을 부여해야으로하는 이상 인상했다 그 노드에 명시 적으로 액세스하지 않아도됩니다.

어떤 깨우침?

답변

7

노드 prediction, costoptimizer이 방법 __init__에서 만든 로컬 변수, 그들은이 방법 launchG에 액세스 할 수 없습니다.

가장 쉬운 수정 클래스 Graph의 속성로 선언하는 것입니다 :

class Graph(object): 

    #To build the graph when instantiated 
    def __init__(self, parameters): 
     self.graph = tf.Graph() 
     with self.graph.as_default(): 
      ... 
      self.prediction = ... 
      self.cost  = ... 
      self.optimizer = ... 
      ... 
    # To launch the graph 
    def launchG(self, inputs): 
     with tf.Session(graph=self.graph) as sess: 
      ... 
      sess.run(self.optimizer, feed_dict) 
      loss = sess.run(self.cost, feed_dict) 
      ... 
     return variables 

당신은 또한 graph.get_tensor_by_namegraph.get_operation_by_name 자신의 정확한 이름을 사용하여 그래프의 노드를 검색 할 수 있습니다.

관련 문제