2017-10-18 77 views
0

我在tensorflow中编写了一个定制的内核操作来读取csv格式的数据。为什么自定义读操作只能在test_session上运行

它在TestCase中正常工作,sess对象返回test_session()函数。

当我转到正常代码时,读取器每次都返回相同的结果。然后,我在MyOp:Compute函数的开头部分进行了一些调试打印。看起来在第一次运行后,sess.run(myop)根本不会调用MyOp:Compute函数。

然后我回到我的测试情况下,如果我更换一个tf.Session()代替self.test_session()会话对象,它没有以同样的方式。

任何人都有这个想法吗?

分享更多的细节,这是我小的演示代码: https://github.com/littleDing/mini_csv_reader

测试用例:

def testSimple(self): 
    input_data_schema, feas, batch_size = self.get_simple_format() 
    iter_op = ops.csv_iter('./sample_data.txt', input_data_schema, feas, batch_size=batch_size, label='label2') 
    with self.test_session() as sess: 
    label,sign = sess.run(iter_op) 
    print label 

    self.assertAllEqual(label.shape, [batch_size]) 
    self.assertAllEqual(sign.shape, [batch_size, len(feas)]) 
    self.assertAllEqual(sum(label), 2) 
    self.assertAllEqual(sign[0,:], [7,0,4,1,1,1,5,9,8]) 

    label,sign = sess.run(iter_op) 
    self.assertAllEqual(label.shape, [batch_size]) 
    self.assertAllEqual(sign.shape, [batch_size, len(feas)]) 
    self.assertAllEqual(sum(label), 1) 
    self.assertAllEqual(sign[0,:], [9,9,3,1,1,1,5,4,8]) 

正常的呼叫:

def testing_tf(): 
    path = './sample_data.txt' 
    input_data_schema, feas, batch_size = get_simple_format() 
    with tf.device('/cpu:0'): 
     n_data_op = tf.placeholder(dtype=tf.float32) 
     iter_op = ops.csv_iter(path, input_data_schema, feas, batch_size=batch_size, label='label2') 
     init_op = [tf.global_variables_initializer(), tf.local_variables_initializer() ] 

    with tf.Session() as sess: 
     sess.run(init_op) 
     n_data = 0 
     for batch_idx in range(3): 
     print '>>>>>>>>>>>>>> before run batch', batch_idx 
     ## it should be some debug printing here, but nothing come out when batch_idx>0 
     label,sign = sess.run(iter_op) 
     print '>>>>>>>>>>>>>> after run batch', batch_idx 
     ## the content of sign remain the same every time 
     print sign 
     if len(label) == 0: 
      break 
+1

你能分享特定的代码来理解更加清晰 –

+0

请尽量分担问题的最小工作示例。没有能够说明您的问题的代码,我们不可能提供帮助。 – Engineero

+0

@Engineero我已更新最低工作代码,您想要检查吗? –

回答

1

一看的implementationtf.test.TestCase.test_session()提供了一些线索,因为它配置会话的方式与直接调用的方式有所不同。特别是,test_session()disables不断折叠优化。默认情况下,TensorFlow会将图的无状态部分转换为tf.constant()节点,因为每次运行它们时都会产生相同的结果。

在你"CsvIter" OP的注册,对SetIsStateful()注释,所以TensorFlow会将其视为无国籍,因此受到恒定的折叠。然而,它的实现是非常有状态的:一般来说,任何你希望用相同的输入张量产生不同结果的操作,或者任何在成员变量中存储可变状态的操作符应该被标记为有状态。

的解决方案是一个修改一行到REGISTER_OP"CsvIter"

REGISTER_OP("CsvIter") 
    .Input("data_file: string") 
    .Output("labels: float32") 
    .Output("signs: int64") 
    .Attr("input_schema: list(string)") 
    .Attr("feas: list(string)") 
    .Attr("label: string = 'label' ") 
    .Attr("batch_size: int = 10000") 
    .SetIsStateful(); // Add this line. 
+0

解决问题,非常感谢! –

相关问题