Get Started

Using one-hot encoding to represent images

Neural networks expect the labels of classes in a dataset to be organized in a one-hot encoded manner: each row in the array contains zeros in all columns, except the column corresponding to a unique label, which is set to 1.

The fashion dataset contains three categories:

  1. Shirts
  2. Dresses
  3. Shoes

In this exercise, you will create a one-hot encoding of a small sample of these labels.

This is a part of the course

“Image Modeling with Keras”

View Course

Exercise instructions

  • Initialize the ohe_labels variable to hold the one-hot encoded array.
  • Use np.where() to find the location of the category of the item in each iteration in categories.
  • Assign a 1 into the correct row/column combination in every iteration.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# The number of image categories
n_categories = 3

# The unique values of categories in the data
categories = np.array(["shirt", "dress", "shoe"])

# Initialize ohe_labels as all zeros
ohe_labels = ____((len(labels), n_categories))

# Loop over the labels
for ii in range(len(labels)):
    # Find the location of this label in the categories variable
    jj = np.where(___)
    # Set the corresponding zero to one
    ohe_labels[____] = ____

This exercise is part of the course

Image Modeling with Keras

AdvancedSkill Level
4.4+
18 reviews

Learn to conduct image analysis using Keras with Python by constructing, training, and evaluating convolutional neural networks.

Convolutional neural networks use the data that is represented in images to learn. In this chapter, we will probe data in images, and we will learn how to use Keras to train a neural network to classify objects that appear in images.

Exercise 1: Introducing convolutional neural networksExercise 2: Images as data: visualizationsExercise 3: Images as data: changing imagesExercise 4: Classifying imagesExercise 5: Using one-hot encoding to represent images
Exercise 6: Evaluating a classifierExercise 7: Classification with KerasExercise 8: Build a neural networkExercise 9: Compile a neural networkExercise 10: Fitting a neural network model to clothing dataExercise 11: Cross-validation for neural network evaluation

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free