Tweet Share Share

Last Updated on August 27, 2020

Machine learning and deep learning models, like those in Keras, require all input and output variables to be numeric.

This means that if your data contains categorical data, you must encode it to numbers before you can fit and evaluate a model.

The two most popular techniques are an integer encoding and a one hot encoding, although a newer technique called learned embedding may provide a useful middle ground between these two methods.

In this tutorial, you will discover how to encode categorical data when developing neural network models in Keras.

After completing this tutorial, you will know:

The challenge of working with categorical data when using machine learning and deep learning models.

How to integer encode and one hot encode categorical variables for modeling.

How to learn an embedding distributed representation as part of a neural network for categorical variables.

Kick-start your project with my new book Deep Learning With Python, including step-by-step tutorials and the Python source code files for all examples.

Let’s get started.

Tutorial Overview

This tutorial is divided into five parts; they are:

The Challenge With Categorical Data Breast Cancer Categorical Dataset How to Ordinal Encode Categorical Data How to One Hot Encode Categorical Data How to Use a Learned Embedding for Categorical Data

The Challenge With Categorical Data

A categorical variable is a variable whose values take on the value of labels.

For example, the variable may be “color” and may take on the values “red,” “green,” and “blue.”

Sometimes, the categorical data may have an ordered relationship between the categories, such as “first,” “second,” and “third.” This type of categorical data is referred to as ordinal and the additional ordering information can be useful.

Machine learning algorithms and deep learning neural networks require that input and output variables are numbers.

This means that categorical data must be encoded to numbers before we can use it to fit and evaluate a model.

There are many ways to encode categorical variables for modeling, although the three most common are as follows:

Integer Encoding: Where each unique label is mapped to an integer. One Hot Encoding: Where each label is mapped to a binary vector. Learned Embedding: Where a distributed representation of the categories is learned.

We will take a closer look at how to encode categorical data for training a deep learning neural network in Keras using each one of these methods.

Breast Cancer Categorical Dataset

As the basis of this tutorial, we will use the so-called “Breast cancer” dataset that has been widely studied in machine learning since the 1980s.

The dataset classifies breast cancer patient data as either a recurrence or no recurrence of cancer. There are 286 examples and nine input variables. It is a binary classification problem.

A reasonable classification accuracy score on this dataset is between 68% and 73%. We will aim for this region, but note that the models in this tutorial are not optimized: they are designed to demonstrate encoding schemes.

You can download the dataset and save the file as “breast-cancer.csv” in your current working directory.

Looking at the data, we can see that all nine input variables are categorical.

Specifically, all variables are quoted strings; some are ordinal and some are not.

'40-49','premeno','15-19','0-2','yes','3','right','left_up','no','recurrence-events' '50-59','ge40','15-19','0-2','no','1','right','central','no','no-recurrence-events' '50-59','ge40','35-39','0-2','no','2','left','left_low','no','recurrence-events' '40-49','premeno','35-39','0-2','yes','3','right','left_low','yes','no-recurrence-events' '40-49','premeno','30-34','3-5','yes','2','left','right_up','no','recurrence-events' ... 1 2 3 4 5 6 '40-49','premeno','15-19','0-2','yes','3','right','left_up','no','recurrence-events' '50-59','ge40','15-19','0-2','no','1','right','central','no','no-recurrence-events' '50-59','ge40','35-39','0-2','no','2','left','left_low','no','recurrence-events' '40-49','premeno','35-39','0-2','yes','3','right','left_low','yes','no-recurrence-events' '40-49','premeno','30-34','3-5','yes','2','left','right_up','no','recurrence-events' ...

We can load this dataset into memory using the Pandas library.

... # load the dataset as a pandas DataFrame data = read_csv(filename, header=None) # retrieve numpy array dataset = data.values 1 2 3 4 5 . . . # load the dataset as a pandas DataFrame data = read_csv ( filename , header = None ) # retrieve numpy array dataset = data . values

Once loaded, we can split the columns into input (X) and output (y) for modeling.

... # split into input (X) and output (y) variables X = dataset[:, :-1] y = dataset[:,-1] 1 2 3 4 . . . # split into input (X) and output (y) variables X = dataset [ : , : - 1 ] y = dataset [ : , - 1 ]

Finally, we can force all fields in the input data to be string, just in case Pandas tried to map some automatically to numbers (it does try).

We can also reshape the output variable to be one column (e.g. a 2D shape).

... # format all fields as string X = X.astype(str) # reshape target to be a 2d array y = y.reshape((len(y), 1)) 1 2 3 4 5 . . . # format all fields as string X = X . astype ( str ) # reshape target to be a 2d array y = y . reshape ( ( len ( y ) , 1 ) )

We can tie all of this together into a helpful function that we can reuse later.

# load the dataset def load_dataset(filename): # load the dataset as a pandas DataFrame data = read_csv(filename, header=None) # retrieve numpy array dataset = data.values # split into input (X) and output (y) variables X = dataset[:, :-1] y = dataset[:,-1] # format all fields as string X = X.astype(str) # reshape target to be a 2d array y = y.reshape((len(y), 1)) return X, y 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # load the dataset def load_dataset ( filename ) : # load the dataset as a pandas DataFrame data = read_csv ( filename , header = None ) # retrieve numpy array dataset = data . values # split into input (X) and output (y) variables X = dataset [ : , : - 1 ] y = dataset [ : , - 1 ] # format all fields as string X = X . astype ( str ) # reshape target to be a 2d array y = y . reshape ( ( len ( y ) , 1 ) ) return X , y

