So suppose I have a tensor
X = tf.placeholder("float", [None, 5])
So that I know the number of columns but not the number of rows. I need to initialize a vector of ones of dimension nrows x 1
Now the following block of code does not work,
o = tf.ones(shape=(tf.shape(X)[0], 1))
==> TypeError: List of Tensors when single Tensor expected
Nor does,
o = tf.ones(shape=(X.get_shape()[0].value, 1))
==> TypeError: Input 'dims' of 'Fill' Op has type
string that does not match expected type of int32.
Now, I have found that one way to get around this is to actually make my vector of ones a placeholder,
o = tf.placeholder(dtype=tf.float32, shape=[None, 1])
And to pass in a numpy array of ones of appropriate size in my feed_dict
. But this solution strikes me as inelegant and not the intended use of a placeholder. I could be wrong here, but surely there's a better way.
To initialize a new variable from the value of another variable use the other variable's initialized_value() property. You can use the initialized value directly as the initial value for the new variable, or you can use it as any other tensor to compute a value for the new variable.
First, remember that you can use the TensorFlow eye functionality to easily create a square identity matrix. We create a 5x5 identity matrix with a data type of float32 and assign it to the Python variable identity matrix. So we used tf. eye, give it a size of 5, and the data type is float32.
EagreTensor represents a tensor who's value has been calculated in eager mode whereas Tensor represents a tensor node in a graph that may not yet have been calculated.
The way to solve your problem is to use tf.pack operation:
o = tf.ones(shape=tf.pack([tf.shape(X)[0], 1]))
The reason you had errors is that TensorFlow shape is expected to be a list of integers or a tensor link. tf.pack makes it easy to convert a list of integers and/or TensorFlow scalars into a Tensor object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With