2017-12-05 1 views
0

메모리를 이유로 비용 함수를 계산할 때 while 루프를 사용하고 있습니다. 그라디언트를 계산할 때, tensorflow는 Nm tensors를 저장합니다. Nm은 while 루프의 반복 횟수입니다 (이것은 원래의 에너지 함수와 동일한 메모리 문제입니다). 나는 충분한 기억이 없기 때문에 나는 그것을 원하지 않는다. 그래서 while 루프를 사용하는 그래디언트 함수와 함께 새로운 연산을 등록하려고합니다.. 그러나 function.defun 및 while 루프 사용하여 문제가 있습니다.Tensorflow : function.defun에서 a while 루프를 사용하면 모양 오류가 발생합니다.

import numpy as np 
import tensorflow as tf 
from tensorflow.python.framework import ops 
from tensorflow.python.ops import array_ops 
from tensorflow.python.ops import sparse_ops 
from tensorflow.python.framework import function 


def _run(tensor): 
    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 
     res = sess.run(tensor) 
    return res 


@function.Defun(tf.float32,tf.float32,func_name ='tf_test_log')#,grad_func=tf_test_logGrad) 
def tf_test_log(t_x,t_y): 
    #N = t_x.shape[0].value 
    condition = lambda i,m1: i<N 

    def body(index,x): 
     #return[(index+1),tf.concat([x, tf.expand_dims(tf.exp(tf.add(t_x[:,index],t_y[:,index])),1) ],1) ] 
     return[(index+1),tf.add(x, tf.exp(tf.add(t_x[:,0],t_y[:,0])) ) ] 

    i0  = tf.constant(0,dtype=tf.int32) 
    m0  = tf.zeros([N,1],dType) 


    ijk_0 = [i0,m0] 

    L,t_log_x = tf.while_loop(condition,body,ijk_0, 
        shape_invariants=[i0.get_shape(), 
             tf.TensorShape([N,None])] 
             ) 
    return t_log_x 



dType = tf.float32 
N  = np.int32(100) 

t_N = tf.constant(N,dtype = tf.int32) 
t_x = tf.constant(np.random.randn(N,N),dtype = dType) 
t_y = tf.constant(np.random.randn(N,N),dtype = dType) 
ys = _run(tf_test_log(t_x,t_y)) 

그때 새로운 연산 테스트하려고 : 나는 값 오류가

: 잠시 동안 모양을/Merge_1 : 일을 단순화하기 위해, 나는 아래의 작은 테스트 예제가 0 루프의 불변량이 아닙니다. 모양 (100,?)으로 루프에 들어가지만 한 번의 반복 후에 모양을 갖습니다. tf.while_loop의 인수 shape_invariants 또는 루프 변수의 set_shape()를 사용하여 모양 불변성을 제공하십시오. 내가 (대신 내 while 루프에 의해 반환됩니다 추가 작업의)는 CONCATENATE 작업을 사용하는 경우

  1. 를 호출, 내가 어떤 문제를하지 않는 것이

    참고.

  2. 그러나 전역 변수로 N을 설정하지 않으면 (즉, N = t_x.shape [0]) tf_test_log 함수의 본문에 N을 설정하면 값 오류가 발생합니다.

    ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 1)

내 코드에 어떤 문제가 있습니까? 도움을 주시면 대단히 감사하겠습니다! 우분투 16.04에

내가 파이썬 3.5를 사용하고

및 tensorflow 1.4

최대 출력 : 위의 주석의 제안에 대한

ValueError        Traceback (most recent call last) 
~/Documents/TheEffingPhDHatersGonnaHate/PAM/defun_while.py in <module>() 
    51 t_x = tf.constant(np.random.randn(N,N),dtype = dType) 
    52 t_y = tf.constant(np.random.randn(N,N),dtype = dType) 
---> 53 ys = _run(tf_test_log(t_x,t_y)) 
    54 
    55 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in __call__(self, *args, **kwargs) 
    503 
    504 def __call__(self, *args, **kwargs): 
--> 505  self.add_to_graph(ops.get_default_graph()) 
    506  args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs 
    507  ret, op = _call(self._signature, *args, **kwargs) 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in add_to_graph(self, g) 
    484 def add_to_graph(self, g): 
    485  """Adds this function into the graph g.""" 
--> 486  self._create_definition_if_needed() 
    487 
    488  # Adds this function into 'g'. 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in _create_definition_if_needed(self) 
    319  """Creates the function definition if it's not created yet.""" 
    320  with context.graph_mode(): 
--> 321  self._create_definition_if_needed_impl() 
    322 
    323 def _create_definition_if_needed_impl(self): 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in _create_definition_if_needed_impl(self) 
    336  # Call func and gather the output tensors. 
    337  with vs.variable_scope("", custom_getter=temp_graph.getvar): 
