ML: Keras multiple input multiple output

https://colab.research.google.com/drive/1ZNLC7QMG0Y2Zf4evf6JG_L0rybzmscoj#scrollTo=lwm64LEEt5NX

Models with multiple inputs and outputs

The functional API makes it easy to manipulate multiple inputs and outputs. This cannot be handled with the Sequential API.

For example, if you’re building a system for ranking customer issue tickets by priority and routing them to the correct department, then the model will have three inputs:

  • the title of the ticket (text input),
  • the text body of the ticket (text input), and
  • any tags added by the user (categorical input)

This model will have two outputs:

  • the priority score between 0 and 1 (scalar sigmoid output), and
  • the department that should handle the ticket (softmax output over the set of departments).

num_tags = 12  # Number of unique issue tagsnum_words = 10000  # Size of vocabulary obtained when preprocessing text datanum_departments = 4  # Number of departments for predictions
title_input = keras.Input(    shape=(None,), name=”title”)  # Variable-length sequence of intsbody_input = keras.Input(shape=(None,), name=”body”)  # Variable-length sequence of intstags_input = keras.Input(    shape=(num_tags,), name=”tags”)  # Binary vectors of size `num_tags`
# Embed each word in the title into a 64-dimensional vectortitle_features = layers.Embedding(num_words, 64)(title_input)# Embed each word in the text into a 64-dimensional vectorbody_features = layers.Embedding(num_words, 64)(body_input)
# Reduce sequence of embedded words in the title into a single 128-dimensional vectortitle_features = layers.LSTM(128)(title_features)# Reduce sequence of embedded words in the body into a single 32-dimensional vectorbody_features = layers.LSTM(32)(body_features)
# Merge all available features into a single large vector via concatenationx = layers.concatenate([title_features, body_features, tags_input])
# Stick a logistic regression for priority prediction on top of the featurespriority_pred = layers.Dense(1, name=”priority”)(x)# Stick a department classifier on top of the featuresdepartment_pred = layers.Dense(num_departments, name=”department”)(x)
# Instantiate an end-to-end model predicting both priority and departmentmodel = keras.Model(    inputs=[title_input, body_input, tags_input],    outputs=[priority_pred, department_pred],)

You can build this model in a few lines with the functional API: