How can I implement shape on Custom Dataset?

I am trying to get “shape” to work on my Custom Dataset:

class MyDataset(Dataset):
    def __init__(self, data, window):
        self.data = data
        self.window = window

    def __getitem__(self, index):
        x = self.data[index:index+self.window]
        return x

    def __len__(self):
        return len(self.data) -  self.window + 1
# my_dataset=MyDataset(train_data_normalized, 14)
my_array = np.arange(99)
my_array.shape

(99,)

my_dataset=MyDataset(my_array,10)
my_dataset.shape
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-42-72becebb3571> in <module>
      1 my_dataset=MyDataset(my_array,10)
----> 2 my_dataset.shape

AttributeError: 'MyDataset' object has no attribute 'shape'

Hi,

shape actually is an attribute for tensors or numpy arrays, if you are interested in adding any attribute to your classes, just define self.shape. Here is an example:


class MyDataset(data.Dataset):
    def __init__(self, data, window):
        self.data = data
        self.window = window
        self.shape = self.__getshape__()

    def __getitem__(self, index):
        x = self.data[index:index+self.window]
        return x

    def __len__(self):
        return len(self.data) -  self.window + 1

    def __getshape__(self):
        return (self.__len__(), *self.__getitem__(0)[0].shape)

x_train = np.random.randn(6000, 1, 32, 32)

my_data = MyDataset(x_train, 1)

Bests

1 Like