问题
I'm trying to do a simple operation with tensorflow of matrix multiplication but I have to use a matrix of variable size of its columns (as it can be seen in the example below)
import tensorflow as tf
input1 = tf.placeholder("float", [None,None])
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
print(sess.run([output], feed_dict={input1:[[1,2],[3,4,5]], input2:[2.]}))
The thing is that once I do this, I receive an error message telling me:
ValueError: setting an array element with a sequence.
I know this can be easily solvable adding any number or None in the first row (to produce an m x n shape), however I want to train bigger data for an experiment and I'm not sure whether a 0 could affect data or not.
回答1:
The tf.placeholder()
op defines a placeholder for a dense tensor, so you must define all of the elements in the value that you are trying to feed.
An alternative (in the latest version of TensorFlow, available if you build from source or download a nightly release) is to use a tf.sparse_placeholder() op, which allows you to feed a tf.SparseTensor with a tf.SparseTensorValue. This allows you to represent an object in which not all elements are defined, but the ones that are undefined are interpreted as zeros.
Note that TensorFlow's support for sparse data and variable-sized examples is still preliminary, and most of the operations—like tf.mul()—are currently only defined for dense tensors. An alternative approach, which we use for variable-sized image data, is to process one (variable-sized) record at a time in an input pipeline, before converting it to a constant shape, and using the batching functions to make a single dense batch.
来源:https://stackoverflow.com/questions/37594350/tensorflow-introducing-a-matrix-of-different-size-in-a-placeholder