Once loaded, we can split the data into training and test sets so that we can fit and evaluate a deep learning model.

We will use the train_test_split() function from scikit-learn and use 67% of the data for training and 33% for testing.

... # load the dataset X, y = load_dataset('breast-cancer.csv') # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1) 1 2 3 4 5 . . . # load the dataset X , y = load_dataset ( 'breast-cancer.csv' ) # split into train and test sets X_train , X_test , y_train , y_test = train_test_split ( X , y , test_size = 0.33 , random_state = 1 )

Tying all of these elements together, the complete example of loading, splitting, and summarizing the raw categorical dataset is listed below.

# load and summarize the dataset from pandas import read_csv from sklearn.model_selection import train_test_split # load the dataset def load_dataset(filename): # load the dataset as a pandas DataFrame data = read_csv(filename, header=None) # retrieve numpy array dataset = data.values # split into input (X) and output (y) variables X = dataset[:, :-1] y = dataset[:,-1] # format all fields as string X = X.astype(str) # reshape target to be a 2d array y = y.reshape((len(y), 1)) return X, y # load the dataset X, y = load_dataset('breast-cancer.csv') # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1) # summarize print('Train', X_train.shape, y_train.shape) print('Test', X_test.shape, y_test.shape) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # load and summarize the dataset from pandas import read_csv from sklearn . model_selection import train_test _ split # load the dataset def load_dataset ( filename ) : # load the dataset as a pandas DataFrame data = read_csv ( filename , header = None ) # retrieve numpy array dataset = data . values # split into input (X) and output (y) variables X = dataset [ : , : - 1 ] y = dataset [ : , - 1 ] # format all fields as string X = X . astype ( str ) # reshape target to be a 2d array y = y . reshape ( ( len ( y ) , 1 ) ) return X , y # load the dataset X , y = load_dataset ( 'breast-cancer.csv' ) # split into train and test sets X_train , X_test , y_train , y_test = train_test_split ( X , y , test_size = 0.33 , random_state = 1 ) # summarize print ( 'Train' , X_train . shape , y_train . shape ) print ( 'Test' , X_test . shape , y_test . shape )

Running the example reports the size of the input and output elements of the train and test sets.

We can see that we have 191 examples for training and 95 for testing.

Train (191, 9) (191, 1) Test (95, 9) (95, 1) 1 2 Train (191, 9) (191, 1) Test (95, 9) (95, 1)

Now that we are familiar with the dataset, let’s look at how we can encode it for modeling.

How to Ordinal Encode Categorical Data

An ordinal encoding involves mapping each unique label to an integer value.

As such, it is sometimes referred to simply as an integer encoding.

This type of encoding is really only appropriate if there is a known relationship between the categories.

This relationship does exist for some of the variables in the dataset, and ideally, this should be harnessed when preparing the data.

In this case, we will ignore any possible existing ordinal relationship and assume all variables are categorical. It can still be helpful to use an ordinal encoding, at least as a point of reference with other encoding schemes.

We can use the OrdinalEncoder() from scikit-learn to encode each variable to integers. This is a flexible class and does allow the order of the categories to be specified as arguments if any such order is known.

Note: I will leave it as an exercise for you to update the example below to try specifying the order for those variables that have a natural ordering and see if it has an impact on model performance.

The best practice when encoding variables is to fit the encoding on the training dataset, then apply it to the train and test datasets.

The function below, named prepare_inputs(), takes the input data for the train and test sets and encodes it using an ordinal encoding.

# prepare input data def prepare_inputs(X_train, X_test): oe = OrdinalEncoder() oe.fit(X_train) X_train_enc = oe.transform(X_train) X_test_enc = oe.transform(X_test) return X_train_enc, X_test_enc 1 2 3 4 5 6 7 # prepare input data def prepare_inputs ( X_train , X_test ) : oe = OrdinalEncoder ( ) oe . fit ( X_train ) X_train_enc = oe . transform ( X_train ) X_test_enc = oe . transform ( X_test ) return X_train_enc , X_test_enc

We also need to prepare the target variable.

It is a binary classification problem, so we need to map the two class labels to 0 and 1.

This is a type of ordinal encoding, and scikit-learn provides the LabelEncoder class specifically designed for this purpose. We could just as easily use the OrdinalEncoder and achieve the same result, although the LabelEncoder is designed for encoding a single variable.

The prepare_targets() integer encodes the output data for the train and test sets.

# prepare target def prepare_targets(y_train, y_test): le = LabelEncoder() le.fit(y_train) y_train_enc = le.transform(y_train) y_test_enc = le.transform(y_test) return y_train_enc, y_test_enc 1 2 3 4 5 6 7 # prepare target def prepare_targets ( y_train , y_test ) : le = LabelEncoder ( ) le . fit ( y_train ) y_train_enc = le . transform ( y_train ) y_test_enc = le . transform ( y_test ) return y_train_enc , y_test_enc

