MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Tensorsflow Lab8 – Tensorsflow FunctionalModel

This lab uses the UCI heart disease dataset (303 patients, 13 features, a binary target) to build a binary classifier with the Keras Functional API in TensorFlow. The notebook above covers loading and exploring the data. The sections below finish the job: preprocessing, defining a functional model, training, evaluating, and a two-input model that shows what the Functional API can do that Sequential cannot.


What the Functional API is and when to use it

Keras gives you three ways to define a model: Sequential (a plain stack of layers), the Functional API, and subclassing keras.Model. With the Functional API you treat each layer as a function. You call it on a tensor and get a tensor back, then build a keras.Model from the input and output tensors. The result is a graph of layers rather than a single straight line, so it can have several inputs, several outputs, shared layers and skip connections.

NeedSequentialFunctional API
Single input, single output, linear stackYesYes
Multiple inputs (for example numeric and categorical branches)NoYes
Multiple outputs or auxiliary lossesNoYes
Skip or residual connections, shared layersNoYes
Readable summary and plot of the whole graphPartialYes

Tabular data like the heart dataset is a good place to learn the API, because the model is small and you can quickly move from one input to two.

Prerequisites and setup

  • Python 3.9 or later and a recent TensorFlow 2.x release. Recent releases bundle Keras 3, and every call below works in both Keras 2 and Keras 3.
  • pandas, numpy, scikit-learn, matplotlib and seaborn.
  • The heart disease CSV from Kaggle, saved as datasets/heart.csv relative to the notebook, because that is the path the notebook reads from.
python -m venv tf-lab
source tf-lab/bin/activate
pip install tensorflow pandas numpy scikit-learn matplotlib seaborn jupyter
mkdir -p datasets   # place heart.csv here
python -c "import tensorflow as tf; print(tf.__version__)"Code language: PHP (php)

Corrections to the notebook above

In current seaborn releases the countplot cell fails. Since seaborn 0.12, plotting variables have to be passed as keyword arguments, so sns.countplot('sex', hue='target', data=df) raises a TypeError. Pass x= explicitly:

sns.countplot(x='sex', hue='target', data=df)
plt.title('Heart Disease Frequency for Gender')
plt.legend(['No Disease', 'Yes Disease'])
plt.xlabel('Gender (0 = Female, 1 = Male)')
plt.ylabel('Frequency')
plt.show()Code language: JavaScript (javascript)

The column notes also don't match the data. thal is described as 3, 6 or 7, but df.describe() above shows values from 0 to 3. ca is described as 0 to 3, but its maximum is 4. This version of the dataset re-encodes these columns, and the thal = 0 and ca = 4 rows are generally treated as placeholders for missing values. Treat both columns as categories, not measurements, and consider dropping or imputing those few rows.

Note: In recent pandas versions, value_counts() labels its output Name: count instead of Name: sex. The counts are the same, so this is not an error.

Prepare the data for training

First split the data, then scale it. Fit the StandardScaler on the training set only, so no statistics from the test set leak into training. Using stratify keeps the roughly 54/46 class balance the same in both splits.

X = df.drop('target', axis=1)
y = df['target']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)

print(X_train_s.shape, X_test_s.shape)   # (242, 13) (61, 13)Code language: PHP (php)

Build the functional model

Start from a keras.Input and call each layer on the output of the previous one. Then wrap the input and output tensors in keras.Model. Use a single sigmoid unit with binary_crossentropy for a 0/1 target.

tf.random.set_seed(42)

def build_model(n_features):
    inputs = keras.Input(shape=(n_features,), name='features')
    x = layers.Dense(16, activation='relu')(inputs)
    x = layers.Dropout(0.3)(x)
    x = layers.Dense(8, activation='relu')(x)
    outputs = layers.Dense(1, activation='sigmoid', name='disease')(x)

    model = keras.Model(inputs=inputs, outputs=outputs, name='heart_functional')
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=0.001),
        loss='binary_crossentropy',
        metrics=['accuracy',
                 keras.metrics.Precision(name='precision'),
                 keras.metrics.Recall(name='recall')])
    return model

