부록: 일괄 학습

매우 큰 데이터 세트는 프로세스에 할당된 메모리에 맞지 않을 수 있습니다. 이전 단계에서는 전체 데이터 세트를 메모리로 가져오고, 데이터를 준비하고, 작업 세트를 학습 함수에 전달하는 파이프라인을 설정했습니다. 대신 Keras는 데이터를 일괄 가져오는 대체 학습 함수(fit_generator)를 제공합니다. 따라서 데이터 파이프라인의 변환을 데이터의 작은 부분 (batch_size 배수)에만 적용할 수 있습니다. 실험 과정에서 DBPedia, Amazon 리뷰, Ag 뉴스, Yelp 리뷰와 같은 데이터 세트에 일괄 처리 (GitHub 코드)를 사용했습니다.

다음 코드는 데이터 배치를 생성하고 fit_generator에 제공하는 방법을 보여줍니다.

def _data_generator(x, y, num_features, batch_size):
    """Generates batches of vectorized texts for training/validation.

    # Arguments
        x: np.matrix, feature matrix.
        y: np.ndarray, labels.
        num_features: int, number of features.
        batch_size: int, number of samples per batch.

    # Returns
        Yields feature and label data in batches.
    """
    num_samples = x.shape[0]
    num_batches = num_samples // batch_size
    if num_samples % batch_size:
        num_batches += 1

    while 1:
        for i in range(num_batches):
            start_idx = i * batch_size
            end_idx = (i + 1) * batch_size
            if end_idx > num_samples:
                end_idx = num_samples
            x_batch = x[start_idx:end_idx]
            y_batch = y[start_idx:end_idx]
            yield x_batch, y_batch

# Create training and validation generators.
training_generator = _data_generator(
    x_train, train_labels, num_features, batch_size)
validation_generator = _data_generator(
    x_val, val_labels, num_features, batch_size)

# Get number of training steps. This indicated the number of steps it takes
# to cover all samples in one epoch.
steps_per_epoch = x_train.shape[0] // batch_size
if x_train.shape[0] % batch_size:
    steps_per_epoch += 1

# Get number of validation steps.
validation_steps = x_val.shape[0] // batch_size
if x_val.shape[0] % batch_size:
    validation_steps += 1

# Train and validate model.
history = model.fit_generator(
    generator=training_generator,
    steps_per_epoch=steps_per_epoch,
    validation_data=validation_generator,
    validation_steps=validation_steps,
    callbacks=callbacks,
    epochs=epochs,
    verbose=2)  # Logs once per epoch.