To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

generic_dataset.py 7.2 KB
Newer Older
matthmey's avatar
matthmey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import numpy as np
import pickle
import warnings 

class generic_dataset:
    ''' Base class for aednn datasets
    On its own it cannot be used but must be extended at least with load_data function

    '''

    def __init__(self,tmp_dir,name='generic',params=None,preprocessing_function=None,restore_from_disk=True,dtype=np.float32):
        self.name = name
        self.tmp_dir = tmp_dir

        self.shape = None               # first entry must be (num_samples, ... ) 
        self.num_labels = None

        self.data_loaded = False

        self.dtype = dtype

        self.ratio = 0.75

        # self.preprocessing_function = preprocessing_function

        if not restore_from_disk:
            self.init_parameters(params)
        else:
            try:
                self.load()
            except:
                self.init_parameters(params)
        
        # if not self.data_loaded:
        #     self.load_data()
        #     self.data_loaded = True
        #     self.save()

    def init_parameters(self,params):
        ''' should be overwritten '''
        pass

    def load_data(self):
        ''' should be overwritten 
        
        It must store the data in a memmap array

        X = np.memmap(self.tmp_dir + 'X_%s.mmap'%self.name,mode='w+',dtype=self.dtype, shape=self.shape)
        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode='w+',dtype=np.bool_, shape=(self.shape[0],self.num_labels))
        '''
        pass

    def get_y(self,reload=False):
        """ Return the y value of the dataset. Currently y is restricted to be labels
        
        Keyword Arguments:
            reload {bool} -- Set to True if the data needs to be reloaded from disk (default: {False})
        
        Returns:
            [type] -- [description]
        """

        if not self.data_loaded or reload:
            self.load_data()
            self.data_loaded = True
            self.save()
        
        return np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode='r',dtype=np.bool_, shape=(self.shape[0],self.num_labels))

    def get_X(self,reload=False):
        if not self.data_loaded or reload:
            self.load_data()
            self.data_loaded = True
            self.save()
        
        return np.memmap(self.tmp_dir + 'X_%s.mmap'%self.name,mode='r',dtype=self.dtype, shape=self.shape)

    def get_label(self,label):
        '''
            # Params

            label:  if label is a string it will return the label id as an integer, if it's an integer it will return the label name as a string.
                    The label id is the identifier which marks the column of the *y* array belonging to the label
            
        '''

        if isinstance(label,str):
            if label not in self.labels:
                raise KeyError('The label name %s is not a correct identifier for the dataset %s'%(label,self.name))
            return self.label_ids[label]
        else:
            if label not in self.label_ids:
                raise KeyError('The label id %d is not a correct identifier for the dataset %s'%(label,self.name))
            return self.labels[label]

    def load_if_needed(self,force_reload=False):
        if not self.data_loaded or force_reload:
            self.load_data()
            self.data_loaded = True
            self.save()

    # @profile
    def get_data(self,dataset='all',reload=False):
        # first check if we need to reload everything
        # print('....',self.data_loaded, reload)
        self.load_if_needed(reload)

        y = self.get_y()
        X = self.get_X()
        
        if dataset == 'train':
            train_idx = int(self.shape[0] * self.ratio)
            return  X[:train_idx], y[:train_idx]
        elif dataset == 'test':
            train_idx = int(self.shape[0] * self.ratio)
            return X[train_idx:], y[train_idx:]
        elif dataset == 'all':
            return X,y
        else:
            assert dataset in ['train','test','all'], "Error: Unknown dataset type. Possible candidates are: train, test, all"

    def get_batch(self,idx,batch_size,reload=False,mode='r'):
        warnings.warn(
            "slow_sort is deprecated, use fast_sort instead",
            DeprecationWarning
        )

        # Check if we need to crop the batch_size because of file end
        original_batch_size = batch_size
        if (idx+1)*batch_size > self.shape[0]:
            batch_size =  int(self.shape[0] - idx*batch_size)
            # print('Cropped value while creating batch. New batch size: %d'%batch_size)

        assert batch_size <= original_batch_size, 'The combination of batch_size and idx does not match the dataset file'

        byte_size = np.dtype(self.dtype).itemsize
        batch_shape = (batch_size,self.shape[1],self.shape[2],self.shape[3])
        batch_bytes = int(byte_size*np.prod(batch_shape))
        X = np.memmap(self.tmp_dir + 'X_%s.mmap'%self.name,mode=mode,dtype=self.dtype , offset=int(idx*batch_bytes), shape=batch_shape)

        byte_size = np.dtype(np.bool_).itemsize
        batch_shape = (batch_size,self.num_labels)
        batch_bytes = byte_size*np.prod(batch_shape)
        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode=mode,dtype=np.bool_, offset=int(idx*batch_bytes), shape=batch_shape)

        return X,y

    def get_segment(self,idx,size,mode='r',return_set='all'):
        original_size = size
        if idx+size > self.shape[0]:
            size =  int(self.shape[0] - (idx+size))
        assert size <= original_size, 'The combination of batch_size and idx does not match the dataset file'

        byte_size = np.dtype(self.dtype).itemsize
        item_shape = (1,self.shape[1],self.shape[2],self.shape[3])
        batch_shape = (size,self.shape[1],self.shape[2],self.shape[3])
        batch_bytes = int(byte_size*np.prod(item_shape))
        X = np.memmap(self.tmp_dir + 'X_%s.mmap'%self.name,mode=mode,dtype=self.dtype , offset=int(idx*batch_bytes), shape=batch_shape)

        byte_size = np.dtype(np.bool_).itemsize
        item_shape = (1,self.num_labels)
        batch_shape = (size,self.num_labels)
        batch_bytes = byte_size*np.prod(item_shape)
        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode=mode,dtype=np.bool_, offset=int(idx*batch_bytes), shape=batch_shape)
        
        # if (skip_preprocessing == False) and (self.preprocessing_function is not None):
        #     print(self.preprocessing_function)
        #     X,y = self.preprocessing_function(X,y)

        if return_set=='all':
            return X,y
        if return_set=='X':
            return X
        if return_set=='y':
            return y
        
    def save(self):
        with open(self.tmp_dir + '%s.pickle' % self.name, 'wb') as f:
            pickle.dump(self.__dict__, f, pickle.HIGHEST_PROTOCOL)
            f.close()

    def load(self):
        # save tmp_dir temporally to set it to the new location, otherwise we could not move the files
        # without reloading everythin
        local_tmp_dir = self.tmp_dir
        local_name = self.name
        # Load all the settings/parameters and set them 
        with open(self.tmp_dir + '%s.pickle' % self.name, 'rb') as f:
            self.__dict__.update(pickle.load(f))
            f.close()
        self.tmp_dir = local_tmp_dir        # reload tmp_dir
        self.name = local_name