forked from zihangdai/cegan_iclr2017
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_iterator.py
87 lines (61 loc) · 2.37 KB
/
data_iterator.py
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
import numpy as np
class FixDimIterator(object):
def __init__(self, data, batch_size, shuffle=False):
super(FixDimIterator, self).__init__()
self.data = data
self.num_data = data.shape[0]
self.shuffle = shuffle
self.set_batchsize(batch_size)
self.reset()
def set_batchsize(self, batch_size):
self.n_batches = self.num_data / batch_size
if self.num_data % batch_size != 0:
self.n_batches += 1
self.batch_size = batch_size
def __iter__(self):
return self
def reset(self):
if self.shuffle:
self.data_indices = np.random.permutation(self.num_data)
else:
self.data_indices = np.arange(self.num_data)
self.batch_idx = 0
def next(self):
if self.batch_idx == self.n_batches:
self.reset()
raise StopIteration
idx = self.batch_idx * self.batch_size
chosen_indices = self.data_indices[idx:idx+self.batch_size]
self.batch_idx += 1
return self.data[chosen_indices]
class MultiFixDimIterator(object):
"""Iterate multiple ndarrays (e.g. images and labels) and return tuples of minibatches"""
def __init__(self, *data, **kwargs):
super(MultiFixDimIterator, self).__init__()
assert all(d.shape[0] == data[0].shape[0] for d in data), 'passed data differ in number!'
self.data = data
self.num_data = data[0].shape[0]
batch_size = kwargs.get('batch_size', 100)
shuffle = kwargs.get('shuffle', False)
self.n_batches = self.num_data / batch_size
if self.num_data % batch_size != 0:
self.n_batches += 1
self.batch_size = batch_size
self.shuffle = shuffle
self.reset()
def __iter__(self):
return self
def reset(self):
if self.shuffle:
self.data_indices = np.random.permutation(self.num_data)
else:
self.data_indices = np.arange(self.num_data)
self.batch_idx = 0
def next(self):
if self.batch_idx == self.n_batches:
self.reset()
raise StopIteration
idx = self.batch_idx * self.batch_size
chosen_indices = self.data_indices[idx:idx+self.batch_size]
self.batch_idx += 1
return tuple(data[chosen_indices] for data in self.data)