Skip to main content
 首页 » 编程设计

python之评估 TensorFlow 张量时执行卡住

2025年02月15日27dflying

所以我的代码是:

with tf.Session() as sess:     
    init.run() 
    epoch = 1 
    iteration = 1 
    print("Checkpoint 1") 
    X_batch, y_batch = tf.train.batch([X_train, y_train], batch_size=batch_size) 
    print("Checkpoint 2") 
    X = X_batch.eval() 
    y = X_batch.eval() 
    print("Checkpoint 3") 

问题是当执行最后两行时,执行卡住了,没有给出任何输出(只打印检查点 1 和 2)。我在谷歌上搜索过,从 tensorflow.python.framework.ops.Tensor 到 numpy.ndarray 的转换似乎是一个微不足道的操作。

我还尝试了以下方法以防有所不同:

X = X_batch.eval(session = sess) 
y = X_batch.eval(session = sess) 

编辑:我尝试使用交互式 session ,但问题仍然存在

`sess = tf.InteractiveSession() 
 X_batch, y_batch = tf.train.batch([X_train, y_train], batch_size=batch_size) 
type(X_batch) 
type(y_batch) 
print(type(X_batch.eval())) 
sess.close()` 

请您参考如下方法:

您需要启动隐藏在 tf.train.batch 中的 queue runner,例如使用 tf.train.Coordinator(有查看 this 或 this 以获得更多信息)。根据方法的文档字符串(我的重点):

This function is implemented using a queue. A QueueRunner for the queue is added to the current Graph's QUEUE_RUNNER collection.

和

The returned operation is a dequeue operation and will throw tf.errors.OutOfRangeError if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself.

由于您没有启动队列运行器,线程会卡住等待运行入队操作。

    X_batch, y_batch = tf.train.batch([X_train, y_train], batch_size=batch_size) 
    with tf.Session() as sess: 
        sess.run(init) 
        coord = tf.train.Coordinator() 
        threads = tf.train.start_queue_runners(coord=coord) 
        try: 
            while not coord.should_stop(): 
                X, y = sess.run([X_batch, y_batch]) 
        except Exception as e: 
            coord.request_stop(e) 
        finally: 
            coord.request_stop() 
            coord.join(threads)