(*)
import numpy as np
import keras
class DataGenerator(keras.utils.Sequence):
def __init__(self, list_IDs, labels, batch_size=10, dim=(32,32), n_channels=1, n_classes=10, shuffle=True):<br>
self.dim = dim
self.batch_size = batch_size
self.labels = labels
self.list_IDs = list_IDs
self.n_channels = n_channels
self.n_classes = n_classes
self.shuffle = shuffle
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.floor(len(self.list_IDs) / self.batch_size))
def __getitem__(self, index):
'Generate one batch of data'
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
# Find list of IDs
list_IDs_temp = [self.list_IDs[k] for k in indexes]
# Generate data
X, y = self.__data_generation(list_IDs_temp)
return X, y
def on_epoch_end(self):
'Updates indexes after each epoch'
self.indexes = np.arange(len(self.list_IDs))
if self.shuffle == True:
np.random.shuffle(self.indexes)
def __data_generation(self, list_IDs_temp):
'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
# Initialization
X = np.empty((self.batch_size, *self.dim, self.n_channels))
y = np.empty((self.batch_size), dtype=int)
# Generate data
for i, ID in enumerate(list_IDs_temp):
# Store sample
X[i,] = np.load('data/' + ID + '.npy')
# Store class
y[i] = self.labels[ID]
return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
答案 0 :(得分:0)
好吧,*self.dim
用于解压缩容器作为参数。这基本上意味着您传递了self.dim
,并且该函数将其视为要在函数内部解压缩的元组。有关更广泛的解释,请参见this(“打开包装箱”一节)。
在您的情况下,您将在以下位置使用它:
X = np.empty((self.batch_size, *self.dim, self.n_channels))
其中np.empty()
期望一个包含int(或单个int)作为第一个参数的元组。在您的情况下,您正在传递一个包含元组作为第二个元素的元组。您必须自己打开包装才能使其正常工作:
X = np.empty((self.batch_size, self.dim[0], self.dim[1], self.n_channels))
因此,您应该坚持使用*
部分,但应以不同的方式对待参数。另外,*arg
具有更大的灵活性,这意味着它可以处理带有2、3等元素的容器,而像args[0], args[1]
这样的硬编码代码则没有。