TensorFlow SparseTensor 动态设置dense_shape [英] TensorFlow SparseTensor with dynamically set dense_shape

查看:41
本文介绍了TensorFlow SparseTensor 动态设置dense_shape的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前问过这个问题在 TensorFlow 上创建布尔掩码关于如何获得一个张量,只将某些索引设置为 1,其余的都设置为 0.

I have previously asked this question Create boolean mask on TensorFlow about how to get a tensor only with certain indices set to 1, and the rest of them to 0.

我认为@MZHm 给出的答案将完全解决我的问题.虽然,tf.SparseTensor 的参数 dense_shape 只接受列表,但我想传递一个从图中推断出的形状(来自另一个具有变量的张量的形状)形状).所以在我的具体情况下,我想做这样的事情:

I thought the answer given by @MZHm would entirely solve my problem. Although, the argument dense_shape of tf.SparseTensor only accepts lists, and I want to pass a shape which is inferred from the graph (from the shape of another tensor which has variable shape). So in my case in specific, I want to do something like this:

# The tensor from which the shape of the sparse tensor is to be inferred
reference_t = tf.zeros([32, 50, 11])

# The indices that will be 1
indices = [[0, 0],
           [3, 0],
           [5, 0],
           [6, 0]]

# Just setting all the values for the sparse tensor to be 1
values = tf.ones([reference_t.shape[-1]])

# The 2d shape I want the sparse tensor to have
sparse_2d_shape = [reference_t.shape[-2],
                   reference_t.shape[-1]]

st = tf.SparseTensor(indices, values, sparse_2d_shape)

由此我得到错误:

TypeError: 应为 int64,得到Dimension"类型的 Dimension(50)相反.

TypeError: Expected int64, got Dimension(50) of type 'Dimension' instead.

如何动态设置稀疏张量的形状?是否有更好的替代方案来实现我的目标?

How to I dynamically set the shape of a sparse tensor? Is there a better alternative to achieve what I'm aiming to do?

推荐答案

您可以通过以下方式获得动态形状:

Here is what you can do to have a dynamic shape:

import tensorflow as tf 
import numpy as np

indices = tf.constant([[0, 0],[1, 1]], dtype=tf.int64)
values = tf.constant([1, 1])
dynamic_input = tf.placeholder(tf.float32, shape=[None, None])
s = tf.shape(dynamic_input, out_type=tf.int64)

st = tf.SparseTensor(indices, values, s)
st_ordered = tf.sparse_reorder(st)
result = tf.sparse_tensor_to_dense(st_ordered)

sess = tf.Session()

具有(动态)形状的输入[5, 3]:

An input with (dynamic) shape [5, 3]:

sess.run(result, feed_dict={dynamic_input: np.zeros([5, 3])})

将输出:

array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]], dtype=int32)

具有(动态)形状的输入[3, 3]:

An input with (dynamic) shape [3, 3]:

sess.run(result, feed_dict={dynamic_input: np.zeros([3, 3])})

将输出:

array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 0]], dtype=int32)

所以你去...动态稀疏形状.

So there you go... dynamic sparse shape.

这篇关于TensorFlow SparseTensor 动态设置dense_shape的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