You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 ?
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..
@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
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?
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)
.
@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.
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).
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.
@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..
@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.
@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 !
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).
@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)
#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 ]]
@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.
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 ;)
Reacted by Alexander Measure, Yihong Chen, Yijun Xiao, butterluo and 德才
@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?
Activity
[-]Feed sparse array for place holder ?[/-][+]Feed sparse array for placeholder ?[/+]chenghuige commentedon Nov 26, 2015
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..
georgedahl commentedon Nov 26, 2015
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
chenghuige commentedon Nov 26, 2015
@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 ?
georgedahl commentedon Nov 26, 2015
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?
chenghuige commentedon Nov 26, 2015
@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
ebrevdo commentedon Nov 26, 2015
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:
chenghuige commentedon Nov 27, 2015
@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
aby matrixb, producinga*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 isFalseby 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_sparseorb_is_sparseflag toTrue. These areFalseby default.For example:
Args:
a:
Tensorof typefloat,double,int32orcomplex64.b:
Tensorwith same type asa.transpose_a: If
True,ais transposed before multiplication.transpose_b: If
True,bis transposed before multiplication.a_is_sparse: If
True,ais treated as a sparse matrix.b_is_sparse: If
True,bis treated as a sparse matrix.name: Name for the operation (optional).
Returns:
A
Tensorof the same type asa."""
ebrevdo commentedon Nov 27, 2015
For this type of calculation, we have embedding_lookup. See the example in word2vec_basic. Your "X" would be the output of embedding_lookup.
ebrevdo commentedon Nov 27, 2015
In fact, for X*w, see embedding_lookup_sparse which does much of the hard work for you.
chenghuige commentedon Nov 27, 2015
@ebrevdo thanks! I will have a try:)
chenghuige commentedon Nov 27, 2015
@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.
georgedahl commentedon Nov 27, 2015
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.
chenghuige commentedon Nov 27, 2015
@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..
ebrevdo commentedon Nov 27, 2015
@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.
chenghuige commentedon Nov 28, 2015
@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
ebrevdo commentedon Nov 29, 2015
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.
chenghuige commentedon Nov 29, 2015
I see, sparse2dense is in melt_dataset.py. Right now there are similar question in stackoverflow but no answer
ebrevdo commentedon Nov 29, 2015
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:
y_values should be the output of X*[w1, w2], where w1 and w2 are the two minibatch entries.
chenghuige commentedon Nov 29, 2015
@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
chenghuige commentedon Nov 30, 2015
@ebrevdo Well should be combiner = "sum", then ok. Thanks very much, ebrevdo and georgedahl.
Since problem solved, closing this bug.
salman1993 commentedon Nov 24, 2016
@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.
physicso commentedon Dec 7, 2016
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 ;)
CasyWang commentedon Jan 18, 2017
@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?
tobegit3hub commentedon Jan 18, 2017
chenghuige commentedon Feb 28, 2017
@CasyWang you can find one example of training and predicting of libsvm format data file example here
https://github.com/chenghuige/hasky/tree/master/applications/text-regression
https://github.com/chenghuige/hasky/blob/master/applications/README.md
Merge pull request tensorflow#342 from ROCmSoftwarePlatform/develop-u…
Update XNNPACK in XLA