We can call these functions to prepare our data.

... # prepare input data X_train_enc, X_test_enc = prepare_inputs(X_train, X_test) # prepare output data y_train_enc, y_test_enc = prepare_targets(y_train, y_test) 1 2 3 4 5 . . . # prepare input data X_train_enc , X_test_enc = prepare_inputs ( X_train , X_test ) # prepare output data y_train_enc , y_test_enc = prepare_targets ( y_train , y_test )

We can now define a neural network model.

We will use the same general model in all of these examples. Specifically, a MultiLayer Perceptron (MLP) neural network with one hidden layer with 10 nodes, and one node in the output layer for making binary classifications.

Without going into too much detail, the code below defines the model, fits it on the training dataset, and then evaluates it on the test dataset.

... # define the model model = Sequential() model.add(Dense(10, input_dim=X_train_enc.shape[1], activation='relu', kernel_initializer='he_normal')) model.add(Dense(1, activation='sigmoid')) # compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # fit the keras model on the dataset model.fit(X_train_enc, y_train_enc, epochs=100, batch_size=16, verbose=2) # evaluate the keras model _, accuracy = model.evaluate(X_test_enc, y_test_enc, verbose=0) print('Accuracy: %.2f' % (accuracy*100)) 1 2 3 4 5 6 7 8 9 10 11 12 . . . # define the model model = Sequential ( ) model . add ( Dense ( 10 , input_dim = X_train_enc . shape [ 1 ] , activation = 'relu' , kernel_initializer = 'he_normal' ) ) model . add ( Dense ( 1 , activation = 'sigmoid' ) ) # compile the keras model model . compile ( loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = [ 'accuracy' ] ) # fit the keras model on the dataset model . fit ( X_train_enc , y_train_enc , epochs = 100 , batch_size = 16 , verbose = 2 ) # evaluate the keras model _ , accuracy = model . evaluate ( X_test_enc , y_test_enc , verbose = 0 ) print ( 'Accuracy: %.2f' % ( accuracy* 100 ) )

If you are new to developing neural networks in Keras, I recommend this tutorial:

Tying all of this together, the complete example of preparing the data with an ordinal encoding and fitting and evaluating a neural network on the data is listed below.

# example of ordinal encoding for a neural network from pandas import read_csv from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OrdinalEncoder from keras.models import Sequential from keras.layers import Dense # load the dataset def load_dataset(filename): # load the dataset as a pandas DataFrame data = read_csv(filename, header=None) # retrieve numpy array dataset = data.values # split into input (X) and output (y) variables X = dataset[:, :-1] y = dataset[:,-1] # format all fields as string X = X.astype(str) # reshape target to be a 2d array y = y.reshape((len(y), 1)) return X, y # prepare input data def prepare_inputs(X_train, X_test): oe = OrdinalEncoder() oe.fit(X_train) X_train_enc = oe.transform(X_train) X_test_enc = oe.transform(X_test) return X_train_enc, X_test_enc # prepare target def prepare_targets(y_train, y_test): le = LabelEncoder() le.fit(y_train) y_train_enc = le.transform(y_train) y_test_enc = le.transform(y_test) return y_train_enc, y_test_enc # load the dataset X, y = load_dataset('breast-cancer.csv') # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1) # prepare input data X_train_enc, X_test_enc = prepare_inputs(X_train, X_test) # prepare output data y_train_enc, y_test_enc = prepare_targets(y_train, y_test) # define the model model = Sequential() model.add(Dense(10, input_dim=X_train_enc.shape[1], activation='relu', kernel_initializer='he_normal')) model.add(Dense(1, activation='sigmoid')) # compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # fit the keras model on the dataset model.fit(X_train_enc, y_train_enc, epochs=100, batch_size=16, verbose=2) # evaluate the keras model _, accuracy = model.evaluate(X_test_enc, y_test_enc, verbose=0) print('Accuracy: %.2f' % (accuracy*100)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 # example of ordinal encoding for a neural network from pandas import read_csv from sklearn . model_selection import train_test_split from sklearn . preprocessing import LabelEncoder from sklearn . preprocessing import OrdinalEncoder from keras . models import Sequential from keras . layers import Dense # load the dataset def load_dataset ( filename ) : # load the dataset as a pandas DataFrame data = read_csv ( filename , header = None ) # retrieve numpy array dataset = data . values # split into input (X) and output (y) variables X = dataset [ : , : - 1 ] y = dataset [ : , - 1 ] # format all fields as string X = X . astype ( str ) # reshape target to be a 2d array y = y . reshape ( ( len ( y ) , 1 ) ) return X , y # prepare input data def prepare_inputs ( X_train , X_test ) : oe = OrdinalEncoder ( ) oe . fit ( X_train ) X_train_enc = oe . transform ( X_train ) X_test_enc = oe . transform ( X_test ) return X_train_enc , X_test _ enc # prepare target def prepare_targets ( y_train , y_test ) : le = LabelEncoder ( ) le . fit ( y_train ) y_train_enc = le . transform ( y_train ) y_test_enc = le . transform ( y_test ) return y_train_enc , y_test _ enc # load the dataset X , y = load_dataset ( 'breast-cancer.csv' ) # split into train and test sets X_train , X_test , y_train , y_test = train_test_split ( X , y , test_size = 0.33 , random_state = 1 ) # prepare input data X_train_enc , X_test_enc = prepare_inputs ( X_train , X_test ) # prepare output data y_train_enc , y_test_enc = prepare_targets ( y_train , y_test ) # define the model model = Sequential ( ) model . add ( Dense ( 10 , input_dim = X_train_enc . shape [ 1 ] , activation = 'relu' , kernel_initializer = 'he_normal' ) ) model . add ( Dense ( 1 , activation = 'sigmoid' ) ) # compile the keras model model . compile ( loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = [ 'accuracy' ] ) # fit the keras model on the dataset model . fit ( X_train_enc , y_train_enc , epochs = 100 , batch_size = 16 , verbose = 2 ) # evaluate the keras model _ , accuracy = model . evaluate ( X_test_enc , y_test_enc , verbose = 0 ) print ( 'Accuracy: %.2f' % ( accuracy* 100 ) )

