Angad Sandhu
Search
Browse
On this page

exercise-question

Open In Colab

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Multiple Output Models using Keras Functional API

Use keras functional API to train a network to predict two different outputs. For this example you will use the Wine Quality Dataset from the UCI machine learning repository. It has separate datasets for red wine and white wine.

Normally the wines are classified into one of the quality ratings specified in the attributes. In our example you will combine the two datasets so to predict the wine quality and whether the wine is red or white solely from the attributes.

You will model wine quality estimations as a regression problem and wine type detection as a binary classification problem.

Imports

try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass
  
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input

import numpy as np
import matplotlib.pyplot as plt
import polars as pl
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools


Load Dataset

Here is where you can download the data for the wines.

You will add a new column named 'is_red' in our dataframe to indicate if the wine is white or red.

In the white wine datset you will fill the column 'is_red' with zeros and in the red wine dataset you will fill it with ones.

Polars (pip install polars) keeps an explicit source_row for the original row-label alcohol demonstrations. Deduplication keeps the first record in source order, excluding that bookkeeping column. It is removed before combining/model inputs.

URL = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv'
white_df = pl.read_csv(URL, separator=";", infer_schema_length=None).with_row_index("source_row")
white_df = white_df.with_columns(pl.lit(# YOUR CODE HERE, dtype=pl.Int64).alias("is_red"))
white_df = white_df.fill_nan(None).unique(
    subset=[name for name in white_df.columns if name != "source_row"],
    keep="first", maintain_order=True)
print(white_df.filter(pl.col("source_row") == 0)["alcohol"].item())
print(white_df.filter(pl.col("source_row") == 100)["alcohol"].item())
#EXPECTED OUTPUT
#8.8
#9.1
URL = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'
red_df = pl.read_csv(URL, separator=";", infer_schema_length=None).with_row_index("source_row")
red_df = red_df.with_columns(pl.lit(# YOUR CODE HERE, dtype=pl.Int64).alias("is_red"))
red_df = red_df.fill_nan(None).unique(
    subset=[name for name in red_df.columns if name != "source_row"],
    keep="first", maintain_order=True)
print(red_df.filter(pl.col("source_row") == 0)["alcohol"].item())
print(red_df.filter(pl.col("source_row") == 100)["alcohol"].item())
#EXPECTED OUTPUT
#9.4
#10.2

Next, the two datasets will be concatenated.

df = pl.concat([red_df.drop("source_row"), white_df.drop("source_row")])
print(df["alcohol"][0])
print(df["alcohol"][100])
#EXPECTED OUTPUT
#9.4
#9.5
# NOTE: In a real-world scenario you should shuffle the data
# YOU ARE NOT going to do that here, because we want to test
# with deterministic data. But if you want the code to do it
# it's in the commented line below:

#df = df[np.random.permutation(df.height).tolist()]

This will chart the quality of the wines

plt.hist(df["quality"].drop_nulls().drop_nans().to_numpy(), bins=20)

We can see from the plot above that wine quality dataset is imbalanced. Since there are very few observations with quality 3, 4, 8 and 9, you can drop these observations from our dataset. You can do this by removing data belonging all classes except those >4 and <8

df = df.filter((pl.col("quality") > # YOUR CODE HERE) & (pl.col("quality") < # YOUR CODE HERE))
print(df["alcohol"][0])
print(df["alcohol"][100])
#EXPECTED OUTPUT
#9.4
#10.9

You can plot again to see the new range of data and quality

plt.hist(df["quality"].drop_nulls().drop_nans().to_numpy(), bins=20)

Next you can split the datasets into training, test and validation datasets.

The data frame should be split 80:20 into train and test

The resulting train should then be split 80:20 into train and validation

train_rows, test_rows = train_test_split(# YOUR CODE HERE)
train, test = df[train_rows], df[test_rows]
train_rows, val_rows = train_test_split(# YOUR CODE HERE)
train, val = train[train_rows], train[val_rows]
print(train.height * train.width)
print(test.height * test.width)
print(val.height * val.width)

#EXPECTED OUTPUT
# 41015
# 12831
# 10257

Compute training-only means and sample standard deviations (ddof=1) for the ordered feature columns. Keep 'quality' and 'is_red' out of these statistics and model inputs. Keyed statistics explicitly match each feature by name.

FEATURES = [name for name in train.columns if name not in ('quality', 'is_red')]
train_stats = {
  'mean': train.select(pl.col(FEATURES).fill_nan(None).mean()).row(0, named=True),
  'std': train.select(pl.col(FEATURES).fill_nan(None).std(ddof=1)).row(0, named=True),
}

Explore the training stats!

train_stats

Select the quality and type columns as separate NumPy arrays without mutating the feature data. Do this for the train, validation and test datasets.

def format_output(data):
  quality = data['quality'].to_numpy()
  is_red = data['is_red'].to_numpy()
  return (quality, is_red)
train_Y = format_output(# YOUR CODE HERE)
val_Y = format_output(# YOUR CODE HERE)
test_Y = format_output(# YOUR CODE HERE)

Normalize each feature with training-only statistics: (X - training mean) / training sample standard deviation. The ordered NumPy matrix contains features only; null/NaN values remain missing.

def norm(x):
  return x.select([
    (pl.col(name) - train_stats['mean'][name]) / train_stats['std'][name]
    for name in FEATURES
  ]).to_numpy()
norm_train_X = norm(# YOUR CODE HERE)
norm_val_X = norm(# YOUR CODE HERE)
norm_test_X = norm(# YOUR CODE HERE)

Defining the Model

Define the model using the functional API. The base model will simply be 2 dense layers of 128 neurons each.

def base_model(inputs):
  x = # YOUR CODE HERE
  x = # YOUR CODE HERE
  return x
  

The final model will need two outputs.

Add output layers to the base model for wine quality output.

The first, for wine quality will be a dense layer with 1 neuron that will be used for classification.

The other, for wine type will be a dense layer with 1 neuron that will be used for regression (and thus activated by sigmoid)

def final_model(inputs):
  x = base_model(inputs)
  
  wine_quality = Dense('1', name = 'wine_quality')(x)
  wine_type = Dense(units = '1', activation = # YOUR CODE HERE, name = 'wine_type')(x)
  
  model = Model(inputs = # YOUR CODE HERE, outputs = # YOUR CODE HERE)
  
  return model

Compiling the Model

Next, compile the model. Use different loss functions for the two outputs.

Since you will performing binary classification on wine type, you should use the binary crossentropy loss function for it.

As wine quality is a regression, you should use mean squared error as its loss function.

Similarly, you should also specify the metrics for two different outputs. Use RMSE for wine quality and accuracy for wine type

inputs = tf.keras.layers.Input(shape=(11,))
rms = tf.keras.optimizers.RMSprop(lr=0.0001)
model = final_model(inputs)
model.compile(optimizer=rms, 
              loss = {'wine_type' : # YOUR CODE HERE,
                      'wine_quality' : # YOUR CODE HERE
                     },
              metrics = {'wine_type' : # YOUR CODE HERE,
                         'wine_quality': # YOUR CODE HERE
                       }
             )

Training the Model

Fit the model to the training inputs and outputs. Train for 180 epochs.

history = model.fit(# YOUR CODE HERE, # YOUR CODE HERE,
                    epochs = 180, validation_data=(# YOUR CODE HERE, # YOUR CODE HERE))

Gather the training metrics

loss, wine_quality_loss, wine_type_loss, wine_quality_rmse, wine_type_accuracy = model.evaluate(x=norm_val_X, y=val_Y)

print(loss)
print(wine_quality_loss)
print(wine_type_loss)
print(wine_quality_rmse)
print(wine_type_accuracy)
# EXPECTED VALUES
# ~ 0.34 - 0.38
# ~ 0.34 - 0.38
# ~ 0.018 - 0.022
# ~ 0.56 - 0.62
# ~ 0.97 - 1.0
# Example:
#0.3657050132751465
#0.3463745415210724
#0.019330406561493874
#0.5885359048843384
#0.9974651336669922

Analyze the Model Performance

Note that the model has two outputs. The output at index 0 is quality and index 1 is wine type

So, round the quality predictions to the nearest integer.

predictions = model.predict(norm_test_X)
quality_pred = predictions[0]
type_pred = predictions[1]
print(quality_pred[0])
# EXPECTED OUTPUT
# 5.6 - 6.0
print(type_pred[0])
print(type_pred[946])
# EXPECTED OUTPUT
# A number close to zero
# A number close to or equal to 1

Plot Utilities

def plot_metrics(metric_name, title, ylim=5):
  plt.title(title)
  plt.ylim(0,ylim)
  plt.plot(history.history[metric_name],color='blue',label=metric_name)
  plt.plot(history.history['val_' + metric_name],color='green',label='val_' + metric_name)
def plot_confusion_matrix(y_true, y_pred, title='', labels=[0,1]):
  cm = confusion_matrix(y_true, y_pred)
  fig = plt.figure()
  ax = fig.add_subplot(111)
  cax = ax.matshow(cm)
  plt.title('Confusion matrix of the classifier')
  fig.colorbar(cax)
  ax.set_xticklabels([''] + labels)
  ax.set_yticklabels([''] + labels)
  plt.xlabel('Predicted')
  plt.ylabel('True')
  fmt = 'd'
  thresh = cm.max() / 2.
  for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
          plt.text(j, i, format(cm[i, j], fmt),
                  horizontalalignment="center",
                  color="black" if cm[i, j] > thresh else "white")
  plt.show()
def plot_diff(y_true, y_pred, title = '' ):
  plt.scatter(y_true, y_pred)
  plt.title(title)
  plt.xlabel('True Values')
  plt.ylabel('Predictions')
  plt.axis('equal')
  plt.axis('square')
  plt.plot([-100, 100], [-100, 100])
  return plt

Plots for Metrics

plot_metrics('wine_quality_root_mean_squared_error', 'RMSE', ylim=2)
plot_metrics('wine_type_loss', 'Wine Type Loss', ylim=0.2)

Plots for Confusion Matrix

Plot the confusion matrices for wine type. You can see that the model performs well for prediction of wine type from the confusion matrix and the loss metrics.

plot_confusion_matrix(test_Y[1], np.round(type_pred), title='Wine Type', labels = [0, 1])
scatter_plot = plot_diff(test_Y[0], quality_pred, title='Type')

Browse the library