Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tensorflow train with sparse data

I want to use a sparse tensor in tensorflow of python for training. I found a lot of code how to do that, but none of them worked.

Here an example code to show what I mean, it throws an error:

import numpy as np
x_vals = tf.sparse.SparseTensor([[0, 0], [0, 1], [1, 2]], [1, 2, 1], [2, 3])
#x_vals = tf.sparse.to_dense(x_vals)    #this line decides, if there is an error
y_vals = np.array([0, 1])

layer_args = lambda : None
layer_args.input_shape = (3,)
layer_args.activation = "sigmoid"
layer_args.use_bias = False

model = tf.keras.models.Sequential(tf.keras.layers.Dense(1, **layer_args.__dict__))

model.compile(loss = "mse")

model.fit(x_vals, y_vals)

The error is:

ValueError: The two structures don't have the same nested structure.

...and a huge stacktrace

like image 289
GuiTaek Avatar asked Oct 18 '25 19:10

GuiTaek


1 Answers

Ok I figured out how it works. The simplest solution is, to use a generator:

from random import shuffle
def data_generator(x_vals, y_vals):
    inds = list(range(x_vals.shape[0]))
    shuffle(inds)
    for ind in inds:
        yield (x_vals[ind, :].todense(), y_vals[ind])

And then using that generator for the x-value in fit:

model.fit(data_generator(x_vals, y_vals))

However it is very slow. Also you can only train one epoch at once and there are a lot of features of keras you can't use. Possible is also a tensorflow.keras.utils.Sequence:

class SparseSequence(tf.keras.utils.Sequence):
    def __init__(self, x_vals, y_vals, batch_size = 32):
        self.x_vals = x_vals
        self.y_vals = y_vals
        self.inds = list(range(x_vals.shape[0]))
        shuffle(self.inds)
        self.batch_size = batch_size
    def __getitem__(self, item):
        from_ind = self.batch_size * item
        to_ind = self.batch_size * (item + 1)
        return (self.x_vals[self.inds[from_ind:to_ind], :].todense(),
                y_vals[self.inds[from_ind:to_ind]])
    def on_epoch_end(self):
        shuffle(self.inds)
    def __len__(self):
        return math.ceil(self.x_vals.shape[0] / self.batch_size)

And then using that in the fit-function:

model.fit(SparseSequence(x_vals, y_vals))

Keep in mind, that the data needs to be converted first to scipy csr sparse matrices, else the code won't work. Keep also in mind to not use the "y"-keyword in Model.fit().

like image 109
GuiTaek Avatar answered Oct 20 '25 08:10

GuiTaek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!