trainmodel | Cell 14 | Cell 16 | Search

The to_categorical function converts integer class vectors into binary class matrices, useful for classification problems. It takes integer class vectors and returns one-hot encoded matrices, where each row represents a sample and each column represents a class.

Cell 15

y_train = to_categorical(y_train,num_classes = 7)
y_test = to_categorical(y_test,num_classes = 7)

What the code could have been:

import numpy as np
from tensorflow.keras.utils import to_categorical

def convert_to_one_hot(y_train, y_test, num_classes):
    """
    Convert class labels to one-hot encoding using Keras' to_categorical function.

    Args:
        y_train (np.ndarray): Training labels.
        y_test (np.ndarray): Testing labels.
        num_classes (int): Number of classes.

    Returns:
        tuple: One-hot encoded training and testing labels.
    """
    y_train_one_hot = to_categorical(y_train, num_classes=num_classes)
    y_test_one_hot = to_categorical(y_test, num_classes=num_classes)

    return y_train_one_hot, y_test_one_hot

# Example usage
y_train = np.array([0, 1, 2, 3, 4, 5, 6])
y_test = np.array([6, 5, 4, 3, 2, 1, 0])
num_classes = 7

y_train_one_hot, y_test_one_hot = convert_to_one_hot(y_train, y_test, num_classes)
print("One-hot encoded training labels:", y_train_one_hot)
print("One-hot encoded testing labels:", y_test_one_hot)

Code Breakdown

Function: to_categorical

The to_categorical function is used to convert integer class vectors to binary class matrices.

Usage:

y_train = to_categorical(y_train, num_classes=7)
y_test = to_categorical(y_test, num_classes=7)

Parameters:

Result:

The function returns binary class matrices, where each row is a one-hot encoding of the corresponding class label. In this case, the classes are numbered from 0 to 6 (since the number of classes is 7). The resulting arrays are:

Each column represents a class, and the value at each position is either 0 or 1, indicating whether the sample belongs to that class or not.