I have started learning tensorflow and have difficulties understanding the placeholders/variables issues.
I am trying to write a function for matrix multiplication. It works when using tf.constant but I have difficulties understanding how to use variables
here is my code
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
This works as expected:
my_matmult1(mat_1, mat_1)
However, the following fails:
my_matmult2(mat_1, mat_1)
with the following error
InvalidArgumentError
You must feed a value for placeholder tensor 'Placeholder' with dtype int32 and shape [4,4]
Even after changing the last line in
qq1 = x_sess1.run(r1, feed_dic={tf.convert_to_tensor(mat_1), tf.convert_to_tensor(mat_2)})
What am I doing wrong?