अन्य जानकारी: बैच ट्रेनिंग

हो सकता है कि बहुत बड़े डेटासेट, आपकी प्रोसेस के लिए उपलब्ध मेमोरी में फ़िट न हों. पिछले चरणों में, हमने एक पाइपलाइन सेट अप की है, जिसमें हम पूरे डेटासेट को मेमोरी में लाते हैं, डेटा तैयार करते हैं, और काम करने के सेट को ट्रेनिंग फ़ंक्शन में पास करते हैं. इसके बजाय, केरास एक वैकल्पिक ट्रेनिंग फ़ंक्शन (fit_generator) देते हैं, जिसमें डेटा को बैच में बांटा जाता है. इससे हम डेटा पाइपलाइन में होने वाले बदलावों को, डेटा के छोटे से हिस्से (batch_size के एक से ज़्यादा) में लागू कर पाएंगे. अपने प्रयोगों के दौरान, हमने DBPedia, Amazon reviews, Ag news, और Yelp reviews जैसे डेटासेट के लिए बैच बनाने की सुविधा का इस्तेमाल किया.

इस कोड में, डेटा बैच जनरेट करने और उन्हें 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.