我已经开始学习 tensorflow,但很难理解占位符/变量问题。
我正在尝试编写一个矩阵乘法函数。它在使用 tf.constant 时有效,但我很难理解如何使用变量
这是我的代码
import tensorflow as tf
import numpy as np
mat_1 = np.array([[0,1,1,0], [1,0,1,0], [1,0,0,1], [0,1,1,0]]).astype('int32')
mat_2 = np.array([[0,1,1,0], [1,0,1,0], [1,0,0,1], [0,1,1,0]]).astype('int32')
def my_matmult1(mat_1, mat_2):
#define session
x_sess = tf.Session()
with x_sess:
xmat_1 = tf.constant(mat_1)
xmat_2 = tf.constant(mat_2)
r1 = tf.matmul(xmat_1, xmat_2)
qq1 = x_sess.run(r1)
return qq1
def my_matmult2(mat_1, mat_2):
#define session
x_sess1 = tf.Session()
with x_sess1:
#initialize placeholders
xmat_1_plh = tf.placeholder(dtype=mat_1.dtype, shape=mat_1.shape)
xmat_2_plh = tf.placeholder(dtype=mat_2.dtype, shape=mat_2.shape)
#create variables
x_mat_1 = tf.Variable(xmat_1_plh, trainable = False)
x_mat_2 = tf.Variable(xmat_2_plh, trainable = False)
x_sess1.run(tf.initialize_all_variables())
#
r1 = tf.matmul(xmat_1, xmat_2)
qq1 = x_sess1.run(r1, feed_dic={mat_1, mat_2})
return qq1
这按预期工作:
my_matmult1(mat_1, mat_1)
但是,以下失败:
my_matmult2(mat_1, mat_1)
出现以下错误
InvalidArgumentError
You must feed a value for placeholder tensor 'Placeholder' with dtype int32 and shape [4,4]
即使更改了最后一行
qq1 = x_sess1.run(r1, feed_dic={tf.convert_to_tensor(mat_1), tf.convert_to_tensor(mat_2)})
我做错了什么?
最佳答案
如果您在创建占位符后删除 tf.Variable()
行(并相应地修改馈送变量的名称),您的代码应该可以工作。
占位符用于您要为模型提供数据的变量。变量用于模型的参数(如权重)。
因此,您正确地创建了两个占位符,但随后无缘无故地创建了其他变量,这可能会在 Tensorflow 图表中造成困惑。
函数如下所示:
import tensorflow as tf
import numpy as np
def my_matmult2(mat_1, mat_2):
#define session
x_sess1=tf.Session()
with x_sess1:
#initialize placeholders
xmat_1_plh = tf.placeholder(dtype=mat_1.dtype, shape=mat_1.shape)
xmat_2_plh = tf.placeholder(dtype=mat_2.dtype, shape=mat_2.shape)
r1 = tf.matmul(xmat_1_plh, xmat_2_plh)
x_sess1.run(tf.initialize_all_variables())
#
qq1 = x_sess1.run(r1, feed_dict={xmat_1_plh: mat_1 , xmat_2_plh: mat_2})
return qq1
mat_1=np.ones((5,5))
mat_2=np.ones((5,5))
b=my_matmult2(mat_1,mat_2)
print b
关于tensorflow - 无效参数错误 : You must feed a value for placeholder tensor Placeholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296200/