Running the example will fit the model in just a few seconds on any modern hardware (no GPU required).

The loss and the accuracy of the model are reported at the end of each training epoch, and finally, the accuracy of the model on the test dataset is reported.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, we can see that the model achieved an accuracy of about 70% on the test dataset.

Not bad, given that an ordinal relationship only exists for some of the input variables, and for those where it does, it was not honored in the encoding.

... Epoch 95/100 - 0s - loss: 0.5349 - acc: 0.7696 Epoch 96/100 - 0s - loss: 0.5330 - acc: 0.7539 Epoch 97/100 - 0s - loss: 0.5316 - acc: 0.7592 Epoch 98/100 - 0s - loss: 0.5302 - acc: 0.7696 Epoch 99/100 - 0s - loss: 0.5291 - acc: 0.7644 Epoch 100/100 - 0s - loss: 0.5277 - acc: 0.7644 Accuracy: 70.53 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... Epoch 95/100 - 0s - loss: 0.5349 - acc: 0.7696 Epoch 96/100 - 0s - loss: 0.5330 - acc: 0.7539 Epoch 97/100 - 0s - loss: 0.5316 - acc: 0.7592 Epoch 98/100 - 0s - loss: 0.5302 - acc: 0.7696 Epoch 99/100 - 0s - loss: 0.5291 - acc: 0.7644 Epoch 100/100 - 0s - loss: 0.5277 - acc: 0.7644 Accuracy: 70.53

This provides a good starting point when working with categorical data.

A better and more general approach is to use a one hot encoding.

How to One Hot Encode Categorical Data

A one hot encoding is appropriate for categorical data where no relationship exists between categories.

It involves representing each categorical variable with a binary vector that has one element for each unique label and marking the class label with a 1 and all other elements 0.

For example, if our variable was “color” and the labels were “red,” “green,” and “blue,” we would encode each of these labels as a three-element binary vector as follows:

Red: [1, 0, 0]

Green: [0, 1, 0]

Blue: [0, 0, 1]

Then each label in the dataset would be replaced with a vector (one column becomes three). This is done for all categorical variables so that our nine input variables or columns become 43 in the case of the breast cancer dataset.

The scikit-learn library provides the OneHotEncoder to automatically one hot encode one or more variables.

The prepare_inputs() function below provides a drop-in replacement function for the example in the previous section. Instead of using an OrdinalEncoder, it uses a OneHotEncoder.

# prepare input data def prepare_inputs(X_train, X_test): ohe = OneHotEncoder() ohe.fit(X_train) X_train_enc = ohe.transform(X_train) X_test_enc = ohe.transform(X_test) return X_train_enc, X_test_enc 1 2 3 4 5 6 7 # prepare input data def prepare_inputs ( X_train , X_test ) : ohe = OneHotEncoder ( ) ohe . fit ( X_train ) X_train_enc = ohe . transform ( X_train ) X_test_enc = ohe . transform ( X_test ) return X_train_enc , X_test_enc

Tying this together, the complete example of one hot encoding the breast cancer categorical dataset and modeling it with a neural network is listed below.

