Skip to content

Feed sparse array for placeholder ? #342

Closed

Description

@chenghuige

X = tf.placeholder("float", [None, num_features]) # create symbolic variables
Y = tf.placeholder("float", [None, 1])

predicts = sess.run(predict_op, feed_dict={X: teX, Y: teY})

What if I'am facing text classification problem, where every instance is extremely sparse,
like using scipy.sparse.csr_matrix or somethint else, what's the best to do this ?

Activity

  1. changed the title [-]Feed sparse array for place holder ?[/-] [+]Feed sparse array for placeholder ?[/+] on Nov 24, 2015
  2. chenghuige commented on Nov 26, 2015

    @chenghuige
    Author

    It seems tesnsorflow right now does not support general sparse matrix yet. Will probably have to convert each mini-batch data into dense matrix but that will make matrix vector operation much slower..

  3. georgedahl commented on Nov 26, 2015

    @georgedahl

    You can probably construct a tf.SparseTensor from three placeholders (for the values, indices, and shape) and then feed dense numpy arrays for each of those.
    http://www.tensorflow.org/api_docs/python/sparse_ops.html#sparse-tensors

  4. chenghuige commented on Nov 26, 2015

    @chenghuige
    Author

    @georgedahl But seems many ops only support input to be tensor not sparse tensor.
    Like below
    h = tf.nn.sigmoid(tf.matmul(X, w_h)) # this is a basic mlp, think 2 stacked logistic regressions

    return tf.matmul(h, w_o)

    Is it possible to pass sparse tensor ?

  5. georgedahl commented on Nov 26, 2015

    @georgedahl

    It depends on what you are trying to do. If you have a sparse-dense product with sparse indicator variables tf.gather might be able to do what you want. Is w_h dense in your example?

  6. chenghuige commented on Nov 26, 2015

    @chenghuige
    Author

    @georgedahl
    X is sparse,w_h, w_o is dense

    X = tf.placeholder("float", [None, num_features]) # create symbolic variables

    Y = tf.placeholder("float", [None, 1])

    w_h = init_weights([num_features, hidden_size]) # create symbolic variables

    w_o = init_weights([hidden_size, 1])

    def model(X, w_h, w_o):

    h = tf.nn.sigmoid(tf.matmul(X, w_h)) # this is a basic mlp, think 2 stacked logistic regressions

    return tf.matmul(h, w_o) # note that we dont take the softmax at the end because our cost fn does that for us

  7. ebrevdo commented on Nov 26, 2015

    @ebrevdo
    Contributor

    We have SparseTensor and embedding lookup ops that with with SparseTensor.
    Can you clarify your exact use case?
    On Nov 25, 2015 5:15 PM, "chenghuige" [email protected] wrote:

    It seems tesnsorflow right now does not support general sparse matrix yet.
    Will probably have to convert each mini-batch data into dense matrix but
    that will make matrix vector operation much slower..

    —
    Reply to this email directly or view it on GitHub
    #342 (comment)
    .

  8. chenghuige commented on Nov 27, 2015

    @chenghuige
    Author

    @ebrevdo I want to use tensorflow doing text classification experiment.
    Say I may use the mini batch sgd implementation logistic regression for text classification.
    Then each mini batch is sparse matrix, like for each instance , will contain 400k features(where only 100 will be non zero), so for matmul(X,w) operation, X(mini batch input matrix) is sparse, w(weight vector) is dense.

    I find the code comment , seems only accept tensor nor sparse tensor, it has parameter a_is_sparse,
    but I'm not sure how to use ? convert sparse mini batch to dense matrix(tensor), then set (a_is_sparse=True)?
    def matmul(a, b,
    transpose_a=False, transpose_b=False,
    a_is_sparse=False, b_is_sparse=False,
    name=None):
    """Multiplies matrix a by matrix b, producing a * b.

    The inputs must be two-dimensional matrices, with matching inner dimensions,
    possibly after transposition.

    Both matrices must be of the same type. The supported types are:
    float, double, int32, complex64.

    Either matrix can be transposed on the fly by setting the corresponding flag
    to True. This is False by default.

    If one or both of the matrices contain a lot of zeros, a more efficient
    multiplication algorithm can be used by setting the corresponding
    a_is_sparse or b_is_sparse flag to True. These are False by default.

    For example:

      # 2-D tensor `a`
      a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) => [[1. 2. 3.]
                                                            [4. 5. 6.]]
      # 2-D tensor `b`
      b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) => [[7. 8.]
                                                               [9. 10.]
                                                               [11. 12.]]
      c = tf.matmul(a, b) => [[58 64]
                              [139 154]]

    Args:
    a: Tensor of type float, double, int32 or complex64.
    b: Tensor with same type as a.
    transpose_a: If True, a is transposed before multiplication.
    transpose_b: If True, b is transposed before multiplication.
    a_is_sparse: If True, a is treated as a sparse matrix.
    b_is_sparse: If True, b is treated as a sparse matrix.
    name: Name for the operation (optional).

    Returns:
    A Tensor of the same type as a.
    """

  9. ebrevdo commented on Nov 27, 2015

    @ebrevdo
    Contributor

    For this type of calculation, we have embedding_lookup. See the example in word2vec_basic. Your "X" would be the output of embedding_lookup.

  10. ebrevdo commented on Nov 27, 2015

    @ebrevdo
    Contributor

    In fact, for X*w, see embedding_lookup_sparse which does much of the hard work for you.

  11. chenghuige commented on Nov 27, 2015

    @chenghuige
    Author

    @ebrevdo thanks!  I will have a try:)

  12. chenghuige commented on Nov 27, 2015

    @chenghuige
    Author

    @ebrevdo Seems will not solve my problem. embeddings_lookup will need ids to be int32, but for X*w,
    w is a weight vector, with float value.

  13. georgedahl commented on Nov 27, 2015

    @georgedahl

    I think you should take another look. tf.gather or embeddinglookup or something similar will work to learn word embeddings. Only the ids need to be ints, the params are floats typically.

  14. chenghuige commented on Nov 27, 2015

    @chenghuige
    Author

    @georgedahl
    def embedding_lookup_sparse(params, sp_ids, sp_weights,
    name=None,
    combiner="mean"):
    Args:
    params: A single tensor representing the complete embedding tensor,

    I suppose params to be single tensor, then for my problem input X must be a tensor which is dense,
    but X actually should be sparse, converting to dense is not good..

  15. ebrevdo commented on Nov 27, 2015

    @ebrevdo
    Contributor

    @chenghuige Since you have 400k features, in practice you must somewhere store a 400k x feature_depth matrix, no? This is what you pass to embedding_lookup_sparse and it performs the sparse multiplication for you.

  16. chenghuige commented on Nov 28, 2015

    @chenghuige
    Author

    @ebrevdo Could you help me modify my simple example code ? I have posted my code and dataset.

    #binary classification of dense input data using logistic regression
    python ./logistic_regression.py --train ./data/feature.normed.rand.12000.0_2.txt --test ./data/feature.normed.rand.12000.1_2.txt
    This will be ok...
    0 auc: 0.776691260816 cost: 1439.02
    1 auc: 0.876033213903 cost: 538.457
    2 auc: 0.893921799102 cost: 495.259
    3 auc: 0.900204872568 cost: 480.429

    #binary classification of sparse input data using logistic regression
    python ./logistic_regression_sparse.py --train ./data/feature.trate.0_2.normed.txt --test ./data/feature.trate.1_2.normed.txt

    This one is really slow(batch size 50), and if setting to large batch size(500) will cause memroy error, could you help me modify it(logistic_regression_sparse.py) to work ? Thanks !

    https://github.com/chenghuige/tensorflow-example

  17. ebrevdo commented on Nov 29, 2015

    @ebrevdo
    Contributor

    There are a few things in that example that I can't see, for example sparse2dense is not defined.

    Also, this is a good question for stackoverflow; github issues is more focused towards reporting bugs.

  18. chenghuige commented on Nov 29, 2015

    @chenghuige
    Author

    I see, sparse2dense is in melt_dataset.py. Right now there are similar question in stackoverflow but no answer

  19. ebrevdo commented on Nov 29, 2015

    @ebrevdo
    Contributor

    Suppose you have a minibatch of 2 entries. The first entry has sparse ids [53, 87, 101], values [0.1, 0.2, 0.3] and the second has sparse ids [34, 98], weights [-1.0, 3.5]. Suppose your total vocab size is 500. Suppose also that the hidden layer has depth 25 (25 units).

    then:

    X = tf.Variable(tf.truncated_normal([500, 25], stddev=1/500.0))
    sp_indices = tf.placeholder(tf.int64)
    sp_shape = tf.placeholder(tf.int64)
    sp_ids_val = tf.placeholder(tf.int64)
    sp_weights_val = tf.placeholder(tf.float32)
    sp_ids = tf.SparseTensor(sp_indices, sp_ids_val, sp_shape)
    sp_weights = tf.SparseTensor(sp_indices, sp_weights_val, sp_shape)
    y = tf.nn.embedding_lookup_sparse(X, sp_ids, sp_weights, "sum")
    tf.initialize_all_variables().run()  # initialize values in X
    
    y_values = tf.run(y, feed_dict={
      sp_indices: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]],  # 3 entries in minibatch entry 0, 2 entries in entry 1.
      sp_shape: [2, 3],  # batch size: 2, max index: 2 (so index count == 3)
      sp_ids_val: [53, 87, 101, 34, 98],
      sp_weights_val: [0.1, 0.2, 0.3, -1.0, 3.5]})

    y_values should be the output of X*[w1, w2], where w1 and w2 are the two minibatch entries.

  20. chenghuige commented on Nov 29, 2015

    @chenghuige
    Author

    @ebrevdo Thanks very much for your patient explanation ! I finally got your point.
    However I'm still a bit confused by the embedding_lookup_sparse result
    seems there is a bug , that "sum" just work the same as "mean".
    I modified your code a bit .
    import tensorflow as tf
    import numpy as np

    X = tf.placeholder("float", [10, 1])
    x = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]], dtype=np.float32)

    sp_indices = tf.placeholder(tf.int64)
    sp_shape = tf.placeholder(tf.int64)
    sp_ids_val = tf.placeholder(tf.int64)
    sp_weights_val = tf.placeholder(tf.float32)
    sp_ids = tf.SparseTensor(sp_indices, sp_ids_val, sp_shape)
    sp_weights = tf.SparseTensor(sp_indices, sp_weights_val, sp_shape)
    y = tf.nn.embedding_lookup_sparse(X, sp_ids, sp_weights, "sum")

    sess = tf.Session()
    sess.run(tf.initialize_all_variables())

    y_values = sess.run(y, feed_dict={
    X: x,
    sp_indices: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], # 3 entries in minibatch entry 0, 2 entries in entry 1.
    sp_shape: [2, 3], # batch size: 2, max index: 2 (so index count == 3)
    sp_ids_val: [2, 5, 8, 3, 4],
    sp_weights_val: [1.0, 1.5, 2.5, 3.5, 4.5]
    })

    print y_values

    #0 should be

    2 * 1 + 5 * 1.5 + 8 * 2.5 = 29.5

    #The result
    ./sparse_tensor.py
    I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 24
    I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 24
    [[ 5.9000001]
    [ 3.5625 ]]

    The result is as 29.5/(1 + 1.5 + 2.5) = 5.9

  21. chenghuige commented on Nov 30, 2015

    @chenghuige
    Author

    @ebrevdo Well should be combiner = "sum", then ok. Thanks very much, ebrevdo and georgedahl.
    Since problem solved, closing this bug.

  22. salman1993 commented on Nov 24, 2016

    @salman1993

    @chenghuige @ebrevdo
    Hey, I am also trying to do text classification - working with very sparse data. TF-IDF feature matrix in SVM light format. I understand the nn.embedding_lookup_sparse BUT your code for producing mini-batch sets does not randomly shuffle the dataset. Is there a good way to do it? Also, does your full_batch_set() have a bug because I get an error when I try to run that.

  23. physicso commented on Dec 7, 2016

    @physicso

    I am also trying to model very sparse sequential input data with RNN (LSTM). Is there any approaches besides converting the sparse data into dense ones? I'm afraid that the input data may blow up the GPU memory ;)

  24. CasyWang commented on Jan 18, 2017

    @CasyWang

    @chenghuige Hey, i am using the tensorflow to train a logistic regression model,
    if i feed the feed_dict with dense feature vector, the computation of gradient is very slow, how should i use the sparse tensor to speed up the training operation?

  25. tobegit3hub commented on Jan 18, 2017

    @tobegit3hub
    Contributor
  26. added a commit that references this issue on Jan 23, 2020
  27. added a commit that references this issue on May 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions