为什么我的稀疏张量不能转换为张量?

时间:2018-11-06 14:36:20

标签: python tensorflow tensor

我想将稀疏数据分批馈送到Tensorflow,所以我使用以下代码:

with graph.as_default():
    global_step = tf.Variable(0, trainable=False)
    # Here we use the indices and values to reproduce the input SparseTensor
    sp_indice = tf.placeholder(tf.int64)
    sp_value = tf.placeholder(tf.float32)
    x =  tf.SparseTensor(sp_indice, sp_value, [batch_size, feature_num])
    y_ = tf.placeholder(tf.float32, [None, 1])
    keep_prob = tf.placeholder("float32")
    W = tf.Variable(tf.zeros([feature_num, 1]))
    b = tf.Variable(tf.zeros([1]))

    # Construct model
    pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
    # Minimize error using cross entropy
    cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))

但是我得到一个错误:

TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. Contents: SparseTensor(indices=Tensor("Placeholder:0", dtype=int64), values=Tensor("Placeholder_1:0", dtype=float32), dense_shape=Tensor("SparseTensor/dense_shape:0", shape=(2,), dtype=int64)). Consider casting elements to a supported type.

我对此错误感到困惑,似乎我的sp_indice = tf.placeholder(tf.int64)是错的,可能是因为我没有给shape。但是我不能确定形状,因为每个批次的形状都不同。如何将索引数组和值数组传递给张量?

1 个答案:

答案 0 :(得分:1)

在执行稀疏张量的矩阵乘法时,需要使用tf.sparse_tensor_dense_matmul

pred = tf.nn.softmax(tf.sparse_tensor_dense_matmul(x, W) + b)
相关问题