# example of one hot encoding for a neural network from pandas import read_csv from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from keras.models import Sequential from keras.layers import Dense # load the dataset def load_dataset(filename): # load the dataset as a pandas DataFrame data = read_csv(filename, header=None) # retrieve numpy array dataset = data.values # split into input (X) and output (y) variables X = dataset[:, :-1] y = dataset[:,-1] # format all fields as string X = X.astype(str) # reshape target to be a 2d array y = y.reshape((len(y), 1)) return X, y # prepare input data def prepare_inputs(X_train, X_test): ohe = OneHotEncoder() ohe.fit(X_train) X_train_enc = ohe.transform(X_train) X_test_enc = ohe.transform(X_test) return X_train_enc, X_test_enc # prepare target def prepare_targets(y_train, y_test): le = LabelEncoder() le.fit(y_train) y_train_enc = le.transform(y_train) y_test_enc = le.transform(y_test) return y_train_enc, y_test_enc # load the dataset X, y = load_dataset('breast-cancer.csv') # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1) # prepare input data X_train_enc, X_test_enc = prepare_inputs(X_train, X_test) # prepare output data y_train_enc, y_test_enc = prepare_targets(y_train, y_test) # define the model model = Sequential() model.add(Dense(10, input_dim=X_train_enc.shape[1], activation='relu', kernel_initializer='he_normal')) model.add(Dense(1, activation='sigmoid')) # compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # fit the keras model on the dataset model.fit(X_train_enc, y_train_enc, epochs=100, batch_size=16, verbose=2) # evaluate the keras model _, accuracy = model.evaluate(X_test_enc, y_test_enc, verbose=0) print('Accuracy: %.2f' % (accuracy*100)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 # example of one hot encoding for a neural network from pandas import read_csv from sklearn . model_selection import train_test_split from sklearn . preprocessing import LabelEncoder from sklearn . preprocessing import OneHotEncoder from keras . models import Sequential from keras . layers import Dense # load the dataset def load_dataset ( filename ) : # load the dataset as a pandas DataFrame data = read_csv ( filename , header = None ) # retrieve numpy array dataset = data . values # split into input (X) and output (y) variables X = dataset [ : , : - 1 ] y = dataset [ : , - 1 ] # format all fields as string X = X . astype ( str ) # reshape target to be a 2d array y = y . reshape ( ( len ( y ) , 1 ) ) return X , y # prepare input data def prepare_inputs ( X_train , X_test ) : ohe = OneHotEncoder ( ) ohe . fit ( X_train ) X_train_enc = ohe . transform ( X_train ) X_test_enc = ohe . transform ( X_test ) return X_train_enc , X_test _ enc # prepare target def prepare_targets ( y_train , y_test ) : le = LabelEncoder ( ) le . fit ( y_train ) y_train_enc = le . transform ( y_train ) y_test_enc = le . transform ( y_test ) return y_train_enc , y_test _ enc # load the dataset X , y = load_dataset ( 'breast-cancer.csv' ) # split into train and test sets X_train , X_test , y_train , y_test = train_test_split ( X , y , test_size = 0.33 , random_state = 1 ) # prepare input data X_train_enc , X_test_enc = prepare_inputs ( X_train , X_test ) # prepare output data y_train_enc , y_test_enc = prepare_targets ( y_train , y_test ) # define the model model = Sequential ( ) model . add ( Dense ( 10 , input_dim = X_train_enc . shape [ 1 ] , activation = 'relu' , kernel_initializer = 'he_normal' ) ) model . add ( Dense ( 1 , activation = 'sigmoid' ) ) # compile the keras model model . compile ( loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = [ 'accuracy' ] ) # fit the keras model on the dataset model . fit ( X_train_enc , y_train_enc , epochs = 100 , batch_size = 16 , verbose = 2 ) # evaluate the keras model _ , accuracy = model . evaluate ( X_test_enc , y_test_enc , verbose = 0 ) print ( 'Accuracy: %.2f' % ( accuracy* 100 ) )

The example one hot encodes the input categorical data, and also label encodes the target variable as we did in the previous section. The same neural network model is then fit on the prepared dataset.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, the model performs reasonably well, achieving an accuracy of about 72%, close to what was seen in the previous section.

A more fair comparison would be to run each configuration 10 or 30 times and compare performance using the mean accuracy. Recall, that we are more focused on how to encode categorical data in this tutorial rather than getting the best score on this specific dataset.

... Epoch 95/100 - 0s - loss: 0.3837 - acc: 0.8272 Epoch 96/100 - 0s - loss: 0.3823 - acc: 0.8325 Epoch 97/100 - 0s - loss: 0.3814 - acc: 0.8325 Epoch 98/100 - 0s - loss: 0.3795 - acc: 0.8325 Epoch 99/100 - 0s - loss: 0.3788 - acc: 0.8325 Epoch 100/100 - 0s - loss: 0.3773 - acc: 0.8325 Accuracy: 72.63 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... Epoch 95/100 - 0s - loss: 0.3837 - acc: 0.8272 Epoch 96/100 - 0s - loss: 0.3823 - acc: 0.8325 Epoch 97/100 - 0s - loss: 0.3814 - acc: 0.8325 Epoch 98/100 - 0s - loss: 0.3795 - acc: 0.8325 Epoch 99/100 - 0s - loss: 0.3788 - acc: 0.8325 Epoch 100/100 - 0s - loss: 0.3773 - acc: 0.8325 Accuracy: 72.63

Ordinal and one hot encoding are perhaps the two most popular methods.

A newer technique is similar to one hot encoding and was designed for use with neural networks, called a learned embedding.

How to Use a Learned Embedding for Categorical Data

A learned embedding, or simply an “embedding,” is a distributed representation for categorical data.

Each category is mapped to a distinct vector, and the properties of the vector are adapted or learned while training a neural network. The vector space provides a projection of the categories, allowing those categories that are close or related to cluster together naturally.

