问题描述
我正在尝试一个简单的 Tensorflow 代码来多次计算两个矩阵的乘积.我的代码如下:
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
在 for 循环中运行 session.run() 时:
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
我收到以下错误:
我在 Tensorflow 网站上查看了 MNIST 的示例代码,但它们在 for 循环中以类似的方式运行session.run()".我正在寻找有关为什么我的代码中的session.run()"在 for 循环中不起作用的任何见解.
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.
谢谢.
推荐答案
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})
您可以直接输入 numpy
数组,Session.run(D, ...)
返回 D's
评估.
You can feed numpy
array directly and Session.run(D, ...)
returns D's
evaluation.
这篇关于Tensorflow 在循环中多次运行会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!