메모리를 이유로 비용 함수를 계산할 때 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 작업을 사용하는 경우
- 를 호출, 내가 어떤 문제를하지 않는 것이
참고.
그러나 전역 변수로 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.
불변하지/혼란 스러울 것 같다 . 대신에 x = tf.add (...); x.set_shape (...); 당신의 몸에 index + 1, x를 반환하면 제대로 작동합니다. –
@AlexandrePassos 감사합니다. 제가 이것을했을 때 작동합니다. 그러나 여전히 N을 글로벌로 설정해야합니다. 아래 답변에 업데이트 된 코드가 있습니다. – Bruce