SparseTensor和SparseTensorValue之间的差异

rne*_*nho 5 machine-learning tensorflow

SparseTensor和SparseTensorValue有什么区别?如果我想基于馈入的索引和值来构建稀疏张量,我应该牢记什么吗?我只能找到一些玩具示例。

小智 2

这取决于您定义稀疏张量的位置。

如果您想在图外定义张量,例如为以后的数据馈送定义稀疏张量,请使用 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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

希望这有帮助~