{"id":47535,"date":"2026-11-24T22:04:56","date_gmt":"2026-11-24T22:04:56","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47535"},"modified":"2026-11-24T22:04:56","modified_gmt":"2026-11-24T22:04:56","slug":"tensorsflow-lab8-tensorsflow-functionalmodel","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/tensorsflow-lab8-tensorsflow-functionalmodel\/","title":{"rendered":"Tensorsflow Lab8 &#8211; Tensorsflow FunctionalModel"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab uses the UCI heart disease dataset (303 patients, 13 features, a binary <code>target<\/code>) 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 <code>Sequential<\/code> cannot.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/e39d26533d6f1c07e08fc314634c74bd.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the Functional API is and when to use it<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Keras gives you three ways to define a model: <code>Sequential<\/code> (a plain stack of layers), the Functional API, and subclassing <code>keras.Model<\/code>. 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 <code>keras.Model<\/code> 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.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Need<\/th><th>Sequential<\/th><th>Functional API<\/th><\/tr><\/thead><tbody><tr><td>Single input, single output, linear stack<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><tr><td>Multiple inputs (for example numeric and categorical branches)<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Multiple outputs or auxiliary losses<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Skip or residual connections, shared layers<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Readable summary and plot of the whole graph<\/td><td>Partial<\/td><td>Yes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites and setup<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>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.<\/li>\n\n\n<li><code>pandas<\/code>, <code>numpy<\/code>, <code>scikit-learn<\/code>, <code>matplotlib<\/code> and <code>seaborn<\/code>.<\/li>\n\n\n<li>The heart disease CSV from Kaggle, saved as <code>datasets\/heart.csv<\/code> relative to the notebook, because that is the path the notebook reads from.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">python -m venv tf-lab\nsource tf-lab\/bin\/activate\npip install tensorflow pandas numpy scikit-learn matplotlib seaborn jupyter\nmkdir -p datasets   <span class=\"hljs-comment\"># place heart.csv here<\/span>\npython -c <span class=\"hljs-string\">\"import tensorflow as tf; print(tf.__version__)\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Corrections to the notebook above<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In current seaborn releases the countplot cell fails. Since seaborn 0.12, plotting variables have to be passed as keyword arguments, so <code>sns.countplot(&#039;sex&#039;, hue=&#039;target&#039;, data=df)<\/code> raises a <code>TypeError<\/code>. Pass <code>x=<\/code> explicitly:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">sns.countplot(x=<span class=\"hljs-string\">'sex'<\/span>, hue=<span class=\"hljs-string\">'target'<\/span>, data=df)\nplt.title(<span class=\"hljs-string\">'Heart Disease Frequency for Gender'<\/span>)\nplt.legend(&#91;<span class=\"hljs-string\">'No Disease'<\/span>, <span class=\"hljs-string\">'Yes Disease'<\/span>])\nplt.xlabel(<span class=\"hljs-string\">'Gender (0 = Female, 1 = Male)'<\/span>)\nplt.ylabel(<span class=\"hljs-string\">'Frequency'<\/span>)\nplt.show()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The column notes also don&#039;t match the data. <code>thal<\/code> is described as 3, 6 or 7, but <code>df.describe()<\/code> above shows values from 0 to 3. <code>ca<\/code> is described as 0 to 3, but its maximum is 4. This version of the dataset re-encodes these columns, and the <code>thal = 0<\/code> and <code>ca = 4<\/code> rows are generally treated as placeholders for missing values. Treat both columns as categories, not measurements, and consider dropping or imputing those few rows.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> In recent pandas versions, <code>value_counts()<\/code> labels its output <code>Name: count<\/code> instead of <code>Name: sex<\/code>. The counts are the same, so this is not an error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prepare the data for training<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">First split the data, then scale it. Fit the <code>StandardScaler<\/code> on the training set only, so no statistics from the test set leak into training. Using <code>stratify<\/code> keeps the roughly 54\/46 class balance the same in both splits.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">X = df.drop(<span class=\"hljs-string\">'target'<\/span>, axis=<span class=\"hljs-number\">1<\/span>)\ny = df&#91;<span class=\"hljs-string\">'target'<\/span>]\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=<span class=\"hljs-number\">0.2<\/span>, random_state=<span class=\"hljs-number\">42<\/span>, stratify=y)\n\nscaler = StandardScaler()\nX_train_s = scaler.fit_transform(X_train)\nX_test_s = scaler.transform(X_test)\n\n<span class=\"hljs-keyword\">print<\/span>(X_train_s.shape, X_test_s.shape)   <span class=\"hljs-comment\"># (242, 13) (61, 13)<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Build the functional model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Start from a <code>keras.Input<\/code> and call each layer on the output of the previous one. Then wrap the input and output tensors in <code>keras.Model<\/code>. Use a single sigmoid unit with <code>binary_crossentropy<\/code> for a 0\/1 target.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">tf.random.set_seed(<span class=\"hljs-number\">42<\/span>)\n\ndef build_model(n_features):\n    inputs = keras.Input(shape=(n_features,), name=<span class=\"hljs-string\">'features'<\/span>)\n    x = layers.Dense(<span class=\"hljs-number\">16<\/span>, activation=<span class=\"hljs-string\">'relu'<\/span>)(inputs)\n    x = layers.Dropout(<span class=\"hljs-number\">0.3<\/span>)(x)\n    x = layers.Dense(<span class=\"hljs-number\">8<\/span>, activation=<span class=\"hljs-string\">'relu'<\/span>)(x)\n    outputs = layers.Dense(<span class=\"hljs-number\">1<\/span>, activation=<span class=\"hljs-string\">'sigmoid'<\/span>, name=<span class=\"hljs-string\">'disease'<\/span>)(x)\n\n    model = keras.Model(inputs=inputs, outputs=outputs, name=<span class=\"hljs-string\">'heart_functional'<\/span>)\n    model.compile(\n        optimizer=keras.optimizers.Adam(learning_rate=<span class=\"hljs-number\">0.001<\/span>),\n        loss=<span class=\"hljs-string\">'binary_crossentropy'<\/span>,\n        metrics=&#91;<span class=\"hljs-string\">'accuracy'<\/span>,\n                 keras.metrics.Precision(name=<span class=\"hljs-string\">'precision'<\/span>),\n                 keras.metrics.Recall(name=<span class=\"hljs-string\">'recall'<\/span>)])\n    <span class=\"hljs-keyword\">return<\/span> model\n\nmodel = build_model(X_train_s.shape&#91;<span class=\"hljs-number\">1<\/span>])\nmodel.summary()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><code>model.summary()<\/code> should list an input layer, two <code>Dense<\/code> layers, a <code>Dropout<\/code> layer and the output layer, for 369 trainable parameters: 13\u00d716+16, plus 16\u00d78+8, plus 8+1. The dropout layer guards against overfitting, which happens quickly on a dataset this small.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Train with early stopping and TensorBoard<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The notebook imports <code>datetime<\/code>, which is useful for giving each TensorBoard run its own log directory. <code>EarlyStopping<\/code> stops training when validation loss stops improving and restores the best weights.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">log_dir = <span class=\"hljs-string\">'logs\/fit\/'<\/span> + datetime.now().strftime(<span class=\"hljs-string\">'%Y%m%d-%H%M%S'<\/span>)\n\ncallbacks = &#91;\n    keras.callbacks.EarlyStopping(monitor=<span class=\"hljs-string\">'val_loss'<\/span>, patience=<span class=\"hljs-number\">15<\/span>,\n                                  restore_best_weights=<span class=\"hljs-keyword\">True<\/span>),\n    keras.callbacks.TensorBoard(log_dir=log_dir)\n]\n\nhistory = model.fit(X_train_s, y_train,\n                    validation_split=<span class=\"hljs-number\">0.2<\/span>,\n                    epochs=<span class=\"hljs-number\">200<\/span>,\n                    batch_size=<span class=\"hljs-number\">16<\/span>,\n                    callbacks=callbacks,\n                    verbose=<span class=\"hljs-number\">0<\/span>)\n\npd.DataFrame(history.history)&#91;&#91;<span class=\"hljs-string\">'loss'<\/span>, <span class=\"hljs-string\">'val_loss'<\/span>]].plot()\nplt.xlabel(<span class=\"hljs-string\">'Epoch'<\/span>)\nplt.show()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">To compare runs, start TensorBoard with <code>tensorboard --logdir logs\/fit<\/code>. If validation loss rises while training loss keeps falling, the model is overfitting. Raise the dropout rate, use fewer units, or add L2 regularisation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Evaluate on the test set<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>predict<\/code> returns probabilities. Apply a threshold to turn them into class labels, then use the scikit-learn metrics imported at the top of the notebook.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">model.evaluate(X_test_s, y_test, verbose=<span class=\"hljs-number\">0<\/span>)\n\ny_prob = model.predict(X_test_s).ravel()\ny_pred = (y_prob &gt; <span class=\"hljs-number\">0.5<\/span>).astype(int)\n\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'Accuracy :'<\/span>, accuracy_score(y_test, y_pred))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'Precision:'<\/span>, precision_score(y_test, y_pred))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'Recall   :'<\/span>, recall_score(y_test, y_pred))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Going further: a two-input functional model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Sequential<\/code> cannot build a model with separate branches. The model below feeds the continuous measurements and the one-hot encoded categorical columns through their own <code>Dense<\/code> layers, then joins them with <code>Concatenate<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">num_cols = &#91;<span class=\"hljs-string\">'age'<\/span>, <span class=\"hljs-string\">'trestbps'<\/span>, <span class=\"hljs-string\">'chol'<\/span>, <span class=\"hljs-string\">'thalach'<\/span>, <span class=\"hljs-string\">'oldpeak'<\/span>]\ncat_cols = &#91;<span class=\"hljs-string\">'sex'<\/span>, <span class=\"hljs-string\">'cp'<\/span>, <span class=\"hljs-string\">'fbs'<\/span>, <span class=\"hljs-string\">'restecg'<\/span>, <span class=\"hljs-string\">'exang'<\/span>, <span class=\"hljs-string\">'slope'<\/span>, <span class=\"hljs-string\">'ca'<\/span>, <span class=\"hljs-string\">'thal'<\/span>]\n\ncat_all = pd.get_dummies(df&#91;cat_cols].astype(str), dtype=float)\ntr_idx, te_idx = train_test_split(df.index, test_size=<span class=\"hljs-number\">0.2<\/span>,\n                                  random_state=<span class=\"hljs-number\">42<\/span>, stratify=df&#91;<span class=\"hljs-string\">'target'<\/span>])\n\nnum_scaler = StandardScaler()\nXn_tr = num_scaler.fit_transform(df.loc&#91;tr_idx, num_cols])\nXn_te = num_scaler.transform(df.loc&#91;te_idx, num_cols])\nXc_tr, Xc_te = cat_all.loc&#91;tr_idx].values, cat_all.loc&#91;te_idx].values\nyt, yv = df.loc&#91;tr_idx, <span class=\"hljs-string\">'target'<\/span>].values, df.loc&#91;te_idx, <span class=\"hljs-string\">'target'<\/span>].values\n\nnum_in = keras.Input(shape=(len(num_cols),), name=<span class=\"hljs-string\">'numeric'<\/span>)\ncat_in = keras.Input(shape=(cat_all.shape&#91;<span class=\"hljs-number\">1<\/span>],), name=<span class=\"hljs-string\">'categorical'<\/span>)\n\nn = layers.Dense(<span class=\"hljs-number\">8<\/span>, activation=<span class=\"hljs-string\">'relu'<\/span>)(num_in)\nc = layers.Dense(<span class=\"hljs-number\">8<\/span>, activation=<span class=\"hljs-string\">'relu'<\/span>)(cat_in)\nx = layers.Concatenate()(&#91;n, c])\nx = layers.Dropout(<span class=\"hljs-number\">0.3<\/span>)(x)\nx = layers.Dense(<span class=\"hljs-number\">8<\/span>, activation=<span class=\"hljs-string\">'relu'<\/span>)(x)\nout = layers.Dense(<span class=\"hljs-number\">1<\/span>, activation=<span class=\"hljs-string\">'sigmoid'<\/span>, name=<span class=\"hljs-string\">'disease'<\/span>)(x)\n\nmulti = keras.Model(inputs=&#91;num_in, cat_in], outputs=out, name=<span class=\"hljs-string\">'heart_two_input'<\/span>)\nmulti.compile(optimizer=<span class=\"hljs-string\">'adam'<\/span>, loss=<span class=\"hljs-string\">'binary_crossentropy'<\/span>, metrics=&#91;<span class=\"hljs-string\">'accuracy'<\/span>])\n\nmulti.fit({<span class=\"hljs-string\">'numeric'<\/span>: Xn_tr, <span class=\"hljs-string\">'categorical'<\/span>: Xc_tr}, yt,\n          validation_split=<span class=\"hljs-number\">0.2<\/span>, epochs=<span class=\"hljs-number\">200<\/span>, batch_size=<span class=\"hljs-number\">16<\/span>, verbose=<span class=\"hljs-number\">0<\/span>,\n          callbacks=&#91;keras.callbacks.EarlyStopping(patience=<span class=\"hljs-number\">15<\/span>,\n                                                   restore_best_weights=<span class=\"hljs-keyword\">True<\/span>)])\n<span class=\"hljs-keyword\">print<\/span>(multi.evaluate({<span class=\"hljs-string\">'numeric'<\/span>: Xn_te, <span class=\"hljs-string\">'categorical'<\/span>: Xc_te}, yv, verbose=<span class=\"hljs-number\">0<\/span>))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The dictionary keys passed to <code>fit<\/code> and <code>evaluate<\/code> must match the <code>name<\/code> given to each <code>keras.Input<\/code>. 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 <code>keras.utils.plot_model(multi, show_shapes=True)<\/code>, which needs the <code>pydot<\/code> package and the Graphviz binaries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Save, reload and troubleshoot<\/h2>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">model.save(<span class=\"hljs-string\">'heart_functional.keras'<\/span>)\nrestored = keras.models.load_model(<span class=\"hljs-string\">'heart_functional.keras'<\/span>)\n\nimport joblib\njoblib.dump(scaler, <span class=\"hljs-string\">'heart_scaler.joblib'<\/span>)   <span class=\"hljs-comment\"># inputs must be scaled the same way at inference<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>FileNotFoundError: datasets\/heart.csv<\/code><\/td><td>CSV is not in the path relative to the notebook<\/td><td>Create <code>datasets\/<\/code> next to the notebook or use an absolute path<\/td><\/tr><tr><td><code>TypeError<\/code> in <code>sns.countplot<\/code><\/td><td>Positional data argument in seaborn 0.12+<\/td><td>Use <code>sns.countplot(x=&#039;sex&#039;, ...)<\/code><\/td><\/tr><tr><td><code>ValueError<\/code> about incompatible input shape<\/td><td><code>Input(shape=...)<\/code> does not match the number of feature columns<\/td><td>Use <code>shape=(X_train_s.shape[1],)<\/code><\/td><\/tr><tr><td><code>ValueError<\/code> about the file extension when saving<\/td><td>Keras 3 requires a <code>.keras<\/code> or <code>.h5<\/code> filename for <code>model.save<\/code><\/td><td>Save as <code>name.keras<\/code>, or use <code>model.export()<\/code> for a SavedModel for serving<\/td><\/tr><tr><td><code>plot_model<\/code> import error<\/td><td><code>pydot<\/code> or Graphviz missing<\/td><td><code>pip install pydot<\/code> and install Graphviz with your OS package manager<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between the Keras Sequential and Functional API?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Sequential<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can the Functional API do everything Sequential can?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Any <code>Sequential<\/code> model can be written as a functional model with one input and one output, and the training, evaluation and saving calls are the same.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why use sigmoid and binary_crossentropy for heart disease prediction?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>target<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Do I need to scale features before training a Keras model?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I pass data to a Keras model with multiple inputs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Pass a list in the same order as the model&#039;s inputs, or a dictionary whose keys match each <code>keras.Input<\/code> name, for example <code>{&#039;numeric&#039;: Xn, &#039;categorical&#039;: Xc}<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230;. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7380],"class_list":["post-47535","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-tensorflow"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47535","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47535"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47535\/revisions"}],"predecessor-version":[{"id":80206,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47535\/revisions\/80206"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47535"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47535"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47535"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}