model = build_model(X_train_s.shape[1])
model.summary()Code language: JavaScript (javascript)

model.summary() should list an input layer, two Dense layers, a Dropout layer and the output layer, for 369 trainable parameters: 13ร—16+16, plus 16ร—8+8, plus 8+1. The dropout layer guards against overfitting, which happens quickly on a dataset this small.

Train with early stopping and TensorBoard

The notebook imports datetime, which is useful for giving each TensorBoard run its own log directory. EarlyStopping stops training when validation loss stops improving and restores the best weights.

log_dir = 'logs/fit/' + datetime.now().strftime('%Y%m%d-%H%M%S')

callbacks = [
    keras.callbacks.EarlyStopping(monitor='val_loss', patience=15,
                                  restore_best_weights=True),
    keras.callbacks.TensorBoard(log_dir=log_dir)
]

history = model.fit(X_train_s, y_train,
                    validation_split=0.2,
                    epochs=200,
                    batch_size=16,
                    callbacks=callbacks,
                    verbose=0)

pd.DataFrame(history.history)[['loss', 'val_loss']].plot()
plt.xlabel('Epoch')
plt.show()Code language: PHP (php)

To compare runs, start TensorBoard with tensorboard --logdir logs/fit. If validation loss rises while training loss keeps falling, the model is overfitting. Raise the dropout rate, use fewer units, or add L2 regularisation.

Evaluate on the test set

predict returns probabilities. Apply a threshold to turn them into class labels, then use the scikit-learn metrics imported at the top of the notebook.

model.evaluate(X_test_s, y_test, verbose=0)

y_prob = model.predict(X_test_s).ravel()
y_pred = (y_prob > 0.5).astype(int)

print('Accuracy :', accuracy_score(y_test, y_pred))
print('Precision:', precision_score(y_test, y_pred))
print('Recall   :', recall_score(y_test, y_pred))Code language: PHP (php)

The test set has only 61 rows, so a single misclassification shifts accuracy by more than a percentage point. Results vary between seeds and splits. For a more reliable estimate, use cross-validation. In a screening scenario, recall (patients with the disease that the model catches) usually matters more than precision. Lowering the threshold below 0.5 trades precision for recall.

Going further: a two-input functional model

Sequential cannot build a model with separate branches. The model below feeds the continuous measurements and the one-hot encoded categorical columns through their own Dense layers, then joins them with Concatenate.

num_cols = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']
cat_cols = ['sex', 'cp', 'fbs', 'restecg', 'exang', 'slope', 'ca', 'thal']

cat_all = pd.get_dummies(df[cat_cols].astype(str), dtype=float)
tr_idx, te_idx = train_test_split(df.index, test_size=0.2,
                                  random_state=42, stratify=df['target'])

num_scaler = StandardScaler()
Xn_tr = num_scaler.fit_transform(df.loc[tr_idx, num_cols])
Xn_te = num_scaler.transform(df.loc[te_idx, num_cols])
Xc_tr, Xc_te = cat_all.loc[tr_idx].values, cat_all.loc[te_idx].values
yt, yv = df.loc[tr_idx, 'target'].values, df.loc[te_idx, 'target'].values

num_in = keras.Input(shape=(len(num_cols),), name='numeric')
cat_in = keras.Input(shape=(cat_all.shape[1],), name='categorical')

n = layers.Dense(8, activation='relu')(num_in)
c = layers.Dense(8, activation='relu')(cat_in)
x = layers.Concatenate()([n, c])
x = layers.Dropout(0.3)(x)
x = layers.Dense(8, activation='relu')(x)
out = layers.Dense(1, activation='sigmoid', name='disease')(x)

multi = keras.Model(inputs=[num_in, cat_in], outputs=out, name='heart_two_input')
multi.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

multi.fit({'numeric': Xn_tr, 'categorical': Xc_tr}, yt,
          validation_split=0.2, epochs=200, batch_size=16, verbose=0,
          callbacks=[keras.callbacks.EarlyStopping(patience=15,
                                                   restore_best_weights=True)])
print(multi.evaluate({'numeric': Xn_te, 'categorical': Xc_te}, yv, verbose=0))Code language: PHP (php)

The dictionary keys passed to fit and evaluate must match the name given to each keras.Input. One-hot encoding is done once on the full DataFrame so the train and test splits get the same columns. It learns nothing from the target, so it does not leak information. To see the branching graph, run keras.utils.plot_model(multi, show_shapes=True), which needs the pydot package and the Graphviz binaries.

Save, reload and troubleshoot

model.save('heart_functional.keras')
restored = keras.models.load_model('heart_functional.keras')

import joblib
joblib.dump(scaler, 'heart_scaler.joblib')   # inputs must be scaled the same way at inferenceCode language: PHP (php)
ErrorCauseFix
FileNotFoundError: datasets/heart.csvCSV is not in the path relative to the notebookCreate datasets/ next to the notebook or use an absolute path
TypeError in sns.countplotPositional data argument in seaborn 0.12+Use sns.countplot(x='sex', ...)
ValueError about incompatible input shapeInput(shape=...) does not match the number of feature columnsUse shape=(X_train_s.shape[1],)
ValueError about the file extension when savingKeras 3 requires a .keras or .h5 filename for model.saveSave as name.keras, or use model.export() for a SavedModel for serving
plot_model import errorpydot or Graphviz missingpip install pydot and install Graphviz with your OS package manager

Note: This dataset is for learning only. A model trained on 303 rows is not clinically validated and should never be used to make medical decisions.

Frequently asked questions

What is the difference between the Keras Sequential and Functional API?

Sequential stacks layers in a single line with one input and one output. The Functional API builds a graph by calling layers on tensors, so it supports multiple inputs and outputs, shared layers and skip connections.

Can the Functional API do everything Sequential can?

Yes. Any Sequential model can be written as a functional model with one input and one output, and the training, evaluation and saving calls are the same.

Why use sigmoid and binary_crossentropy for heart disease prediction?

The target column is 0 or 1. A single sigmoid unit outputs a probability between 0 and 1, and binary cross-entropy is the matching loss for that output.

Do I need to scale features before training a Keras model?

Neural networks train faster and more reliably when input features are on similar scales, so standardise them. Fit the scaler on the training data only and reuse it for test and production data.

How do I pass data to a Keras model with multiple inputs?

Pass a list in the same order as the model's inputs, or a dictionary whose keys match each keras.Input name, for example {'numeric': Xn, 'categorical': Xc}.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Tensorsflow Lab7 – Tensorsflow SequentialModel

This lab uses the WHO life expectancy dataset to build a regression model with the TensorFlow Keras Sequential API. The notebook above covers loading the data, inspecting…

Read More

Tensorsflow Lab6 – Tensorsflow SimpleLinearRegression

This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with tf.Variable, computes gradients of…

Read More

Tensorsflow Lab5 – Tensorsflow GradientTape

tf.GradientTape is TensorFlow's automatic differentiation API. It records the operations you run inside a with block, then plays them back in reverse to compute gradients for training….

Read More

Tensorsflow Lab4 – Tensorsflow function

This lab shows how tf.function turns ordinary Python functions into TensorFlow graphs. It covers how AutoGraph converts if, for and while into graph ops, why Python side…

Read More

Tensorsflow Lab3 – Tensorsflow EagerExecution

In eager execution, TensorFlow runs each operation as soon as Python calls it and gives you a concrete value back, with no graph to build first. It…

Read More

Tensorsflow Lab2 – Tensorsflow V1Sessions

This lab shows how TensorFlow 1.x style graphs and sessions still work in TensorFlow 2 through the tf.compat.v1 API. You will see why Session.run() fails while eager…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x