SparseTensor和SparseTensorValue之间有什么区别?如果我想根据提供的索引和值构建稀疏张量,有什么需要注意的吗?我只能找到一些简单的例子。
回答:
这取决于您在哪里定义您的稀疏张量。
如果您想在图外定义张量,例如为后续数据馈送定义稀疏张量,请使用SparseTensorValue。相反,如果稀疏张量在图中定义,请使用SparseTensor。
tf.SparseTensorValue的示例代码:
x_sp = tf.sparse_placeholder(dtype=tf.float32)W = tf.Variable(tf.random_normal([6, 6]))y = tf.sparse_tensor_dense_matmul(sp_a=x_sp, b=W)init = tf.global_variables_initializer()gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))sess.run(init)stv = tf.SparseTensorValue(indices=[[0, 0], [1, 2]], values=[1.1, 1.2], dense_shape=[2,6])result = sess.run(y,feed_dict={x_sp:stv})print(result)
tf.SparseTensor的示例代码:
indices_i = tf.placeholder(dtype=tf.int64, shape=[2, 2])values_i = tf.placeholder(dtype=tf.float32, shape=[2])dense_shape_i = tf.placeholder(dtype=tf.int64, shape=[2])st = tf.SparseTensor(indices=indices_i, values=values_i, dense_shape=dense_shape_i)W = tf.Variable(tf.random_normal([6, 6]))y = tf.sparse_tensor_dense_matmul(sp_a=st, b=W)init = tf.global_variables_initializer()gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))sess.run(init)result = sess.run(y,feed_dict={indices_i:[[0, 0], [1, 2]], values_i:[1.1, 1.2], dense_shape_i:[2,6]})print(result)
希望这对您有帮助~