--> 338   outputs = self._func(*inputs) 
    339 
    340  # There is no way of distinguishing between a function not returning 

~/Documents/TheEffingPhDHatersGonnaHate/PAM/defun_while.py in tf_test_log(t_x, t_y) 
    39  L,t_log_x = tf.while_loop(condition,body,ijk_0, 
    40       shape_invariants=[i0.get_shape(), 
---> 41           tf.TensorShape([N,None])] 
    42           ) 
    43  return t_log_x 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py in while_loop(cond, body, loop_vars, shape_invariants, parallel_iterations, back_prop, swap_memory, name) 
    2814  loop_context = WhileContext(parallel_iterations, back_prop, swap_memory) # pylint: disable=redefined-outer-name 
    2815  ops.add_to_collection(ops.GraphKeys.WHILE_CONTEXT, loop_context) 
-> 2816  result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants) 
    2817  return result 
    2818 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py in BuildLoop(self, pred, body, loop_vars, shape_invariants) 
    2638  self.Enter() 
    2639  original_body_result, exit_vars = self._BuildLoop(
-> 2640   pred, body, original_loop_vars, loop_vars, shape_invariants) 
    2641  finally: 
    2642  self.Exit() 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py in _BuildLoop(self, pred, body, original_loop_vars, loop_vars, shape_invariants) 
    2619  for m_var, n_var in zip(merge_vars, next_vars): 
    2620  if isinstance(m_var, ops.Tensor): 
-> 2621   _EnforceShapeInvariant(m_var, n_var) 
    2622 
    2623  # Exit the loop. 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py in _EnforceShapeInvariant(merge_var, next_var) 
    576   "Provide shape invariants using either the `shape_invariants` " 
    577   "argument of tf.while_loop or set_shape() on the loop variables." 
--> 578   % (merge_var.name, m_shape, n_shape)) 
    579 else: 
    580  if not isinstance(var, (ops.IndexedSlices, sparse_tensor.SparseTensor)): 

ValueError: The shape for while/Merge_1:0 is not an invariant for the loop. It enters the loop with shape (100, ?), but has shape <unknown> after one iteration. Provide shape invariants using either the `shape_invariants` argument of tf.while_loop or set_shape() on the loop variables. 
+0

불변하지/혼란 스러울 것 같다 . 대신에 x = tf.add (...); x.set_shape (...); 당신의 몸에 index + 1, x를 반환하면 제대로 작동합니다. –

+0

@AlexandrePassos 감사합니다. 제가 이것을했을 때 작동합니다. 그러나 여전히 N을 글로벌로 설정해야합니다. 아래 답변에 업데이트 된 코드가 있습니다. – Bruce

답변

0

감사 @Alexandre 파 소스! 다음 코드는 본문 내부에 set_shape 함수가 추가 된 원본을 수정 한 것입니다.

import numpy as np 
import tensorflow as tf 
from tensorflow.python.framework import ops 
from tensorflow.python.ops import array_ops 
from tensorflow.python.ops import sparse_ops 
from tensorflow.python.framework import function 

def _run(tensor): 
    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 
     res = sess.run(tensor) 
    return res 


@function.Defun(tf.float32,tf.float32,tf.float32,func_name ='tf_test_logGrad') 
def tf_test_logGrad(t_x,t_y,grad): 
    return grad 



@function.Defun(tf.float32,tf.float32,func_name  ='tf_test_log')#,grad_func=tf_test_logGrad) 
def tf_test_log(t_x,t_y): 
    #N = t_x.shape[0].value 
    condition = lambda i,m1: i<N 

    def body(index,x): 
     #return[(index+1),tf.concat([x, tf.expand_dims(tf.exp(tf.add( t_x[:,index],t_y[:,index])),1) ],1) ] 
     x = tf.add(x, tf.exp(tf.add(t_x[:,0],t_y[:,0])) ) 
     x.set_shape([N]) 
     return[(index+1), x] 

    i0  = tf.constant(0,dtype=tf.int32) 
    m0  = tf.zeros([N],dType) 


    ijk_0 = [i0,m0] 

    L,t_log_x = tf.while_loop(condition,body,ijk_0, 
        shape_invariants=[i0.get_shape(), 
             tf.TensorShape([N])] 
             ) 
    return t_log_x 



dType = tf.float32 
N  = np.int32(100) 

t_N = tf.constant(N,dtype = tf.int32) 
t_x = tf.constant(np.random.randn(N,N),dtype = dType) 
t_y = tf.constant(np.random.randn(N,N),dtype = dType) 
ys = _run(tf_test_log(t_x,t_y)) 

