我正在使用tf.keras训练具有以下摘要的模型:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 28, 28, 20) 520
_________________________________________________________________
flatten (Flatten) (None, 15680) 0
_________________________________________________________________
dense (Dense) (None, 5) 78405
=================================================================
Total params: 78,925
Trainable params: 78,925
Non-trainable params: 0
_________________________________________________________________
我正在使用
调用fit方法 model.fit(X_train, y_train, batch_size=32, steps_per_epoch=125, epochs=5, use_multiprocessing=True)
其中X_train是形状为[900000,32,32,1]的张量流变量。
我遇到以下错误:
Resource exhausted: OOM when allocating tensor with shape[900000,28,28,20] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
[[{{node conv2d_1/Conv2D}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
[[metrics_2/acc/Identity/_53]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
(1) Resource exhausted: OOM when allocating tensor with shape[900000,28,28,20] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
[[{{node conv2d_1/Conv2D}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
0 successful operations.
0 derived errors ignored.
当批次大小为32时,我无法理解为什么它会分配形状为[900000,28,28,20]的张量。我期望的是[32,28,28,20]。
完整代码:
IMAGE_SIZE = 32
BATCH_SIZE = 32
conv1_layer = keras.layers.Conv2D(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 1), filters=20, kernel_size=[5, 5], activation='relu')
f = keras.layers.Flatten()
output_layer = keras.layers.Dense(units=5, activation='softmax')
model = keras.models.Sequential(layers=[conv1_layer, f, output_layer])
model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=BATCH_SIZE, steps_per_epoch=int(X_train.shape[0])//BATCH_SIZE, epochs=5, use_multiprocessing=True)
答案 0 :(得分:0)
该问题最可能出现在use_multiprocessing=True
中,该问题期望输入作为生成器对象(请参见docs)-因此,如果馈送X_train
数组不会立即产生错误,则可能通过在轴0上进行迭代并一次馈送所有900,000个样本,将其视为发生器,从而产生误差。尝试使用use_multiprocessing=False
,或使用generator输入数据。
此外,steps_per_epoch
可能是一个附加来源-从fit
中省略它们-然后,在输入tf.Variable
之前,先评估 ,例如{{ 1}}不会自动处理。
答案 1 :(得分:0)
我建议您编写自己的训练数据生成器或keras.utils.Sequence
。直接输入整个训练数据不是一个好主意,特别是当您的数据集非常大时。另外, use_multiprocessing
自变量用于generator或keras.utils。仅按顺序输入,如.fit() doc
以下代码改编自A detailed example of how to use data generators with Keras。
import numpy as np
import keras
class DataGenerator(keras.utils.Sequence):
'Generates data for Keras'
def __init__(self, list_IDs, labels, batch_size=32, dim=(32,32), n_channels=1, n_classes=10, shuffle=True):
'Initialization'
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'
# Generate indexes of the batch
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)
params = {'dim': (32,32),
'batch_size': 32,
'n_classes': 5,
'n_channels': 1,
'shuffle': True}
train_data_path = # (list of string) ['0302','0325','3103',...] 'data/0302.npy' is the path where stores the '0302' image.
train_labels = # (list of int) [1,0,4,...] corresponding labels of 900,000 images.
# Generators
train_gen = DataGenerator(train_data_path, train_labels, **params)
model.fit_generator(generator=train_gen,
epochs=5,
use_multiprocessing=True,
workers=2)