Tensorflow running session multiple times in a loop

那年仲夏 提交于 2021-02-18 17:50:26

问题


I'm trying out a simple Tensorflow code to compute the product of two matrices multiple times. My code is as follows:

import numpy as np
import tensorflow as tf

times = 10
alpha = 2
beta = 3

graph = tf.Graph()

with graph.as_default():
    A = tf.placeholder(tf.float32)
    B = tf.placeholder(tf.float32)
    C = tf.placeholder(tf.float32)
    alpha = tf.constant(2.0, shape=[1, 1])
    beta = tf.constant(3.0, shape=[1, 1])
    D = alpha*tf.matmul(A, B) + beta*C          

with tf.Session(graph=graph) as session:
    tf.initialize_all_variables().run()
    for time in xrange(1, 2):
        N = 10**time
        a = tf.constant(np.random.random((N, N)))
        b = tf.constant(np.random.random((N, N)))
        c = tf.constant(np.random.random((N, N)))

        for num in xrange(1, 3):
            print num
            session.run(D, feed_dict={A:a.eval(), B:b.eval(), C:c.eval()})      
            c = D

Upon running session.run() in the for loop:

for num in xrange(1, 3):
    print num
    session.run(D, feed_dict={A:a.eval(), B:b.eval(), C:c.eval()})      
    c = D

I get the following error:

I looked at the sample code for MNIST on the Tensorflow website but they run 'session.run()' in a similar manner in a for loop. I'm looking for any insight on why 'session.run()' in my code does not work inside a for loop.

Thank you.


回答1:


with tf.Session(graph=graph) as session:
    tf.initialize_all_variables().run()
    for time in xrange(1, 2):
        N = 10**time
        a = np.random.random((N, N))
        b = np.random.random((N, N))
        c = np.random.random((N, N))

        for num in xrange(1, 3):
            print num
            c = session.run(D, feed_dict={A:a, B:b, C:c})

You can feed numpy array directly and Session.run(D, ...) returns D's evaluation.



来源:https://stackoverflow.com/questions/48767184/tensorflow-running-session-multiple-times-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!