글로벌 N의 발행은 계속됩니다.

defoon 데코레이터의 외부 변수 외부에 루프 텐서의 모양을 설정해야합니다.. 당신이 defun는 데코레이터의 입력의 모양에서 그것을 얻을하려고하면 얻을 :

TypeError         Traceback (most recent call last) 
~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py in zeros(shape, dtype, name) 
    1438  shape = tensor_shape.as_shape(shape) 
-> 1439  output = constant(zero, shape=shape, dtype=dtype, name=name) 
    1440  except (TypeError, ValueError): 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name, verify_shape) 
    207  tensor_util.make_tensor_proto(
--> 208   value, dtype=dtype, shape=shape, verify_shape=verify_shape)) 
    209 dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape) 
    379  # exception when dtype is set to np.int64 
--> 380  if shape is not None and np.prod(shape, dtype=np.int64) == 0: 
    381  nparray = np.empty(shape, dtype=np_dt) 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/numpy/core/fromnumeric.py in prod(a, axis, dtype, out, keepdims) 
    2517  return _methods._prod(a, axis=axis, dtype=dtype, 
-> 2518       out=out, **kwargs) 
    2519 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/numpy/core/_methods.py in _prod(a, axis, dtype, out, keepdims) 
    34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False): 
---> 35  return umr_prod(a, axis, dtype, out, keepdims) 
    36 

TypeError: __int__ returned non-int (type NoneType) 

During handling of the above exception, another exception occurred: 

ValueError        Traceback (most recent call last) 
~/Documents/TheEffingPhDHatersGonnaHate/PAM/defun_while.py in <module>() 
    52 t_x = tf.constant(np.random.randn(N,N),dtype = dType) 
    53 t_y = tf.constant(np.random.randn(N,N),dtype = dType) 
---> 54 ys = _run(tf_test_log(t_x,t_y)) 
    55 
    56 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in __call__(self, *args, **kwargs) 
    503 
    504 def __call__(self, *args, **kwargs): 
--> 505  self.add_to_graph(ops.get_default_graph()) 
    506  args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs 
    507  ret, op = _call(self._signature, *args, **kwargs) 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in add_to_graph(self, g) 
    484 def add_to_graph(self, g): 
    485  """Adds this function into the graph g.""" 
--> 486  self._create_definition_if_needed() 
    487 
    488  # Adds this function into 'g'. 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in _create_definition_if_needed(self) 
    319  """Creates the function definition if it's not created yet.""" 
    320  with context.graph_mode(): 
--> 321  self._create_definition_if_needed_impl() 
    322 
    323 def _create_definition_if_needed_impl(self): 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/function.py in _create_definition_if_needed_impl(self) 
    336  # Call func and gather the output tensors. 
    337  with vs.variable_scope("", custom_getter=temp_graph.getvar): 
--> 338   outputs = self._func(*inputs) 
    339 
    340  # There is no way of distinguishing between a function not returning 

~/Documents/TheEffingPhDHatersGonnaHate/PAM/defun_while.py in tf_test_log(t_x, t_y) 
    33 
    34  i0  = tf.constant(0,dtype=tf.int32) 
---> 35  m0  = tf.zeros([N],dType) 
    36 
    37 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py in zeros(shape, dtype, name) 
    1439  output = constant(zero, shape=shape, dtype=dtype, name=name) 
    1440  except (TypeError, ValueError): 
-> 1441  shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape") 
    1442  output = fill(shape, constant(zero, dtype=dtype), name=name) 
    1443 assert output.dtype.base_dtype == dtype 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in convert_to_tensor(value, dtype, name, preferred_dtype) 
    834  name=name, 
    835  preferred_dtype=preferred_dtype, 
--> 836  as_ref=False) 
    837 
    838 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx) 
    924 
    925  if ret is None: 
--> 926  ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) 
    927 
    928  if ret is NotImplemented: 

~/environments/tf_1_4_gpu/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py in _tensor_shape_tensor_conversion_function(s, dtype, name, as_ref) 
    248 if not s.is_fully_defined(): 
    249  raise ValueError(
--> 250   "Cannot convert a partially known TensorShape to a Tensor: %s" % s) 
    251 s_list = s.as_list() 
    252 int64_value = 0 

ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,) 
tf.add (...) 텐서의 모양이 몸에서 반환
+0

예, 함수 정의 자체는 입력 모양에 의존하지 않으므로 defun 데코레이터는 입력 모양을 지 웁니다.함수의 외부에서 정의 된 전역 정수 (텐서가 아닌)로 N을 가짐으로써 N = tf.shape (x) [0] –

관련 문제