This provides both the benefits of an ordinal relationship by allowing any such relationships to be learned from data, and a one hot encoding in providing a vector representation for each category. Unlike one hot encoding, the input vectors are not sparse (do not have lots of zeros). The downside is that it requires learning as part of the model and the creation of many more input variables (columns).

The technique was originally developed to provide a distributed representation for words, e.g. allowing similar words to have similar vector representations. As such, the technique is often referred to as a word embedding, and in the case of text data, algorithms have been developed to learn a representation independent of a neural network. For more on this topic, see the post:

An additional benefit of using an embedding is that the learned vectors that each category is mapped to can be fit in a model that has modest skill, but the vectors can be extracted and used generally as input for the category on a range of different models and applications. That is, they can be learned and reused.

Embeddings can be used in Keras via the Embedding layer.

For an example of learning word embeddings for text data in Keras, see the post:

One embedding layer is required for each categorical variable, and the embedding expects the categories to be ordinal encoded, although no relationship between the categories is assumed.

Each embedding also requires the number of dimensions to use for the distributed representation (vector space). It is common in natural language applications to use 50, 100, or 300 dimensions. For our small example, we will fix the number of dimensions at 10, but this is arbitrary; you should experimenter with other values.

First, we can prepare the input data using an ordinal encoding.

The model we will develop will have one separate embedding for each input variable. Therefore, the model will take nine different input datasets. As such, we will split the input variables and ordinal encode (integer encoding) each separately using the LabelEncoder and return a list of separate prepared train and test input datasets.

The prepare_inputs() function below implements this, enumerating over each input variable, integer encoding each correctly using best practices, and returning lists of encoded train and test variables (or one-variable datasets) that can be used as input for our model later.

# prepare input data def prepare_inputs(X_train, X_test): X_train_enc, X_test_enc = list(), list() # label encode each column for i in range(X_train.shape[1]): le = LabelEncoder() le.fit(X_train[:, i]) # encode train_enc = le.transform(X_train[:, i]) test_enc = le.transform(X_test[:, i]) # store X_train_enc.append(train_enc) X_test_enc.append(test_enc) return X_train_enc, X_test_enc 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # prepare input data def prepare_inputs ( X_train , X_test ) : X_train_enc , X_test_enc = list ( ) , list ( ) # label encode each column for i in range ( X_train . shape [ 1 ] ) : le = LabelEncoder ( ) le . fit ( X_train [ : , i ] ) # encode train_enc = le . transform ( X_train [ : , i ] ) test_enc = le . transform ( X_test [ : , i ] ) # store X_train_enc . append ( train_enc ) X_test_enc . append ( test_enc ) return X_train_enc , X_test_enc

Now we can construct the model.

We must construct the model differently in this case because we will have nine input layers, with nine embeddings the outputs of which (the nine different 10-element vectors) need to be concatenated into one long vector before being passed as input to the dense layers.

We can achieve this using the functional Keras API. If you are new to the Keras functional API, see the post:

First, we can enumerate each variable and construct an input layer and connect it to an embedding layer, and store both layers in lists. We need a reference to all of the input layers when defining the model, and we need a reference to each embedding layer to concentrate them with a merge layer.

... # prepare each input head in_layers = list() em_layers = list() for i in range(len(X_train_enc)): # calculate the number of unique inputs n_labels = len(unique(X_train_enc[i])) # define input layer in_layer = Input(shape=(1,)) # define embedding layer em_layer = Embedding(n_labels, 10)(in_layer) # store layers in_layers.append(in_layer) em_layers.append(em_layer) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 . . . # prepare each input head in_layers = list ( ) em_layers = list ( ) for i in range ( len ( X_train_enc ) ) : # calculate the number of unique inputs n_labels = len ( unique ( X_train_enc [ i ] ) ) # define input layer in_layer = Input ( shape = ( 1 , ) ) # define embedding layer em_layer = Embedding ( n_labels , 10 ) ( in_layer ) # store layers in_layers . append ( in_layer ) em_layers . append ( em_layer )

We can then merge all of the embedding layers, define the hidden layer and output layer, then define the model.

... # concat all embeddings merge = concatenate(em_layers) dense = Dense(10, activation='relu', kernel_initializer='he_normal')(merge) output = Dense(1, activation='sigmoid')(dense) model = Model(inputs=in_layers, outputs=output) 1 2 3 4 5 6 . . . # concat all embeddings merge = concatenate ( em_layers ) dense = Dense ( 10 , activation = 'relu' , kernel_initializer = 'he_normal' ) ( merge ) output = Dense ( 1 , activation = 'sigmoid' ) ( dense ) model = Model ( inputs = in_layers , outputs = output )

When using a model with multiple inputs, we will need to specify a list that has one dataset for each input, e.g. a list of nine arrays each with one column in the case of our dataset. Thankfully, this is the format we returned from our prepare_inputs() function.

Therefore, fitting and evaluating the model looks like it does in the previous section.

Additionally, we will plot the model by calling the plot_model() function and save it to file. This requires that pygraphviz and pydot are installed, which can be a pain on some systems. If you have trouble, just comment out the import statement and call to plot_model().

... # compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # plot graph plot_model(model, show_shapes=True, to_file='embeddings.png') # fit the keras model on the dataset model.fit(X_train_enc, y_train_enc, epochs=20, batch_size=16, verbose=2) # evaluate the keras model _, accuracy = model.evaluate(X_test_enc, y_test_enc, verbose=0) print('Accuracy: %.2f' % (accuracy*100)) 1 2 3 4 5 6 7 8 9 10 . . . # compile the keras model model . compile ( loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = [ 'accuracy' ] ) # plot graph plot_model ( model , show_shapes = True , to_file = 'embeddings.png' ) # fit the keras model on the dataset model . fit ( X_train_enc , y_train_enc , epochs = 20 , batch_size = 16 , verbose = 2 ) # evaluate the keras model _ , accuracy = model . evaluate ( X_test_enc , y_test_enc , verbose = 0 ) print ( 'Accuracy: %.2f' % ( accuracy* 100 ) )

Tying this all together, the complete example of using a separate embedding for each categorical input variable in a multi-input layer model is listed below.

# example of learned embedding encoding for a neural network from numpy import unique from pandas import read_csv from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras.layers import Embedding from keras.layers.merge import concatenate from keras.utils import plot_model # load the dataset def load_dataset(filename): # load the dataset as a pandas DataFrame data = read_csv(filename, header=None) # retrieve numpy array dataset = data.values # split into input (X) and output (y) variables X = dataset[:, :-1] y = dataset[:,-1] # format all fields as string X = X.astype(str) # reshape target to be a 2d array y = y.reshape((len(y), 1)) return X, y # prepare input data def prepare_inputs(X_train, X_test): X_train_enc, X_test_enc = list(), list() # label encode each column for i in range(X_train.shape[1]): le = LabelEncoder() le.fit(X_train[:, i]) # encode train_enc = le.transform(X_train[:, i]) test_enc = le.transform(X_test[:, i]) # store X_train_enc.append(train_enc) X_test_enc.append(test_enc) return X_train_enc, X_test_enc # prepare target def prepare_targets(y_train, y_test): le = LabelEncoder() le.fit(y_train) y_train_enc = le.transform(y_train) y_test_enc = le.transform(y_test) return y_train_enc, y_test_enc # load the dataset X, y = load_dataset('breast-cancer.csv') # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1) # prepare input data X_train_enc, X_test_enc = prepare_inputs(X_train, X_test) # prepare output data y_train_enc, y_test_enc = prepare_targets(y_train, y_test) # make output 3d y_train_enc = y_train_enc.reshape((len(y_train_enc), 1, 1)) y_test_enc = y_test_enc.reshape((len(y_test_enc), 1, 1)) # prepare each input head in_layers = list() em_layers = list() for i in range(len(X_train_enc)): # calculate the number of unique inputs n_labels = len(unique(X_train_enc[i])) # define input layer in_layer = Input(shape=(1,)) # define embedding layer em_layer = Embedding(n_labels, 10)(in_layer) # store layers in_layers.append(in_layer) em_layers.append(em_layer) # concat all embeddings merge = concatenate(em_layers) dense = Dense(10, activation='relu', kernel_initializer='he_normal')(merge) output = Dense(1, activation='sigmoid')(dense) model = Model(inputs=in_layers, outputs=output) # compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # plot graph plot_model(model, show_shapes=True, to_file='embeddings.png') # fit the keras model on the dataset model.fit(X_train_enc, y_train_enc, epochs=20, batch_size=16, verbose=2) # evaluate the keras model _, accuracy = model.evaluate(X_test_enc, y_test_enc, verbose=0) print('Accuracy: %.2f' % (accuracy*100)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 # example of learned embedding encoding for a neural network from numpy import unique from pandas import read_csv from sklearn . model_selection import train_test_split from sklearn . preprocessing import LabelEncoder from keras . models import Model from keras . layers import Input from keras . layers import Dense from keras . layers import Embedding from keras . layers . merge import concatenate from keras . utils import plot _ model # load the dataset def load_dataset ( filename ) : # load the dataset as a pandas DataFrame data = read_csv ( filename , header = None ) # retrieve numpy array dataset = data . values # split into input (X) and output (y) variables X = dataset [ : , : - 1 ] y = dataset [ : , - 1 ] # format all fields as string X = X . astype ( str ) # reshape target to be a 2d array y = y . reshape ( ( len ( y ) , 1 ) ) return X , y # prepare input data def prepare_inputs ( X_train , X_test ) : X_train_enc , X_test_enc = list ( ) , list ( ) # label encode each column for i in range ( X_train . shape [ 1 ] ) : le = LabelEncoder ( ) le . fit ( X_train [ : , i ] ) # encode train_enc = le . transform ( X_train [ : , i ] ) test_enc = le . transform ( X_test [ : , i ] ) # store X_train_enc . append ( train_enc ) X_test_enc . append ( test_enc ) return X_train_enc , X_test _ enc # prepare target def prepare_targets ( y_train , y_test ) : le = LabelEncoder ( ) le . fit ( y_train ) y_train_enc = le . transform ( y_train ) y_test_enc = le . transform ( y_test ) return y_train_enc , y_test _ enc # load the dataset X , y = load_dataset ( 'breast-cancer.csv' ) # split into train and test sets X_train , X_test , y_train , y_test = train_test_split ( X , y , test_size = 0.33 , random_state = 1 ) # prepare input data X_train_enc , X_test_enc = prepare_inputs ( X_train , X_test ) # prepare output data y_train_enc , y_test_enc = prepare_targets ( y_train , y_test ) # make output 3d y_train_enc = y_train_enc . reshape ( ( len ( y_train_enc ) , 1 , 1 ) ) y_test_enc = y_test_enc . reshape ( ( len ( y_test_enc ) , 1 , 1 ) ) # prepare each input head in_layers = list ( ) em_layers = list ( ) for i in range ( len ( X_train_enc ) ) : # calculate the number of unique inputs n_labels = len ( unique ( X_train_enc [ i ] ) ) # define input layer in_layer = Input ( shape = ( 1 , ) ) # define embedding layer em_layer = Embedding ( n_labels , 10 ) ( in_layer ) # store layers in_layers . append ( in_layer ) em_layers . append ( em_layer ) # concat all embeddings merge = concatenate ( em_layers ) dense = Dense ( 10 , activation = 'relu' , kernel_initializer = 'he_normal' ) ( merge ) output = Dense ( 1 , activation = 'sigmoid' ) ( dense ) model = Model ( inputs = in_layers , outputs = output ) # compile the keras model model . compile ( loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = [ 'accuracy' ] ) # plot graph plot_model ( model , show_shapes = True , to_file = 'embeddings.png' ) # fit the keras model on the dataset model . fit ( X_train_enc , y_train_enc , epochs = 20 , batch_size = 16 , verbose = 2 ) # evaluate the keras model _ , accuracy = model . evaluate ( X_test_enc , y_test_enc , verbose = 0 ) print ( 'Accuracy: %.2f' % ( accuracy* 100 ) )

Running the example prepares the data as described above, fits the model, and reports the performance.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, the model performs reasonably well, matching what we saw for the one hot encoding in the previous section.

As the learned vectors were trained in a skilled model, it is possible to save them and use them as a general representation for these variables in other models that operate on the same data. A useful and compelling reason to explore this encoding.

... Epoch 15/20 - 0s - loss: 0.4891 - acc: 0.7696 Epoch 16/20 - 0s - loss: 0.4845 - acc: 0.7749 Epoch 17/20 - 0s - loss: 0.4783 - acc: 0.7749 Epoch 18/20 - 0s - loss: 0.4763 - acc: 0.7906 Epoch 19/20 - 0s - loss: 0.4696 - acc: 0.7906 Epoch 20/20 - 0s - loss: 0.4660 - acc: 0.7958 Accuracy: 72.63 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... Epoch 15/20 - 0s - loss: 0.4891 - acc: 0.7696 Epoch 16/20 - 0s - loss: 0.4845 - acc: 0.7749 Epoch 17/20 - 0s - loss: 0.4783 - acc: 0.7749 Epoch 18/20 - 0s - loss: 0.4763 - acc: 0.7906 Epoch 19/20 - 0s - loss: 0.4696 - acc: 0.7906 Epoch 20/20 - 0s - loss: 0.4660 - acc: 0.7958 Accuracy: 72.63

To confirm our understanding of the model, a plot is created and saved to the file embeddings.png in the current working directory.

The plot shows the nine inputs each mapped to a 10 element vector, meaning that the actual input to the model is a 90 element vector.

Note: Click to the image to see the large version.

Common Questions

This section lists some common questions and answers when encoding categorical data.

Q. What if I have a mixture of numeric and categorical data?

Or, what if I have a mixture of categorical and ordinal data?

You will need to prepare or encode each variable (column) in your dataset separately, then concatenate all of the prepared variables back together into a single array for fitting or evaluating the model.

Q. What if I have hundreds of categories?

Or, what if I concatenate many one hot encoded vectors to create a many thousand element input vector?

You can use a one hot encoding up to thousands and tens of thousands of categories. Also, having large vectors as input sounds intimidating, but the models can generally handle it.

Try an embedding; it offers the benefit of a smaller vector space (a projection) and the representation can have more meaning.

Q. What encoding technique is the best?

This is unknowable.

Test each technique (and more) on your dataset with your chosen model and discover what works best for your case.

Further Reading

This section provides more resources on the topic if you are looking to go deeper.

Posts

API

Dataset

Summary

In this tutorial, you discovered how to encode categorical data when developing neural network models in Keras.

Specifically, you learned:

The challenge of working with categorical data when using machine learning and deep learning models.

How to integer encode and one hot encode categorical variables for modeling.

How to learn an embedding distributed representation as part of a neural network for categorical variables.

Do you have any questions?

Ask your questions in the comments below and I will do my best to answer.

Develop Deep Learning Projects with Python! What If You Could Develop A Network in Minutes ...with just a few lines of Python Discover how in my new Ebook:

Deep Learning With Python It covers end-to-end projects on topics like:

Multilayer Perceptrons, Convolutional Nets and Recurrent Neural Nets, and more... Finally Bring Deep Learning To

Your Own Projects Skip the Academics. Just Results. See What's Inside