<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fernando Nieuwveldt on Medium]]></title>
        <description><![CDATA[Stories by Fernando Nieuwveldt on Medium]]></description>
        <link>https://medium.com/@fdnieuwveldt?source=rss-1a1ed1ae9d3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xhD7dCtdnufQuMFP00oAiw.png</url>
            <title>Stories by Fernando Nieuwveldt on Medium</title>
            <link>https://medium.com/@fdnieuwveldt?source=rss-1a1ed1ae9d3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:27:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fdnieuwveldt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unifying Scikit-learn Pipelines and PyTorch Models with ONNX for Deployment]]></title>
            <link>https://pub.towardsai.net/unifying-scikit-learn-pipelines-and-pytorch-models-with-onnx-for-deployment-d6b783eeca44?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b783eeca44</guid>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 12:02:15 GMT</pubDate>
            <atom:updated>2026-05-02T06:20:10.739Z</atom:updated>
            <content:encoded><![CDATA[<p>I have blogged in the past about a common machine learning design pattern involving feature engineering and preprocessing when working with an scikit-learn pipeline alongside a deep learning framework where your model is built. This could be PyTorch or TensorFlow Keras. The issue with this workflow is that it creates a disconnect between preprocessing, model building, and ultimately model deployment, making it a flawed approach.</p><p>Previously, I wrote about this issue specifically in cases where the model is built in one of the major deep learning frameworks. The solution was to implement feature engineering and encoding natively within the deep learning framework of choice. You can find my posts on this <a href="https://fdnieuwveldt.medium.com/feature-engineering-using-custom-keras-layers-part-2-aead2b89ee06">here</a> and <a href="https://fdnieuwveldt.medium.com/creating-feature-engineering-flow-graphs-in-keras-87bb38f0b5cf">here</a>.</p><p>Integrating preprocessing and feature engineering into your neural network architecture definitely has advantages. For example, having a complete blueprint of your model in a PyTorch model architecture allows you to serve it efficiently using something like TorchServe or Tensorflow Serving for optimized, fast inference. This led to writing this post to explore whether there’s a better way to handle this. Sure, fully implementing your solution with preprocessing, feature engineering natively in PyTorch or Keras has many advantages, but it also introduces a some complexity. That’s when I stumbled upon <strong>ONNX</strong> and how it could help us with the <strong>design pattern</strong> above. <strong>ONNX</strong> (Open Neural Network Exchange) is an open standard format for representing machine learning models, enabling interoperability between different frameworks like PyTorch, TensorFlow, and scikit-learn.</p><p>Using ONNX we can still build our feature pipelines and models in the framework of our choice for our training pipeline and have and extra bridge to ONNX for our inference pipeline. We should see Scikit-Learn and PyTorch(just in this scenario being discussed) as model-building or training frameworks. They are not built for production or inference at scale especially Scikit-Learn. This is what we will explore in this post.</p><h4>What We’ll Cover</h4><p>We will discuss how to leverage our favorite model-building frameworks for training while using ONNX for inference and production. Specifically, we will:</p><ul><li>Use the heart dataset for illustration</li><li>Separate and decouple training from inference at the framework level, creating a more compute optimised workflow.</li><li>Convert SKLearn preprocessing pipeline and PyTorch model to ONNX format</li><li>Unify the preprocessing pipeline and model from ONNX format into an optimised ONNX graph</li><li>Discuss some benefits in this approach or ONNX in general</li></ul><h4>This is the ONNX Graph we will build:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwogN11Xbfg6gzG8FUBqIA.png" /><figcaption>Here’s an image of what our final unified model graph will look like after converting our training frameworks into a single ONNX inference pipeline</figcaption></figure><h4>Installation and imports</h4><pre>!pip install pandas onnx onnxruntime torch lightning skl2onnx netron<br><br>import numpy as np<br>import pandas as pd<br>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br><br>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>import torch.nn as nn<br>import pytorch_lightning as pl<br>from torch.utils.data import DataLoader, TensorDataset, random_split<br><br>import onnx<br>import onnxruntime as ort<br>from skl2onnx import convert_sklearn<br>from skl2onnx.common.data_types import FloatTensorType, Int32TensorType</pre><h4>Setting up the preprocessing pipeline using SKLearn</h4><p>Next we will apply scaling and one-hot encoding to our features using sklearn</p><pre>file_url = &quot;http://storage.googleapis.com/download.tensorflow.org/data/heart.csv&quot;<br>dataframe = pd.read_csv(file_url)<br>labels = dataframe.pop(&quot;target&quot;)<br><br>NUMERICAL_FEATURES = [&#39;age&#39;, &#39;trestbps&#39;, &#39;chol&#39;, &#39;thalach&#39;, &#39;oldpeak&#39;, &#39;slope&#39;]<br>CATEGORICAL_FEATURES = [&#39;sex&#39;, &#39;cp&#39;, &#39;fbs&#39;, &#39;restecg&#39;, &#39;exang&#39;, &#39;ca&#39;]<br><br># Define transformers for numerical and categorical features<br>numerical_transformer = StandardScaler()<br>categorical_transformer = OneHotEncoder(handle_unknown=&quot;ignore&quot;)<br><br># Create ColumnTransformer<br>preprocessor = ColumnTransformer(<br>    transformers=[<br>        (&quot;numerical_transformer&quot;, numerical_transformer, NUMERICAL_FEATURES),<br>        (&quot;categorical_transformer&quot;, categorical_transformer, CATEGORICAL_FEATURES),<br>    ]<br>)<br><br>preprocessor.fit(dataframe)<br><br>transformed_data_example = preprocessor.transform(dataframe)</pre><h4>Training model with PyTorch</h4><p>The goal of this article is not really to train a model, but for completeness we chose torch lightning for the easiest and quickest way to get setup for training:</p><pre>N_FEATURES = transformed_data_example.shape[1]<br><br>dataset = TensorDataset(<br>    torch.from_numpy(transformed_data_example).float(),<br>    torch.from_numpy(labels.values.reshape((-1, 1))).float()<br>)<br>train_size = int(0.8 * len(dataset))<br>val_size = len(dataset) - train_size<br>train_dataset, val_dataset = random_split(dataset, [train_size, val_size])<br><br>train_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)<br>val_dataloader = DataLoader(val_dataset, batch_size=32, shuffle=False)<br><br><br>class Model(pl.LightningModule):<br>    def __init__(self, n_features):<br>        super(Model, self).__init__()<br>        self.fc1 = nn.Linear(n_features, 32)<br>        self.fc2 = nn.Linear(32, 16)<br>        self.fc3 = nn.Linear(16, 1)<br>    <br>    def forward(self, x):<br>        x = self.fc1(x)<br>        x = F.relu(x)<br>        x = self.fc2(x)<br>        x = F.relu(x)<br>        x = self.fc3(x)<br>        # Apply sigmoid to obtain output probabilities<br>        x = torch.sigmoid(x)<br>        return x<br>    <br>    def training_step(self, batch, batch_idx):<br>        x, y = batch<br>        y_hat = self(x)<br>        # Ensure y is a float tensor and has the same shape as y_hat<br>        loss = F.binary_cross_entropy(y_hat, y.float())<br>        self.log(&#39;train_loss&#39;, loss, prog_bar=True)<br>        return loss<br><br>    def validation_step(self, batch, batch_idx):<br>        x, y = batch<br>        y_hat = self(x)<br>        loss = F.binary_cross_entropy(y_hat, y.float())<br>        self.log(&#39;val_loss&#39;, loss, prog_bar=True)<br>        return loss<br>    <br>    def configure_optimizers(self):<br>        optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)<br>        return optimizer<br><br><br>model = Model(n_features=N_FEATURES)<br><br>trainer = pl.Trainer(max_epochs=20)<br>trainer.fit(model, train_dataloader, val_dataloader)</pre><p>We now have preprocessing pipeline build with sklearn and the model built with PyTorch. We are now done with our model training and build process. In the next section we will start with an optimised unified ONNX model for model inference.</p><h3>Converting to ONNX</h3><p>In this section we will start the conversion process to ONNX format. This will entail three subsections:</p><ul><li>Converting the Preprocessing Pipeline to ONNX.</li><li>Converting the Torch Model to ONNX.</li><li>Unifying Preprocessing Pipeline and Models with ONNX.</li></ul><h4>Converting the Scikit-Learn Preprocessing Pipeline to ONNX</h4><p>Here we will convert the scikit learn pipeline to ONNX. We will also get the input data ready for an onnx inference session.</p><pre># convert and save preprocessor<br><br># Cast features to appropriate onnx format<br># - numerical features   ---&gt; FloatTensorType<br># - categorical features ---&gt; Int32TensorType<br>initial_numerical_types = [<br>    (numerical_feature, FloatTensorType([None, 1]))<br>    for numerical_feature in NUMERICAL_FEATURES<br>]<br>initial_categorical_types = [<br>    (categorical_feature, Int32TensorType([None, 1]))<br>    for categorical_feature in CATEGORICAL_FEATURES<br>]<br>initial_types = initial_numerical_types + initial_categorical_types<br>onnx_model = convert_sklearn(preprocessor, initial_types=initial_types)<br><br><br>with open(&quot;preprocessing_sklearn_pipeline.onnx&quot;, &quot;wb&quot;) as f:<br>    f.write(onnx_model.SerializeToString())</pre><p>Using the netron package we can create preprocessing subgraph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Tck1HgdXr6ldXc1a3cIng.png" /></figure><h4>Converting the Torch Model to ONNX</h4><p>In this section we will convert the PyTorch model. ONNX comes installed torch.</p><pre># use one output of the onnx preprocessing outputs to export torch model<br>dummy_input = torch.tensor(transformed_data_example, dtype=torch.float32)<br><br>torch.onnx.export(<br>    model,<br>    dummy_input,<br>    &quot;torch_model.onnx&quot;,<br>    input_names=[&quot;input&quot;],<br>    output_names=[&quot;output&quot;],<br>)</pre><p>This is PyTorch model graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/61/1*0ZrEBlBcinw1tEztz8PclA.png" /></figure><h4>Unifying the SKLearn preprocessing pipeline with our PyTorch Neural Network</h4><p>We have both the scikit learn preprocessing pipeline and the torch model saved to onnx format. The last part is to unify these onnx models into one graph. This can be bit tricky.</p><p>We need to make sure:</p><ul><li>The input name to the torch model graph is the output of the preprocessing subgraph.</li><li>The Pytorch model node should also explicitly use the preprocessing output.</li><li>Set the opset version; we set it to 17.</li><li>Create a new ONNX graph and then model.</li><li>Saving the new model.</li></ul><pre># Load the preprocessing ONNX model<br>preprocessing_model = onnx.load(&quot;preprocessing_sklearn_pipeline.onnx&quot;)<br><br># Load the PyTorch ONNX model<br>pytorch_model = onnx.load(&quot;torch_model.onnx&quot;)<br><br># Get the preprocessing model&#39;s output name<br>preprocessing_output_name = preprocessing_model.graph.output[0].name<br><br># Update PyTorch model input name to match preprocessing output<br>pytorch_model.graph.input[0].name = preprocessing_output_name  # Rename input<br><br># Ensure the PyTorch model input correctly refers to preprocessing model output<br>assert (<br>    preprocessing_output_name == pytorch_model.graph.input[0].name<br>), &quot;Mismatched preprocessing output and PyTorch input!&quot;<br><br># Update PyTorch model nodes to explicitly use the preprocessing output<br># And we only do it for the first node<br>for counter, node in enumerate(pytorch_model.graph.node):<br>    if counter == 0:<br>        node.input[0] = preprocessing_output_name<br>        break<br><br># Combine the two graphs<br>combined_graph = onnx.helper.make_graph(<br>    nodes=list(preprocessing_model.graph.node) + list(pytorch_model.graph.node),<br>    name=&quot;UnifiedPipeline&quot;,<br>    inputs=preprocessing_model.graph.input,<br>    outputs=pytorch_model.graph.output,<br>    initializer=list(preprocessing_model.graph.initializer)<br>    + list(pytorch_model.graph.initializer),<br>)<br><br>unified_opset_version = 17  # Adjust based on your opset version<br><br># Combine the existing opset imports from both models<br>combined_opset_import = [<br>    onnx.helper.make_opsetid(&quot;ai.onnx.ml&quot;, 1),  # Scikit-learn opset<br>    onnx.helper.make_opsetid(&quot;&quot;, unified_opset_version),<br>]<br># Create a new ONNX model with the combined graph<br>combined_model = onnx.helper.make_model(<br>    combined_graph, opset_imports=combined_opset_import<br>)<br><br># Save the combined model<br>onnx.save(combined_model, &quot;unified_model.onnx&quot;)</pre><p>This contains our full inference Graph containing preprocessing and model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwogN11Xbfg6gzG8FUBqIA.png" /></figure><h3>Comparisons</h3><p>In this section we run the two scenarios with and without ONNX conversion and:</p><ul><li>Compare results</li><li>Calculate execution time</li></ul><p>One thing to note is that we need convert our pandas data frame to dictionaries for the onnx inference session.</p><pre># Prepare input data as dictionaries with numpy type values<br>numerical_input_data = {<br>    feature: dataframe[feature].to_numpy().reshape(-1, 1).astype(np.float32)<br>    for feature in NUMERICAL_FEATURES<br>}<br>categorical_input_data = {<br>    feature: dataframe[feature].to_numpy().reshape(-1, 1).astype(np.int32)<br>    for feature in CATEGORICAL_FEATURES<br>}<br># combine numerical and categorical features into one dict<br>input_data = {**numerical_input_data, **categorical_input_data}<br><br># Load the unified ONNX model<br>session = ort.InferenceSession(&quot;unified_model.onnx&quot;)<br><br>onnx_outputs = session.run(None, input_data)<br><br># # calling model seperately<br>transformed_data = preprocessor.transform(dataframe)<br>non_onnx_outputs = model(torch.tensor(transformed_data, dtype=torch.float32))<br><br># Check if arrays are nearly equal<br>are_equal = np.allclose(<br>                onnx_outputs[0],<br>                non_onnx_outputs.detach().numpy(),<br>                rtol=1e-6, atol=1e-6<br>)<br><br>print(are_equal)<br># True</pre><p>Below we ran some speed comparisons and saw an increase of 20 to 30 fold faster on a MacBook M1</p><pre>import time<br><br><br>onnx_times = []<br>for k in range(1000):<br>    start_time = time.time()<br>    _ = session.run(None, input_data)<br>    onnx_times.append(time.time() - start_time)<br>avg_onnx_time = np.mean(onnx_times)<br><br><br>sequential_execution_time = []<br>for k in range(1000):<br>    start_time = time.time()<br>    transformed_data = preprocessor.transform(dataframe)<br>    non_onnx_outputs = model(torch.tensor(transformed_data, dtype=torch.float32))<br>    sequential_execution_time.append(time.time() - start_time)<br>avg_sequential_execution_time = np.mean(sequential_execution_time)<br><br>print(f&quot;ONNX Inference Time: {avg_onnx_time:.6f} seconds&quot;)<br>print(f&quot;Sequential Inference Time: {avg_sequential_execution_time:.6f} seconds&quot;)<br>print(f&quot;ONNX speed increase {avg_sequential_execution_time/avg_onnx_time}&quot;)</pre><pre>ONNX Inference Time: 0.000096 seconds<br>Sequential Inference Time: 0.002689 seconds<br>ONNX speed increase 27.905641984838585</pre><h3>Advantages of Using ONNX for Unification</h3><p>Below we will list some advantages of building a unified pipeline:</p><h4>Single Model Deployment:</h4><ul><li>Simplifies the deployment process by handling both models within one ONNX file.</li><li>While we still use our favourite frameworks for model building.</li></ul><h4>Reduced External Dependencies:</h4><ul><li>A unified model runs entirely within ONNX Runtime; meaning you don’t need additional libraries (like NumPy or separate frameworks) during inference.</li><li>If we used something like fastapi we would have to install sklearn and pytorch with the docker image which would make it quite bulky.</li><li>Even if we go onnx inside fastapi we would still numpy installed and the extra latency from preprocessing and than run model.</li></ul><h4>Optimized Performance:</h4><ul><li>ONNX Runtime can apply graph-level optimizations across the entire merged pipeline, potentially reducing latency and improving inference speed.</li><li>Unifying the graphs ensures that data seamlessly flows from preprocessing to prediction.</li></ul><h4>Easier Maintenance and Debugging:</h4><ul><li>With a unified pipeline, there’s a single model to monitor, version, and debug. This helps isolate issues within one cohesive framework rather than juggling multiple independent models.</li></ul><h4>Optimized Docker images:</h4><ul><li>We only need onnxruntime at inference time which results in small docker images which can assist with quicker horizontal scaling with sudden bursts.</li></ul><h3>Conclusion</h3><p>In this post we looked at a solution to the common problem and design pattern of using your model training framework for inference and production purposes as well. More specifically we looked at the combination of scikit learn feature engineering and preprocessing pipelines and how can have a more optimized deployment pattern when we combine it with a PyTorch model.</p><p>We build the preprocessing pipeline and saved it to an onnx Graph, the same for the model. The next part we unified these two graph into a single ONNX graph that will be used for Deployment or Production purposes. We gave some advantages of this approach and also a big gain in execution. One of my favourite visuals was the Graph we created showing how everything fits in and showing all computations part of the Graph.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b783eeca44" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/unifying-scikit-learn-pipelines-and-pytorch-models-with-onnx-for-deployment-d6b783eeca44">Unifying Scikit-learn Pipelines and PyTorch Models with ONNX for Deployment</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Keras Functional API: Where Flexibility Meets Functionality showed by building custom…]]></title>
            <link>https://fdnieuwveldt.medium.com/the-keras-functional-api-where-flexibility-meets-functionality-7394d0980880?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7394d0980880</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 19:13:25 GMT</pubDate>
            <atom:updated>2025-01-20T07:47:42.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Keras Functional API: Where Flexibility Meets Functionality showed by building custom architectures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWrs_7rWSIFL-56N1iuVIA.png" /><figcaption>© 2023 mlnuggets — All rights reserved.</figcaption></figure><p>Designing the right architecture for a neural network is a blend of creativity and science. As problems grow more complex, the need for tools that help researchers and developers create adaptable and sophisticated models becomes essential. That’s where the Keras Functional API shines. Unlike the traditional sequential approach, which builds models in a straightforward, linear fashion, the Functional API offers the flexibility to craft more intricate structures. This allows for capturing complex relationships within data. In this article, we’ll explore the capabilities of this powerful tool, highlighting how it works and why it matters. Whether you’re an experienced neural network designer or just starting in deep learning, mastering the Keras Functional API can take your modeling skills to the next level.</p><p><em>I recently gave a talk in our company’s data science CoP showing the different architectures and functional API flexibility and thought create a blog post from it. This is also a reference for myself to lookup in future.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9UwQnW8z8nGCHQCRkizTg.jpeg" /></figure><p>In this blog post we will be looking at different neural architecture designs that showcases the power and flexibility of Keras’s Functional API. We will look at some high level examples.</p><p>Here is an outline of the different examples:</p><ul><li>Shared Layer</li><li>Single Input Multi Input</li><li>Multi-Input, Single-Output: Integrating Mixed Data Structures</li><li>Wide and Deep architecture</li><li>Adding post processing logic after output layer</li></ul><h3>Shared Layer example</h3><p>For illustrative purposes, in this example, we will examine a shared layer scenario where two Dense layers both receive their input from the same preceding layer.</p><p>Say for example that you have a need to use different activation functions for two Dense layers. This is how it can be implemented:</p><pre>from tensorflow.keras.layers import Input, Dense<br>from tensorflow.keras.models import Model<br><br># Define the input layer<br>inputs = Input(shape=(10,), name=&#39;Input Layer&#39;)<br><br># Define the layers<br>x = Dense(64, activation=&#39;relu&#39;, name=&#39;Dense-Layer-with-relu-activation&#39;)(inputs)<br>y = Dense(32, activation=&#39;tanh&#39;, name=&#39;Dense-Layer-with-tanh-activation&#39;)(inputs)<br>z = Concatenate(name=&#39;Concatenated-Layers&#39;)([x, y])<br>outputs = Dense(1, activation=&#39;sigmoid&#39;, name=&#39;Output-Layer&#39;)(z)<br><br># Define the model<br>model = Model(inputs=inputs, outputs=outputs)<br><br># plot model architecture<br>from tensorflow.keras.utils import plot_model<br>plot_model(model, to_file=&#39;model.png&#39;, show_shapes=True, show_layer_names=True)</pre><p>In the code block above we notice that layer x and y takes in as input the same Input layer. Below is the plot for the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahqRsJPtwdtoxXGZ4-dYpQ.png" /><figcaption>Plot that shows two layers using the same layer as input</figcaption></figure><h3><em>Single Input Multi Output example</em></h3><p>In the following example we look at single input multi output example. Say you need to predict the quality of wine which can be perhaps have a rating of 1 to 5. From that same dataset you also want predict the price. These two problems have similar feature data but different outputs. One is a classification problem with softmax and the other a regression problem.</p><p>We can combine the two problems into a single problem using the Functional API and shared layers:</p><pre>from tensorflow.keras.layers import Input, Dense, Concatenate<br>from tensorflow.keras.models import Model<br><br># Define the input layer<br>inputs = Input(shape=(10,), name=&#39;Input Layer&#39;)<br><br># Define the layers<br>x = Dense(64, activation=&#39;relu&#39;, name=&#39;Dense-Layer-with-relu-activation&#39;)(inputs)<br>classification_outputs = Dense(10, activation=&#39;softmax&#39;, name=&#39;Classification-Output-Layer&#39;)(x)<br>regression_outputs = Dense(1, activation=&#39;linear&#39;, name=&#39;Regression-Output-Layer&#39;)(x)<br><br># Define the model<br>model = Model(inputs=inputs, outputs=[classification_outputs, regression_outputs])<br><br># plot model architecture<br>from tensorflow.keras.utils import plot_model<br>plot_model(model, to_file=&#39;single_input_multi_output.png&#39;, show_shapes=True, show_layer_names=True)</pre><p>In this example we have two output layers one for classification and one for regression. Below is a graph of the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*A_uAhCiyZwRDT4h0fdfD-A.png" /><figcaption>Single Input Multi Output Neural Network Architecture Graph</figcaption></figure><h3>Multi-Input, Single-Output: Integrating Mixed Data Structures</h3><p>We can also have a problem with multiple inputs and a single output. For example you can have tabular data features of a product and also an image of the product. In this case we have different input types as well. Lets say we want to predict the price of a specific wine as in the previous example, but we also want to use an image of the wine bottle as intput.</p><p>This is how it can be implemented:</p><pre>from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, Concatenate<br>from tensorflow.keras.models import Model<br><br># The first branch operates on the first input<br>image_input = Input(shape=(10,), name=&quot;product_info&quot;)<br>x = Dense(64, activation=&quot;relu&quot;)(image_input)<br>x = Dense(32, activation=&quot;relu&quot;)(x)<br><br># The second branch operates on the second input<br>product_info_input = Input(shape=(64, 64, 3), name=&quot;product_image&quot;)<br>y = Conv2D(32, (3, 3), activation=&quot;relu&quot;)(product_info_input)<br>y = MaxPooling2D(pool_size=(2, 2))(y)<br>y = Flatten()(y)<br>y = Dense(64, activation=&quot;relu&quot;)(y)<br>y = Dense(32, activation=&quot;relu&quot;)(y)<br><br># Combine the output of the two branches<br>combined = Concatenate()([x, y])<br><br># Apply a FC layer and then a classification prediction on the<br># combined outputs<br>z = Dense(10, activation=&quot;relu&quot;)(combined)<br>z = Dense(4, activation=&quot;relu&quot;)(z)<br>output = Dense(1, activation=&quot;linear&quot;, name=&quot;price&quot;)(z) # Binary classification output<br><br># The model will accept inputs of the form [tabular data, image data]<br># and will output a regression problem<br>model = Model(inputs=[product_info_input, image_input], outputs=output)<br><br># plot model architecture<br>from tensorflow.keras.utils import plot_model<br>plot_model(model, to_file=&#39;multi_input_single_output.png&#39;, show_shapes=True, show_layer_names=True)</pre><p>In the above code example we have two different types of inputs. We first process them separately and complete the image input as a fully connected Dense layer whereafter we concatenate the Dense layers from the product info(tabular data). Here is a model graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*XJsyXTr62nWHMvb0Za-LPQ.png" /><figcaption>Multi Input Single Output with mixed data structures as the input</figcaption></figure><h3>Wide &amp; Deep architecture</h3><p>The Wide &amp; Deep Learning architecture was introduced by Google for large-scale regression problems, such as recommending apps in the Google Play store. The implementation was for the Google Play click-through rate prediction problem. However, it can be adapted other datasets.</p><p>Here’s an implementation of the Wide &amp; Deep architecture using the Keras functional API:</p><pre>from tensorflow.keras.layers import Input, Dense, Concatenate<br>from tensorflow.keras.models import Model<br><br># Wide<br># The wide inputs will be directly connected to the output after the Concatenate layer<br>wide_inputs = Input(shape=(5,), name=&#39;Wide-Input&#39;)<br><br># Deep<br>deep_inputs = Input(shape=(5,), name=&#39;Deep-Input&#39;)<br>deep = Dense(64, activation=&#39;relu&#39;, name=&#39;Dense-Layer-1&#39;)(deep_inputs)<br>deep = Dense(32, activation=&#39;relu&#39;, name=&#39;Dense-Layer-2&#39;)(deep)<br><br># Combine<br>combined = Concatenate(name=&#39;Concatenate-Layer&#39;)([wide_inputs, deep])<br>outputs = Dense(1, activation=&#39;linear&#39;, name=&#39;Output-Layer&#39;)(combined)  # Assuming regression problem<br><br># Create the model<br>model = Model(inputs=[wide_inputs, deep_inputs], outputs=outputs)<br><br># Plot the model<br>from tensorflow.keras.utils import plot_model<br>plot_model(model, to_file=&#39;wide_and_deep_model.png&#39;, show_shapes=True, show_layer_names=True)</pre><p>This code illustrates a basic Wide &amp; Deep architecture. The wide component directly connects the input to the output, especially sparse categorical features, capturing memorization of the data. The deep component, on the other hand, allows for generalization by capturing intricate patterns through the layers.</p><p>Below is a graph of the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*wN4WeO1Zbs4_b_Xqxf4N7g.png" /><figcaption>Wide and deep neural network architecture</figcaption></figure><h3><em>Adding Post processing step after Prediction/Output Layer</em></h3><p>Here we will look at applying post postprocessing after our output or prediction layers. An example could be the wine quality rating and you consider defining it as a regression problem for the rating to capture the order of quality. You can have conditions between intervals and assign it a specific value. For example any value &gt; 5 is mapped as 5, &lt; 1.5 is a rating of 1 etc. In the code example below we use a different post processing logic for illustration purposes.</p><p>With Keras’s flexbility this is also easy to implement. Having post processing logic in your network architecture has many benefits one being that the logic will be deployed with your model and no extra step is needed when doing inference. Here is an implementation:</p><pre>from tensorflow.keras.layers import Lambda<br>from tensorflow.keras import backend as K<br><br># Your existing model<br>inputs = Input(shape=(10,), name=&#39;Input Layer&#39;)<br>x = Dense(64, activation=&#39;relu&#39;, name=&#39;Dense-Layer-with-relu-activation&#39;)(inputs)<br>classification_outputs = Dense(10, activation=&#39;softmax&#39;, name=&#39;Classification-Output-Layer&#39;)(x)<br>regression_outputs = Dense(1, activation=&#39;linear&#39;, name=&#39;Regression-Output-Layer&#39;)(x)<br><br># Post-processing steps<br>def classification_postprocess(x):<br>    # replace with your own post-processing function<br>    return K.log(x + 1e-7)  # just an example, applying log transformation<br><br>def regression_postprocess(x):<br>    # replace with your own post-processing function<br>    return x * 100  # just an example, scaling the outputs<br><br>classification_postprocessed = Lambda(classification_postprocess, name=&#39;Classification-Postprocess&#39;)(classification_outputs)<br>regression_postprocessed = Lambda(regression_postprocess, name=&#39;Regression-Postprocess&#39;)(regression_outputs)<br><br># Define the model<br>model = Model(inputs=inputs, outputs=[classification_postprocessed, regression_postprocessed])<br><br># plot model architecture<br>from tensorflow.keras.utils import plot_model<br>plot_model(model, to_file=&#39;post_processing.png&#39;, show_shapes=True, show_layer_names=True)</pre><p>Since the preprocessing is just normal function or transformation that we apply on the output we will utilize Lambda layers for this. For production purposes you might want to create a custom layer for example. Here is the graph of our implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*xjHC34DEpa8tTXrwKettOw.png" /><figcaption>Post processing logic inside our neural network architecture</figcaption></figure><h3>Conclusion</h3><p>In this post we looked at the flexibility of Keras Functional API and how we can easily implement advanced and complex neural network architectures. To showcase the power of the functional API we used different architecture types for illustration. In a <a href="https://medium.com/mlearning-ai/creating-feature-engineering-flow-graphs-in-keras-87bb38f0b5cf">previous article </a>I showed using the functional API how to create informed feature engineering graphs where we created a feature engineering layer to show the dependencies between features.</p><p>What other types of neural networks architectures would you add to your list. Let me know in comment section.</p><h4><a href="https://mlearning.substack.com/about">WRITER at MLearning.ai</a> /<a href="https://open.substack.com/pub/mlearning/p/let-ai-agents-rescue-large-language-models?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">AI Agents LLM</a> / <a href="https://open.substack.com/pub/mlearning/p/good-bad-ai-art?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">Good-Bad AI Art</a> / <a href="https://open.substack.com/pub/mlearning/p/sensory-ai-art-experience?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">Sensory</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7394d0980880" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Novel Approach to Designing a Modular ML Lifecycle Framework with Custom Steps and Pipelines]]></title>
            <link>https://fdnieuwveldt.medium.com/a-novel-approach-to-designing-a-modular-ml-lifecycle-framework-with-custom-steps-and-pipelines-6a1e38719896?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1e38719896</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 19:44:14 GMT</pubDate>
            <atom:updated>2023-04-26T07:34:52.186Z</atom:updated>
            <content:encoded><![CDATA[<h4>Streamlining Machine Learning Development through Reusable, Customizable Steps and Pipelines</h4><h4>Introduction</h4><p>The development of machine learning projects often requires practitioners to manage multiple steps and components within the ML lifecycle. A well-structured ML lifecycle framework can streamline this process, helping developers create reusable components and maintain organized codebases. In this article, we will discuss a modular approach to designing an ML lifecycle framework using custom steps and pipelines that serve as a foundation for your projects. The approach here is novel approach or guideline to implement a frame for the ML lifecycle. We will extend two base classes that will be the foundation of our framework; i.e BaseStep and the BasePipeline.</p><p>In the following sections we will go through the following:</p><ul><li>The BaseStep</li><li>The BasePipeline</li><li>An example or use case</li></ul><h4>BaseStep: The Building Block of Custom Steps</h4><p>The BaseStep class is an abstract base class (ABC) that serves as the foundation for all steps in the ML lifecycle. Each step in the pipeline will inherit from this base class, ensuring that every step adheres to a consistent interface. This base class provides methods for saving and loading pipeline step artifacts.</p><p>The main methods and properties in this class include:</p><ul><li>run(self, *args, **kwargs): An abstract method that runs the pipeline component. Each derived class must implement this method.</li><li>metadata(self): An abstract property that returns any metadata recorded during the component run. Each derived class must implement this method.</li><li>get_init_args(cls): A class method that returns the constructor arguments of the component.</li><li>get_init_values(self): An instance method that returns the attribute values for the current instance.</li><li>The __repr__ method is also implemented to provide a readable representation of the step.</li></ul><p>Here is a <strong>possible </strong>of such a base class</p><pre>&quot;&quot;&quot;Base class for all ML Lifecycle Steps&quot;&quot;&quot;<br><br>from abc import ABC, abstractmethod<br>import pickle<br>import inspect<br><br><br>class BaseStep(ABC):<br>    &quot;&quot;&quot;Base Class for a ML pipeline step. Each step in ML life cycle will inherit from this Base class.<br>    Base clas methods mainly contains saving and loading of pipeline component artifacts .<br>    &quot;&quot;&quot;<br><br>    _type = &quot;step&quot;<br><br>    @abstractmethod<br>    def run(self, *args, **kwargs):<br>        &quot;&quot;&quot;Run the pipeline step&quot;&quot;&quot;<br>        return self<br><br>    @property<br>    @abstractmethod<br>    def metadata(self):<br>        &quot;&quot;&quot;Return any metadata that was recorded during the step run&quot;&quot;&quot;<br><br>    @classmethod<br>    def get_init_args(cls):<br>        &quot;&quot;&quot;Get constructor names&quot;&quot;&quot;<br>        # get the contructor arguments of the step<br>        init_signature = inspect.signature(cls.__init__)<br>        return sorted(<br>            [p.name for p in init_signature.parameters.values() if p.name != &#39;self&#39;]<br>        )<br><br>    def get_init_values(self):<br>        &quot;&quot;&quot;<br>        Get instance attribute values<br>        &quot;&quot;&quot;<br>        return {<br>            key: getattr(self, key) for key in self.get_init_args() <br>        }<br><br>    def set_local_components(self, local_variables):<br>        for name, var in local_variables.items():<br>            if hasattr(var, &#39;run&#39;):<br>                self.__dict__.update({name: var})<br><br>    def __repr__(self):<br>        return f&quot;Completed {self.__class__.__name__} component run&quot;</pre><p>For example, the DataLoader component inherits from the BaseStep class and implements the run() method to load data and preprocess it if necessary. Similarly, other components like DataFeatureMapper, DataValidator, ModelTrainer, ModelEvaluator, and ArtifactPusher also inherit from BaseStep and provide custom implementations for the run() method.</p><p>We will cover the following steps in the pipeline:</p><ol><li>DataLoader</li><li>DataFeatureMapper</li><li>DataValidator</li><li>ModelTrainer</li><li>ModelEvaluator</li><li>ArtifactPusher</li></ol><h4>BasePipeline: Orchestrating the ML Lifecycle</h4><p>The BasePipeline class serves as the foundation for all pipelines in the ML lifecycle framework. It contains methods for registering metadata and saving the final state of components during the pipeline execution. This base class allows developers to create pipelines that manage multiple components and their metadata efficiently.</p><p>The main methods and properties in this class include:</p><ul><li>metadata(self): A property that returns the metadata of all run pipeline components.</li><li>The __repr__ method is also implemented to provide a readable representation of the pipeline.</li></ul><pre>&quot;&quot;&quot;Base class for all pipelines&quot;&quot;&quot;<br><br>import pathlib<br>import json<br><br><br>class BasePipeline:<br>    &quot;&quot;&quot;Base class for all Pipeline. Contains metadata registring and saving final component state<br>    during pipeline&quot;&quot;&quot;<br><br>    _type = &quot;pipeline&quot;<br><br>    @property<br>    def metadata(self):<br>        &quot;&quot;&quot;Return metadata of all runned pipeline components<br>        &quot;&quot;&quot;<br>        return {component.__class__.__name__: component.metadata<br>                for _, component in self.__dict__.items() if hasattr(component, &#39;run&#39;)<br>        }<br><br>    def __repr__(self):<br>        return f&quot;Completed {self.__class__.__name__} pipeline run&quot;</pre><h4>Implementing a Modular ML Lifecycle Framework</h4><p>By using these base classes, you can create modular and reusable steps and pipelines for your machine learning projects. The BaseStep ensures that each step in the pipeline adheres to a consistent interface, while the BasePipeline class provides a foundation for constructing pipelines that can manage multiple steps and their metadata.</p><p>Here&#39;s a high-level overview of how to implement this modular ML lifecycle framework:</p><ol><li>Create custom components for each step in the ML lifecycle by inheriting from the BaseStep class and implementing the run() method and the metadata property. For example, the DataLoader, DataFeatureMapper, and other steps mentioned earlier.</li><li>Construct a pipeline using the BasePipeline class to manage the custom steps and their metadata.</li><li>Design high-level interfaces for training and inference using the custom steps</li></ol><p>By following these steps, developers can create a modular and reusable ML lifecycle framework that streamlines the development process and maintains an organized codebase.</p><h4>Example of ML Lifecycle flow</h4><p>The below example and the suggested framework above can be found in the following <a href="https://github.com/fernandonieuwveldt/mlxops-pipeline">Github</a> repo. This is a novel approach. Other packages such MLFlow pipelines, Tensorflow Extended(TFx), Kedro etc. can be used to develop robust pipelines.</p><h4><strong>DataLoader</strong>:</h4><p>The DataLoader is responsible for loading the data and performing any stateless preprocessing steps. It can load data from a file or a URL and automatically split it into training, testing, and evaluation sets using the specified splitting strategy (e.g., ShuffleSplit):</p><pre>import pandas as pd<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier, IsolationForest<br>from sklearn.metrics import accuracy_score<br>from sklearn.model_selection import ShuffleSplit<br><br># local imports<br>import mlxops<br>from mlxops.sklearn.components import (<br>  DataLoader,<br>  DataFeatureMapper,<br>  DataValidator,<br>  ModelTrainer,<br>  ModelEvaluator,<br>  ArtifactPusher<br>)</pre><pre>file_url = &quot;http://storage.googleapis.com/download.tensorflow.org/data/heart.csv&quot;<br>data_loader = DataLoader.from_file(<br>                    file_url,<br>                    target=&#39;target&#39;,<br>                    splitter=ShuffleSplit<br>)<br>data_loader.run()</pre><p>DataLoader splits data into train, test and evaulation sets. These sets can retrieved from the following properties</p><pre>data_loader.train_set<br>data_loader.test_set<br>data_loader.eval_set</pre><h4><strong>DataFeatureMapper</strong>:</h4><p>This component handles feature processing, such as normalization for numeric features and one-hot encoding for categorical features. Users can create a feature mapper based on the inferred pipeline in this, which automatically determines the appropriate transformations based on the data types of the features, or by supplying their own feature transformation pipeline</p><pre>feature_mapper = DataFeatureMapper.from_infered_pipeline()<br>feature_mapper.run(data_loader=data_loader)<br>mapped_train_features = feature_mapper.transform(data_loader.train_set[0])</pre><h4>Validator</h4><p>This component step is optional and it takes in a sklearn validator or outlier detector as input. This validator needs to implement a predict method that returns 1 for inlier and -1 for outlier. The validator component gets applied on feature mapped data from the feature_mapper step. The run method takes in a runned DataLoader and DataValidator as input.</p><pre>data_validator = DataValidator(<br>    validator=IsolationForest(contamination=0.001)<br>)<br>data_validator.run(data_loader=data_loader, feature_mapper=feature_mapper)</pre><p>The mask for the train data can be retrieved from a property method. This mask can be used in conjunction with the DataLoader component to select only relevant samples. For example</p><pre>train_data, train_targets = data_loader.train_set<br>valid_train_data, valid_train_targets = train_data[data_validator.trainset_valid],\<br>                                        train_targets[data_validator.trainset_valid]</pre><h4><strong>ModelTrainer</strong>:</h4><p>The ModelTrainer component trains a user-specified estimator (e.g., a scikit-learn classifier) using the processed data. It depends on the DataLoader, DataFeatureMapper, and DataValidator components.</p><pre>base_trainer = ModelTrainer(<br>    estimator=LogisticRegression()<br>)<br>base_trainer.run(data_loader, feature_mapper, data_validator)</pre><p>Let save this base model and build a new model. We will compare the new model against the base model later.</p><pre>mlxops.saved_model.save(base_trainer, &quot;lr_base_model&quot;)</pre><p>Let build a second challenger model using a random forest classifier</p><pre>new_trainer = ModelTrainer(<br>    estimator=RandomForestClassifier(n_estimators=50)<br>)<br>new_trainer.run(data_loader, feature_mapper, data_validator)</pre><h4>ModelEvaluator:</h4><p>The ModelEvaluator component compares the performance of two models using the specified metrics (e.g., accuracy_score from scikit-learn). It takes the DataLoader, DataFeatureMapper, DataValidator components, and a new trained model as inputs.</p><pre>evaluator = ModelEvaluator(base_model=&quot;lr_base_model&quot;, metrics=[accuracy_score])<br>evaluator.run(<br>    data_loader, feature_mapper, data_validator, new_trainer<br>)</pre><h4>ArtifactPusher:</h4><p>The ArtifactPusher component pushes the artifacts (e.g., trained models) to a specified directory if the current model is an improvement over the existing best model. The Artifact pusher takes in Evaluator as input in its run method. The evalautor has a boolean attribute push_model, which will be True if the model is performing better than the current model(s)</p><pre>pusher = ArtifactPusher(model_serving_dir=&#39;serving&#39;)<br>pusher.run(evaluator)</pre><h4>High-level interfaces for training and inference:</h4><p>For a more streamlined approach, users can create a ModelTrainingPipeline that combines all the components in a single pipeline.</p><pre>from mlxops.sklearn.pipeline import ModelTrainingPipeline<br><br><br>file_url = &quot;http://storage.googleapis.com/download.tensorflow.org/data/heart.csv&quot;<br><br>train_pipeline_arguments = {<br>    &#39;data_loader&#39;: DataLoader.from_file(<br>        file_name=file_url, target=&#39;target&#39;, splitter=ShuffleSplit<br>    ),<br>    &#39;data_validator&#39;: DataValidator(<br>        validator=IsolationForest(contamination=0.01)<br>    ),<br>    &#39;feature_mapper&#39;: DataFeatureMapper.from_infered_pipeline(),<br>    &#39;trainer&#39;: ModelTrainer(<br>        estimator=RandomForestClassifier(n_estimators=100, max_depth=3)<br>    ),<br>    &#39;evaluator&#39;: ModelEvaluator(<br>        base_model=&#39;lr_base_model&#39;,<br>        metrics=[accuracy_score]<br>    ),<br>    &#39;pusher&#39;: ArtifactPusher(model_serving_dir=&#39;serving&#39;),<br>    &quot;run_id&quot;: &quot;0.0.0.1&quot;<br>}<br><br># execute pipeline<br>train_pipeline = ModelTrainingPipeline(<br>    **train_pipeline_arguments<br>)<br>train_pipeline.run()<br>mlxops.saved_model.save(train_pipeline, &quot;base_model&quot;)</pre><p>The Pipeline will be for local running. Though you can run it in a single container for example, but usually you would want to run each step separately in its own container instance. An orchestrator such as AWS stepfunctions or Airflow be used to run each step.</p><p>The steps and pipelines here uses Pandas and SKLearn or any SKLearn type model such as XGBoost that fits in this framework with fit and predict methods.</p><p>One can also create further base classes. The DataLoader is such an example which implements methods based on Pandas. Similar classes can be created to integrate with say Dask or Tensorflow datasets. Same goes for the other steps.</p><h4>Conclusion</h4><p>This modular approach to designing an ML lifecycle framework using custom components and pipelines allows developers to focus on the crucial aspects of their projects, such as model selection and feature engineering. By creating reusable components and high-level interfaces, users can quickly prototype. This is a novel approach and gives a guideline on how such a framework can be implemented</p><h4><a href="https://mlearning.substack.com/about"><strong>BECOME a WRITER at MLearning.ai</strong></a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1e38719896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Sklearn-like Transformers in Keras: A Custom Preprocessing Layer Example]]></title>
            <link>https://fdnieuwveldt.medium.com/implementing-sklearn-like-transformers-in-keras-a-custom-preprocessing-layer-example-60688ba821e0?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/60688ba821e0</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 20:48:34 GMT</pubDate>
            <atom:updated>2023-04-23T07:40:58.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ad34XoYPBFwSu2qRd_9fDg.png" /></figure><p>In this article we will be looking at implementing a Sklearn-like transformer as a Keras Preprocessing layer. The example transformer will be the MinMax scaler.</p><p>Keras is a powerful deep learning library that enables the creation and training of neural network models. However, before training any machine learning model, it is essential to preprocess the data. Sklearn provides a variety of transformers to preprocess data, including the MinMaxScaler that scales features to a specific range. In this blog post, we will demonstrate how to implement a custom Keras preprocessing layer that behaves like Sklearn’s MinMaxScaler, using the MinMaxScalerLayer example. We will then compare the results using the same data to highlight the similarities between the two methods.</p><h4><strong>The MinMaxScalerLayer</strong></h4><p>Our custom preprocessing layer, MinMaxScalerLayer, scales features to a specified range by transforming them according to a provided feature_range. The layer can be easily integrated into a Keras model as it is a subclass of tf.python.keras.engine.base_preprocessing_layer.PreprocessingLayer. The main components of the layer are:</p><ul><li>__init__ method: Initializes the layer with the required feature range.</li><li>adapt method: Computes the minimum and maximum values for each feature in the input data; i.e contains the state for the scaler</li><li>call method: Applies the scaling transformation to the input data.</li><li>get_config method: Returns the layer configuration for serialization purposes.</li></ul><p>Here is the implementation to create an equivalent custom MinMax scaler in Keras:</p><pre>import tensorflow as tf<br><br>class MinMaxScalerLayer(tf.python.keras.engine.base_preprocessing_layer.PreprocessingLayer):<br>    def __init__(self, feature_range=(0, 1), **kwargs):<br>        super(MinMaxScalerLayer, self).__init__(**kwargs)<br>        self.feature_range = feature_range<br>        self.data_min = None<br>        self.data_max = None<br><br>    def adapt(self, data):<br>        data = tf.convert_to_tensor(data)<br>        self.data_min = tf.math.reduce_min(data, axis=0)<br>        self.data_max = tf.math.reduce_max(data, axis=0)<br><br>    def call(self, inputs):<br>        if self.data_min is None or self.data_max is None:<br>            raise RuntimeError(&quot;The layer has not been adapted. Call &#39;adapt&#39; before using the layer.&quot;)<br>        <br>        inputs = tf.convert_to_tensor(inputs)<br>        scaled_data = (inputs - self.data_min) / (self.data_max - self.data_min)<br>        return self.feature_range[0] + (scaled_data * (self.feature_range[1] - self.feature_range[0]))<br><br>    def get_config(self):<br>        config = super(MinMaxScalerLayer, self).get_config()<br>        config.update({<br>            &quot;feature_range&quot;: self.feature_range<br>        })<br>        return config</pre><h4>Comparing MinMaxScalerLayer with Sklearn’s MinMaxScaler</h4><p>To demonstrate the similarities between our custom preprocessing layer and Sklearn’s MinMaxScaler, we will use the same data for both methods and compare the results.</p><p>First, let’s generate a dataset:</p><pre>import numpy as np<br><br>data = np.random.randn(100, 10).astype(np.float32)<br>labels = np.random.randn(100, 1)</pre><p>Now, let’s preprocess the data using Sklearn’s MinMaxScaler:</p><pre>from sklearn.preprocessing import MinMaxScaler<br><br>scaler = MinMaxScaler(feature_range=(0, 1))<br>data_scaled_sklearn = scaler.fit_transform(data)</pre><p>Next, we will preprocess the data using our custom MinMaxScalerLayer:</p><pre>minmax_scaler_layer = MinMaxScalerLayer(feature_range=(0, 1))<br>minmax_scaler_layer.adapt(data)<br>data_scaled_keras = minmax_scaler_layer(data)</pre><p>Finally, we can compare the results:</p><pre>print(&quot;Sklearn MinMaxScaler result:&quot;)<br>print(data_scaled_sklearn)<br><br>print(&quot;Keras MinMaxScalerLayer result:&quot;)<br>print(data_scaled_keras.numpy())<br><br>print(&quot;Difference between Sklearn and Keras results:&quot;)<br>print(np.abs(data_scaled_sklearn - data_scaled_keras.numpy()))</pre><h4>Preparing Real-World Data</h4><p>In this section, we will demonstrate the usage of the custom MinMaxScalerLayer with a real-world dataset. We will use the UCI Machine Learning Repository’s “Wine Quality” dataset, which consists of various physicochemical properties of wines and their corresponding quality ratings.</p><p>First, let’s load the dataset and split it into features and labels:</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br><br>url = &quot;https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv&quot;<br>data = pd.read_csv(url, delimiter=&quot;;&quot;)<br>features = data.drop(&quot;quality&quot;, axis=1).values.astype(np.float32)<br>labels = data[&quot;quality&quot;].values.reshape(-1, 1)<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)</pre><h4><strong>Building and Training a Keras Model:</strong></h4><p>We will now build a simple Keras model using the custom MinMaxScalerLayer and train it on the Wine Quality dataset. The performance of the model will be evaluated on the test set.</p><pre>import tensorflow as tf<br><br># Instantiate and adapt the custom preprocessing layer<br>minmax_scaler_layer = MinMaxScalerLayer(feature_range=(0, 1))<br>minmax_scaler_layer.adapt(X_train)<br><br># Create and compile a Keras model using the custom preprocessing layer<br>model = tf.keras.Sequential([<br>    minmax_scaler_layer,<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;),<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;),<br>    tf.keras.layers.Dense(1)<br>])<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;, metrics=[&#39;mae&#39;])<br><br># Train the model<br>history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2, verbose=2)<br><br># Evaluate the model on the test set<br>test_loss, test_mae = model.evaluate(X_test, y_test, verbose=2)<br>print(f&quot;Test MAE: {test_mae:.4f}&quot;)</pre><p>This example demonstrates how to use the custom MinMaxScalerLayer in a Keras model for a real-world dataset. The layer is adapted to the training data, and it can be easily integrated into a Keras model to handle feature scaling.</p><h4>Conclusion</h4><p>In this blog post, we demonstrated how to implement a custom preprocessing layer in Keras that imitates Sklearn’s MinMaxScaler. The MinMaxScalerLayer can be easily integrated into a Keras model to handle feature scaling. By comparing the results of our custom layer with Sklearn’s MinMaxScaler, we showed that they produce similar results, highlighting the flexibility and usefulness of Keras for creating custom transformers. This approach can be extended to other preprocessing tasks, making it easier to integrate Sklearn-like transformers directly into Keras models.</p><h4><a href="https://mlearning.substack.com/about">BECOME a WRITER at MLearning.ai</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60688ba821e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Modular AWS Lambda Deployment Pipelines with Github Actions]]></title>
            <link>https://towardsaws.com/building-modular-aws-lambda-deployment-pipelines-with-github-actions-9264fa59d7ba?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9264fa59d7ba</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 09:43:07 GMT</pubDate>
            <atom:updated>2023-04-24T06:36:51.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*gI1H87qMMl7hfWSqVkqwNA.png" /></figure><p>In today’s world of serverless computing, AWS Lambda functions have become an essential tool for developers to build and deploy scalable, event-driven applications. With the growing complexity of these applications, it’s crucial to have an efficient and modular deployment pipeline. In this blog post, we will discuss the idea behind creating a modular deployment pipeline for AWS Lambda functions with custom layers and Docker containers, and how you can leverage this approach in your projects.</p><h3>The Idea Behind Modular Deployment Pipelines</h3><p>The primary goal of creating a modular deployment pipeline is to enable developers to manage and deploy different components of their AWS Lambda applications independently. This approach provides better organization, separation of concerns, and flexibility. It allows for independent updates to the custom layer or Lambda function, catering to different scenarios and requirements, while still ensuring that both components can be deployed together when needed. We also have a deployment pipeline using docker containers.</p><p>We will use the repository that implements these pipelines: <a href="https://github.com/fernandonieuwveldt/lambda-deployment-pipelines/">https://github.com/fernandonieuwveldt/lambda-deployment-pipelines/</a></p><p>Here are the descriptions of the pipelines in the repository:</p><ol><li>Custom Layer Deployment (deploy_custom_layer.yml): This pipeline deploys the custom layer independently, allowing you to update and manage the custom layer separately from the Lambda function. Useful when you need to update shared libraries or code used by multiple Lambda functions.</li><li>Lambda Function Deployment (deploy_lambda_function.yml): This pipeline deploys the Lambda function independently. Useful when you need to update the Lambda function code without modifying the custom layer.</li><li>Lambda Function Deployment as Docker Container (deploy_lambda_container.yml): This pipeline deploys the Lambda function using a Docker container. Useful when you want to package your Lambda function with a container image, which provides more flexibility in managing dependencies and runtime environment.</li><li>Both Custom Layer and Lambda Function Deployment (deploy_lambda_function_and_layer.yml): This pipeline deploys both the custom layer and the Lambda function together by utilizing the other two pipelines. Useful when you need to deploy updates to both components simultaneously.</li></ol><p>In this article we will be looking at 2 of them.</p><h3>Benefits of Modular Deployment Pipelines</h3><ol><li>Modularity: The separation of the deployment pipelines allows for better organization and independent updates to either component.</li><li>Flexibility: The ability to deploy the custom layer or Lambda function independently caters to different scenarios and requirements, while the combined deployment pipeline ensures that both components can be deployed together when needed. The docker container lambda solution provides even more flexibility</li><li>Version control: By using GitHub Actions in combination with your source code repository, you can keep track of changes to the custom layer, Lambda function, and their dependencies over time. This makes it easier to identify issues and roll back to previous versions if necessary.</li><li>Collaboration: A modular pipeline approach makes it easier for team members to collaborate on different aspects of the project, as they can contribute changes through pull requests and rely on the pipeline to automatically deploy the necessary components upon merging.</li><li>Time-saving and consistency: By automating the build and deployment process, developers can focus on writing code and improving the application, rather than spending time on manual deployment tasks. The pipelines also ensure consistent packaging and deployment of the components across different environments, reducing the risk of errors due to manual processes or misconfigurations.</li></ol><h3>Leveraging Cookiecutter for Easy Project Setup</h3><p>To make it easy for users to leverage the modular deployment pipelines in their projects, we created a Cookiecutter template. Cookiecutter is a command-line utility that generates projects from project templates, allowing developers to quickly set up and customize their applications.</p><p>To create a Cookiecutter template for the modular deployment pipelines, follow these steps:</p><ol><li>Install Cookiecutter: pip install cookiecutter</li><li>To generate a new project based on the template, run: cookiecutter <a href="https://github.com/fernandonieuwveldt/lambda-deployment-pipelines">https://github.com/fernandonieuwveldt/lambda-deployment-pipelines</a></li></ol><p>Users can then easily set up their own Lambda function projects with the modular deployment pipelines by using the Cookiecutter template. There are 4 pipelines, but with the post_gen_project.py we remove the templates of the non selected pipeline to keep your folders clean.</p><h3>Example YAML Code for Modular Deployment Pipelines</h3><p>Here are examples of YAML code for deploying Lambda functions. We will look specifically on how to deploy lambda function using docker containers and also how to build and publish a custom layer. Please see the repo for other examples as stated above.</p><p>These pipelines utilize GitHub Actions for building, packaging, and deploying the components to AWS Lambda. We will be looking at two types of pipelines:</p><h3>Deploying a custom layer</h3><pre>name: Deploy Custom Layer<br><br>env:<br>  LAYER_NAME: {{ cookiecutter.layer_name }}<br>  S3_BUCKET: {% raw %}${{ secrets.S3_BUCKET }}{% endraw %}<br><br>on:<br>  workflow_dispatch:<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v2<br><br>    - name: Set up Python<br>      uses: actions/setup-python@v2<br>      with:<br>        python-version: 3.9<br><br>    - name: Configure AWS credentials<br>      uses: aws-actions/configure-aws-credentials@v1<br>      with:<br>        aws-access-key-id: {% raw %}${{ secrets.AWS_ACCESS_KEY_ID }}{% endraw %}<br>        aws-secret-access-key: {% raw %}${{ secrets.AWS_SECRET_ACCESS_KEY }}{% endraw %}<br>        aws-region: {% raw %}${{ secrets.AWS_REGION }}{% endraw %}<br><br>    - name: Package custom layer<br>      run: |<br>        mkdir -p my_layer/python<br>        pip install -r layer_requirements.txt -t my_layer/python<br>        cp -r layers/* my_layer/python<br>        cd my_layer<br>        zip -r ../custom_layer.zip .<br>  <br>    - name: Upload custom layer to S3<br>      run: |<br>        aws s3 cp custom_layer.zip s3://$S3_BUCKET/$LAYER_NAME.zip<br><br>    - name: Publish custom layer<br>      run: |<br>        aws lambda publish-layer-version \<br>            --layer-name $LAYER_NAME \<br>            --content S3Bucket=$S3_BUCKET,S3Key=$LAYER_NAME.zip</pre><p>We need a layer_requirements.txtfile that will be used to build the layer. The zip file will be loaded to an s3 bucket for versioning. We can add a specific tag to it like a version number or a github run number. The final step is to publish the layer to Lambda.</p><h3>Deploy lambda function using Docker containers</h3><pre>name: Deploy Lambda function with Docker container<br><br>env:<br>  ECR_REPOSITORY: {{ cookiecutter.ecr_repository }}<br>  LAMBDA_ROLE_ARN: {{ cookiecutter.lambda_function_role_arn }}<br>  LAMBDA_CONTAINER_NAME: {{ cookiecutter.lambda_container_name }}<br>  # set env from secrets<br>  AWS_REGION: {% raw %}${{ secrets.AWS_REGION }}{% endraw %}<br>  AWS_ACCOUNT: {% raw %}${{ secrets.AWS_ACCOUNT }}{% endraw %}<br><br>on:<br>  workflow_dispatch:<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v2<br><br>    - name: Set up Python<br>      uses: actions/setup-python@v2<br>      with:<br>        python-version: 3.9<br><br>    - name: Configure AWS credentials<br>      uses: aws-actions/configure-aws-credentials@v1<br>      with:<br>        aws-access-key-id: {% raw %}${{ secrets.AWS_ACCESS_KEY_ID }}{% endraw %}<br>        aws-secret-access-key: {% raw %}${{ secrets.AWS_SECRET_ACCESS_KEY }}{% endraw %}<br>        aws-region: {% raw %}${{ secrets.AWS_REGION }}{% endraw %}<br><br>    - name: Login to Amazon ECR<br>      id: login-ecr<br>      uses: aws-actions/amazon-ecr-login@v1<br><br>    - name: Build and Push Docker Image<br>      uses: docker/build-push-action@v2<br>      with:<br>        context: .<br>        push: true<br>        tags: $AWS_ACCOUNT.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPOSITORY:{% raw %}${{ github.sha }}{% endraw %}<br>  <br>    - name: Deploy Lambda function<br>      run: |<br>        export IMAGE_TAG={% raw %}${{ github.sha }}{% endraw %}<br>        export IMAGE_URI=$AWS_ACCOUNT.dkr.ecr.$AWS_REGION.amazonaws.com/$ECR_REPOSITORY:{% raw %}${{ github.sha }}{% endraw %}<br>        FUNCTION_ARN=$(aws lambda get-function --function-name $LAMBDA_CONTAINER_NAME --query &#39;Configuration.FunctionArn&#39; --output text || true)<br>        <br>        if [ -z &quot;$FUNCTION_ARN&quot; ]; then<br>          aws lambda create-function \<br>              --function-name $LAMBDA_CONTAINER_NAME \<br>              --role arn:aws:iam::$AWS_ACCOUNT:role/service-role/$LAMBDA_ROLE_ARN \<br>              --package-type Image --code ImageUri=$IMAGE_URI \<br>              --timeout 15 \<br>              --memory-size 256<br>        else<br>         aws lambda update-function-code \<br>              --function-name $LAMBDA_CONTAINER_NAME \<br>              --image-uri $IMAGE_URI \<br>              --publish<br>        <br>        # wait for the lambda function to complete the update before applying any config<br>        aws lambda wait function-updated \<br>          --function-name $LAMBDA_CONTAINER_NAME<br><br>         aws lambda update-function-configuration \<br>           --function-name $LAMBDA_CONTAINER_NAME \<br>           --timeout 15 \<br>           --memory-size 256<br>        fi</pre><p>The Deploy Lambda function with docker container. We need to build a docker image and push it to ECR. Here is an example of the Dockerfile:</p><pre># Use AWS-provided base image for Python<br>FROM public.ecr.aws/lambda/python:3.9<br><br># Copy function code and dependencies<br>COPY container/app.py ${LAMBDA_TASK_ROOT}<br>COPY requirements.txt ./<br><br># Install dependencies<br>RUN pip install -r requirements.txt<br><br># Set the CMD to your handler (replace `app.lambda_handler` with your specific handler)<br>CMD [&quot;app.lambda_handler&quot;]</pre><p>We need a requirements.txt file with our packages that we want to install. Finally for this example we have an app.py</p><pre>import requests<br><br><br>def lambda_handler(event, context):<br>    print(&quot;triggered with workflow dispatch&quot;)<br>    response = requests.get(&#39;https://api.github.com&#39;)<br>    return {<br>        &#39;statusCode&#39;: response.status_code,<br>        &#39;body&#39;: response.content<br>    }</pre><p>For this example the only package we need to install is the requests library. This only for illustration purposes and we are using the requests libary on the github api.</p><h3>A note on the IAM user and role permissions</h3><p>In your AWS account, create an IAM user with programmatic access and attach a policy with the required permissions. Store the AWS access key ID and secret access key as secrets in your GitHub repository with the names AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Also need to add a AWS_ACCOUNT secret and s3 bucket details.</p><p>The following IAM policy should be attached to the IAM user the github actions is running on. This is the case for deploying lambda functions and custom layers.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;iam:ListRoles&quot;,<br>                &quot;lambda:CreateFunction&quot;,<br>                &quot;lambda:UpdateFunctionCode&quot;,<br>                &quot;lambda:PublishLayerVersion&quot;,<br>                &quot;lambda:UpdateFunctionConfiguration&quot;,<br>                &quot;lambda:DeleteLayerVersion&quot;,<br>                &quot;lambda:UpdateLayerVersion&quot;,<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:PutObjectAcl&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::your-s3-bucket-name/*&quot;,<br>                &quot;arn:aws:lambda:*:*:function:&lt;your lambda function name&gt;&quot;,<br>                &quot;arn:aws:lambda:*:*:layer:&lt;your custom layer name&gt;&quot;,<br>                &quot;arn:aws:lambda:*:*:layer:&lt;your custom layer name&gt;:*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>An example for the IAM policy to deploy a lambda docker container. These are the minimum permissions you will need:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;iam:ListRoles&quot;,<br>                &quot;ecr:CreateRepository&quot;,<br>                &quot;ecr:DescribeRepositories&quot;,<br>                &quot;ecr:GetAuthorizationToken&quot;,<br>                &quot;ecr:InitiateLayerUpload&quot;,<br>                &quot;ecr:UploadLayerPart&quot;,<br>                &quot;ecr:CompleteLayerUpload&quot;,<br>                &quot;ecr:BatchCheckLayerAvailability&quot;,<br>                &quot;ecr:PutImage&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::your-s3-bucket-name/*&quot;,<br>                &quot;arn:aws:lambda:*:123456789012:function:&lt;your lambda function name&gt;&quot;,<br>                &quot;arn:aws:lambda:*:123456789012:layer:&lt;your custom layer name&gt;&quot;,<br>                &quot;arn:aws:lambda:*:123456789012:layer:&lt;your custom layer name&gt;:*&quot;,<br>                &quot;arn:aws:ecr:*:123456789012:repository/&lt;your ecr repository&gt;&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>Finally, to create a new AWS Lambda function, the IAM role used to create the function should have permissions to perform the following actions:</p><ul><li>lambda:CreateFunction - this permission allows the role to create a new Lambda function.</li><li>lambda:UpdateFunctionCode - this permission allows the role to update the code of an existing Lambda function.</li><li>lambda:UpdateFunctionConfiguration - this permission allows the role to update the configuration of an existing Lambda function.</li></ul><p>To grant these permissions to the IAM role, you can attach an appropriate IAM policy to the role. Here’s an example policy that grants these permissions:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;lambda:CreateFunction&quot;,<br>                &quot;lambda:UpdateFunctionCode&quot;,<br>                &quot;lambda:UpdateFunctionConfiguration&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><h3>Conclusion</h3><p>In this blog post, we have explored the idea behind creating modular deployment pipelines for AWS Lambda functions with custom layers and Docker containers. By using GitHub Actions and a modular approach, we can simplify the deployment process, improve collaboration, and save time for developers. Additionally, using a Cookiecutter template makes it easy for other users to leverage this modular pipeline approach in their projects.</p><p>With these modular deployment pipelines, you can efficiently manage and deploy your AWS Lambda applications, making your development process more streamlined and consistent.</p><h4>The DynamoDB Book(35% OFF)</h4><p>Master DynamoDB. Use code ‘TOWARDSAWS’ during checkout. <a href="https://gumroad.com/a/49071827">Buy here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*wOSe2NxjKU5TTFbfk2FIRQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9264fa59d7ba" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/building-modular-aws-lambda-deployment-pipelines-with-github-actions-9264fa59d7ba">Building Modular AWS Lambda Deployment Pipelines with Github Actions</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Feature Engineering Flow Graphs in Keras]]></title>
            <link>https://fdnieuwveldt.medium.com/creating-feature-engineering-flow-graphs-in-keras-87bb38f0b5cf?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/87bb38f0b5cf</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 21:03:19 GMT</pubDate>
            <atom:updated>2022-09-06T05:44:42.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwnExqe720PPHykHhs5Hqw.png" /></figure><p>In this blog we will look at creating plots while building up our feature engineering flow graph natively with Keras layers. At each step we will plot the status of our feature graph. At the end we will have an informative graph of how our features were created and how they flow into each other. We will also see the interdependency of the features or steps. For illustration purposes we will utilise Lambda layers too easily create new feature layers. The code here is similar to <a href="https://medium.com/mlearning-ai/feature-engineering-using-keras-lambda-layers-ae0c6d3c904f">this blog post</a>. For this article we only focus on creating informative feature graphs.</p><p><strong><em>(Click on the Graphs to enlarge)</em></strong></p><p>We will use the same dataset used in the article mentioned above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53c96cd7db947f743d7d5e5de2e673dd/href">https://medium.com/media/53c96cd7db947f743d7d5e5de2e673dd/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a01d115d7a77c583a8bcc4b3d8bf2d7/href">https://medium.com/media/0a01d115d7a77c583a8bcc4b3d8bf2d7/href</a></iframe><p>Next we define a function to create our Input layers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82a884a29b3949b9f574875b1d340976/href">https://medium.com/media/82a884a29b3949b9f574875b1d340976/href</a></iframe><p>To create our feature graphs we need a Keras model object with inputs and outputs. So far we only have the Input layer so both our inputs and outputs will be the feature layer inputs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a31a0c7681b69110bcd3dd0a067271/href">https://medium.com/media/80a31a0c7681b69110bcd3dd0a067271/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hydaKj0sBcxG9dmvSeTjkw.png" /></figure><h4>Feature Engineering with Keras Lambda Layers</h4><p>Lets define the feature engineering functions:(The engineered features are only for illustration purposes)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44118c311a453aed923734e503175ef5/href">https://medium.com/media/44118c311a453aed923734e503175ef5/href</a></iframe><h4>Create custom Feature Engineering Layer</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8852857f05ddab2ad8e1bb5a21bcf160/href">https://medium.com/media/8852857f05ddab2ad8e1bb5a21bcf160/href</a></iframe><h4>Visualise the Feature Engineering Layers</h4><p>So far we have our input layer where the inputs feeds into the different Lambda layers. Below is our feature graph we have thus far. Note that some of the input layer’s features does not feed into any other layers. We will add this in the next section. Our inputs to the network is still our feature layer inputs, but our outputs of the network is our feature layer computed with the Lambda layers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a93225bfcf91a3b3b4226c13828b130/href">https://medium.com/media/9a93225bfcf91a3b3b4226c13828b130/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUYhSJkC6Hjrg37BbkbFQg.png" /></figure><h4>Combine all feature to create a complete Feature Layer:</h4><p>Lets combine the layers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0964195dab251624c62a768965e4a789/href">https://medium.com/media/0964195dab251624c62a768965e4a789/href</a></iframe><h4>Visualising the Feature Layer Graph</h4><p>This our complete Feature Engineering Flow Graph. This is a good way to see if you apply certain preprocessing layers for example the batch norm to the correct features. Initially I had the categorical features batch normalised as well which I noticed when looking at my feature graph. In the below graph only the numerical were normalised. And only after they are normalised the categorical and numerical features gets joined as our complete feature layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bf982e32e80f7d0ed5d1b6b8b2bfa02/href">https://medium.com/media/4bf982e32e80f7d0ed5d1b6b8b2bfa02/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mS-1gXU9KRaIDiKzIOYqYA.png" /></figure><p>For completeness we will train the model to show that everything works as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa13d6367b34e0874400657569dd006/href">https://medium.com/media/4fa13d6367b34e0874400657569dd006/href</a></iframe><p>The complete network graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7ouorun0jy0F7F2Gg1tPw.png" /></figure><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87bb38f0b5cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building advanced custom Feature transformation Pipelines in Keras using EasyFlow.]]></title>
            <link>https://fdnieuwveldt.medium.com/building-advanced-custom-feature-transformation-pipelines-in-keras-using-easyflow-4c5fce545dc2?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c5fce545dc2</guid>
            <category><![CDATA[machine-learning-design]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Thu, 21 Jul 2022 16:44:38 GMT</pubDate>
            <atom:updated>2023-04-25T06:02:13.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imH3ZOX-Y5vuVAWpQ7Gk3g.png" /></figure><p>In this post we will show case how to apply different transformations and preprocessing steps on the same feature. What we have here is an example of a <strong>Single Input Multiple Output</strong> feature transformation scenario.</p><p>This is what the feature transformation <strong>Pipeline</strong> looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ef836197b05a9488b1ed3449443c4e7/href">https://medium.com/media/3ef836197b05a9488b1ed3449443c4e7/href</a></iframe><p>We will be utilising a library called <strong>easyflow</strong> which implements feature transformation pipelines natively implemented in Keras (https://pypi.org/project/easy-tensorflow/ or <a href="https://github.com/fernandonieuwveldt/easyflow">https://github.com/fernandonieuwveldt/easyflow</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd05aa7e811d8d0ac503238040a0f323/href">https://medium.com/media/cd05aa7e811d8d0ac503238040a0f323/href</a></iframe><p>For our example we will use the imdb reviews dataset. The steps here is similar to the preprocessing example on the Tensorflow blog: <a href="https://blog.tensorflow.org/2021/11/an-introduction-to-keras-preprocessing.html.">https://blog.tensorflow.org/2021/11/an-introduction-to-keras-preprocessing.html.</a> We will however make use of the Feature Preprocessing and Transformation Pipelines from the <strong>EasyFlow</strong> library.</p><h4>Loading of the data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae00fd5a7ef0b3ffbcc07dbc8be03844/href">https://medium.com/media/ae00fd5a7ef0b3ffbcc07dbc8be03844/href</a></iframe><h4>Create Feature transformation Pipeline</h4><p>Let’s create our feature transformation Pipeline. For this example we only have one raw feature; <strong><em>review</em></strong> . The transformations that we will be applying is:</p><ol><li><strong>TextVectorization</strong> as one step and;</li><li>Another step transforming text to the length of the review and then normalising it.</li></ol><p>These steps will be concatenated in our final output layer. The transformation layer we will be using is a custom layer implemented in <strong>easyflow</strong> namely <strong>MultiOutputTransformer</strong> . EasyFlow is python package that contains high level buildings blocks to create custom feature transformation flows in a structured way. This layer takes as input a list of independent preprocessing or transformation steps (composed of layers) that will be applied on the giving feature. MultiOutputTransformer is used as a step in <strong>FeaturePreprocessor</strong> and/or <strong>FeatureUnion</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61a144468bfabbc6bfba831a30d84551/href">https://medium.com/media/61a144468bfabbc6bfba831a30d84551/href</a></iframe><p>Lets define our input layer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/519387ae7b9a8d258e634351387c2863/href">https://medium.com/media/519387ae7b9a8d258e634351387c2863/href</a></iframe><h4>Fitting the model</h4><p>For completeness of this example, we will use the common pattern for training by creating a model that applies the preprocessing to speed up training. When we start from raw data as in our example. We need to preprocess all string operations on the CPU and then feed that to a GPU. Preprocessing is also not something that we train and it is independent from the forward pass. This will reduce our throughput as the GPU will be idle while waiting for data. To speed things up we will prefetch batches of preprocessed data. This will ensure that while we processing batch of data on the GPU the CPU is getting the next batch of preprocessed data ready.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebbed7598a3c7f93eeda9adadeea2875/href">https://medium.com/media/ebbed7598a3c7f93eeda9adadeea2875/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83628554aa28e9592dc2edebacfc15e1/href">https://medium.com/media/83628554aa28e9592dc2edebacfc15e1/href</a></iframe><p>In this post we showed how we can create more advanced feature transformation and preprocessing pipelines using <strong>EasyFlow </strong>and the Keras functional API show casing the flexibility of both and the power of Keras’s api.</p><p>See Google <a href="https://colab.research.google.com/github/fernandonieuwveldt/easyflow/blob/develop/examples/single_input_multiple_output/single_input_multiple_output_preprocessor.ipynb"><strong><em>Colab notebook</em></strong></a><strong><em> </em></strong>to run this example.</p><h4><a href="https://mlearning.substack.com/about">BECOME a WRITER at MLearning.ai</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c5fce545dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating an Sklearn model training Pipeline to Tensorflow Keras.]]></title>
            <link>https://fdnieuwveldt.medium.com/migrating-an-sklearn-model-training-pipeline-to-tensorflow-keras-d248754f991d?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d248754f991d</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[machine-learning-systems]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 05:22:21 GMT</pubDate>
            <atom:updated>2022-08-13T10:32:33.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*tAOraGyTG26uLs7HGxSQkw.png" /><figcaption>Image source: <a href="https://medium.com/towards-data-science/from-scikit-learn-to-tensorflow-part-1-9ee0b96d4c85">https://medium.com/towards-data-science/from-scikit-learn-to-tensorflow-part-1-9ee0b96d4c85</a></figcaption></figure><p>In this post we look at ways to migrate an Sklearn training pipeline to Tensorflow Keras. There might be a few reasons to move from Sklearn to Tensorflow.</p><h4>Possible benefits:</h4><ul><li>Flexibility to basically any ML model architecture.</li><li>Distributed training utilising GPUs.</li><li>Flexibility when it comes to retraining.</li><li>Tensorflow serving.</li><li>etc.</li></ul><h4>Objectives</h4><ul><li>We will implement a model training pipeline with Sklearn.</li><li>Implement the same pipeline using only Tensorflow Keras modules. Preprocessing layers will used here.</li><li>Use <strong>EasyFlow</strong> for equivalent pipelines such as Sklearn’s Pipeline and ColumnTransformer module.</li></ul><p>Probably the most common use case comes from designing a ML pipeline where your preprocessing is implemented in Sklearn and model in Keras. We will have different artifacts for each part. With Keras and the EasyFlow module it will be easy to implement a native Keras solution.</p><p>For our dataset we will use the popular heart dataset. It consists of a mix of feature types such as numerical, categorical feature encoded as int’s and as strings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95f707d71084a40ae3394d8deb0027fb/href">https://medium.com/media/95f707d71084a40ae3394d8deb0027fb/href</a></iframe><p>Lets setup our Sklearn training Pipeline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/252afd1bbb5dc922131bc61943075c71/href">https://medium.com/media/252afd1bbb5dc922131bc61943075c71/href</a></iframe><p>The above Pipeline is not very involved and easy to implement. The idea here is to show how we can go about implementing an equivalent Pipeline in Tensorflow Keras.</p><h3>Migrate Sklearn Pipeline to Tensorflow Keras</h3><p>Let’s create our feature preprocessing Pipeline natively in Keras. We will duplicate the same pipeline as implemented in the Sklearn section. Keras recently added preprocessing layers. The Keras equivalent preprocessors for <strong>StandardScaler</strong> and <strong>OneHotEncoder</strong> is <strong>Normalization</strong> and <strong>IntegerLookup</strong> respectively. When our categorical features are of type string we first need to apply StringLookup preprocessing layer followed by IntegerLookup layer.</p><p>The last thing we need is a Keras implementation for Pipeline and ColumnTransformer. There is currently no implementation in Keras so we will use another package for this:</p><p>EasyFlow : <a href="https://pypi.org/project/easy-tensorflow/">https://pypi.org/project/easy-tensorflow/</a></p><p><strong><em>pip install easy-tensorflow</em></strong></p><p><strong>EasyFlow</strong> makes use of Keras preprocessing layers. All high level pipelines in <strong>EasyFlow</strong> such as <strong>FeatureUnion</strong> subclasses tf.keras.layers.Layer and thus behave like any other Keras layer. (<strong>FeatureUnion</strong> is equivalent to Sklearn’s <strong>ColumnTransformer</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51af023b08132c1f8ffa91cf1fd0c19e/href">https://medium.com/media/51af023b08132c1f8ffa91cf1fd0c19e/href</a></iframe><p>We will be making use of the Keras functional API. So we first need to create a feature input layer. Below we have a data type mapping dict as input to <strong>FeatureInputLayer. </strong>Next we will use <strong>FeatureUnion</strong> from EasyFlow module to implement similar preprocessing pipeline to ColumnTransformer. We will update the preprocessing layer states by running <em>adapt </em>method on our data. Keras preprocessing layers uses <em>.</em><a href="https://gist.github.com/fernandonieuwveldt/ebb5a67415f462f1aa09ebd2913eca1a"><strong><em>adap</em></strong></a><strong><em>t</em></strong><em> </em>to update states and in this case similar to <em>.</em><strong><em>fit</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1dc490bd83ba7b8783581c9375f3990/href">https://medium.com/media/a1dc490bd83ba7b8783581c9375f3990/href</a></iframe><p>As stated FeatureUnion and all other Pipelines in EasyFlow are Keras layers and are also callable. Below we setup our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fd66c61c54d0196a17e50398714f021/href">https://medium.com/media/1fd66c61c54d0196a17e50398714f021/href</a></iframe><p>The results are similar to the Sklearn results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d543696aaa2ffdb134a550aecc55eae/href">https://medium.com/media/5d543696aaa2ffdb134a550aecc55eae/href</a></iframe><p>That is it! We successfully ported an Sklearn training pipeline to Tensorflow Keras by utilising preprocessing layers and EasyFlow’s feature preprocessing pipelines. We also persisted the model and loaded it for inference to showcase that it is truly end to end. The results compares well with our Sklearn implementation. Huge advantage here is the fact that preprocessing is part of the network and persisted as such. Without Keras preprocessing layers and EasyFlow’s pipeline implementation we usually had a separate Sklearn artifact for preprocessing. Using Sklearn for preprocessing and then feeding data to a Keras model used to be a common design pattern. With serving containers such as Tensorflow serving that can serve our models without python or Tensorflow installation makes this migration to a native Tensorflow Keras implementation very appealing. All you need a saved model.</p><p>We can go one step further to improve our training speed. See next section.</p><h3>Quick note on improving Keras training speed.</h3><p>Next we will use the common pattern for training by creating 1) a Keras model object that applies the preprocessing step and 2) a Keras model object that does the training to speed up the process. When we start from raw data as in our example. We need to preprocess all preprocessing operations on the CPU and then feed that data to a GPU. Preprocessing is also not something that we train and it is independent from the forward pass. This will reduce our throughput as the GPU will be idle while waiting for data. To speed things up we will prefetch batches of preprocessed data. This will ensure that while we processing batch of data on the GPU the CPU is getting the next batch of preprocessed data ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vrxz6GDA4TKSUMnEKKFHpQ.png" /><figcaption><em>Image taken from </em><a href="https://www.tensorflow.org/"><em>https://www.tensorflow.org</em></a></figcaption></figure><p>Below we implement a preprocessing_model and a training_model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/840b2c12f9154a6e1a89de54c0f0f6ef/href">https://medium.com/media/840b2c12f9154a6e1a89de54c0f0f6ef/href</a></iframe><p>Next we will map the Pandas data frame to tf.data.Dataset type. The preprocessing model above will be mapped onto our feature data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/041cc8ca9421b458d473b1bf0a74182a/href">https://medium.com/media/041cc8ca9421b458d473b1bf0a74182a/href</a></iframe><p>This gives similar results as our implementation in the previous section, but much faster.</p><p>We need one last step to create a model that can be used for inference. Since we splitted the model into a preprocessing and training step we can’t save training_model as is. We need to combine the preprocessing and training into one model. Let’s create our inference model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bca98836a324223e06fd7ff2773410de/href">https://medium.com/media/bca98836a324223e06fd7ff2773410de/href</a></iframe><p>In conclusion we showed how we can migrate an Sklearn training pipeline to Tensorflow and Keras. We started off by building our training pipeline in Sklearn consisting of a preprocessing step and we used LogisticRegression as our estimator. We used the same Sklearn pipeline and migrated it to Keras using preprocessing layers and EasyFlow Pipeline modules. Our model architecture was a simple linear model(LogisticRegression equivalent) with no hidden layers. Our feature preprocessing was part of our network architecture and we persisted and loaded the model to apply inference. We ended up with a final section on improving training speed by splitting the preprocessing and model steps for training. At the end we added the preprocessing back with the training model to create our inference model.</p><p><strong><em>Google Colab Notebook</em></strong>: <a href="https://colab.research.google.com/github/fernandonieuwveldt/easyflow/blob/develop/examples/migrating_from_sklearn_to_keras/migrate_sklearn_pipeline.ipynb">notebook link</a></p><p><strong><em>References: </em></strong><a href="https://pypi.org/project/easy-tensorflow/">https://pypi.org/project/easy-tensorflow/</a></p><p><strong><em>Github repo</em></strong>: <a href="https://github.com/fernandonieuwveldt/easyflow">https://github.com/fernandonieuwveldt/easyflow</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d248754f991d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering using custom Keras Layers for a complete training and inference pipeline.]]></title>
            <link>https://fdnieuwveldt.medium.com/feature-engineering-using-custom-keras-layers-part-2-aead2b89ee06?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/aead2b89ee06</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[machine-learning-systems]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 21:34:21 GMT</pubDate>
            <atom:updated>2022-07-05T17:01:36.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kAvwH89NumNaTd1kzo36w.png" /></figure><p>In a previous <a href="https://medium.com/mlearning-ai/feature-engineering-using-keras-lambda-layers-ae0c6d3c904f">post</a> we looked at applying feature engineering with Keras Lambda layers. We also mentioned that Lambda layers have some serialization limitations. In this post we will see how we can overcome these issues by subclassing Keras Layer interface and create custom layers to achieve feature engineering.</p><p>Quick recap on the previous post:</p><p>We implemented a training and inference pipeline natively with Keras/Tensorflow. From loading data with tf.data. We utilized Lambda layers for feature engineering. We ended up with a training pipeline where feature engineering was part of the network architecture and can be persisted and loaded for inference as standalone. From a design and serving perspective this has some benefits if for example one used Tensorflow serving to serve models. Data does not need to be engineered with a different library before feeding it your serving endpoint.</p><p>Steps we will follow:</p><ul><li>Load data with tf.data</li><li>Create Input layer</li><li>Subclass Keras Layer class</li><li>Train model</li></ul><p>We will again use the heart disease dataset. Lets import tensorflow and read in the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df4f1c598f30f29df72cf10be4412777/href">https://medium.com/media/df4f1c598f30f29df72cf10be4412777/href</a></iframe><p>Create a dictionary of Input objects for each feature:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82a884a29b3949b9f574875b1d340976/href">https://medium.com/media/82a884a29b3949b9f574875b1d340976/href</a></iframe><p>We will look at two ways to create our Feature layer. Scenario 1 is using multiple custom Keras layers for the different features and Scenario 2 uses only one layer.</p><h4>Scenario 1: Multiple custom Layers</h4><p>Here we will create separate custom layers for the different features and as a final step we will concatenate our layers to create one complete feature layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a34b709cdbf9c3057172fbe1e0a32a13/href">https://medium.com/media/a34b709cdbf9c3057172fbe1e0a32a13/href</a></iframe><p>Let us build up our graph using our custom layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccfeb5430819eb6f4d6f56a958736ed9/href">https://medium.com/media/ccfeb5430819eb6f4d6f56a958736ed9/href</a></iframe><p>Next we will create a Keras Model to aid in visualising our network graph. This will illustrate how everything flows together and showcases layer dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8b79364c801bf62b5733c07d42c4be9/href">https://medium.com/media/c8b79364c801bf62b5733c07d42c4be9/href</a></iframe><p>This will produce the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdsUtHLL40rYd18YtPitxA.png" /></figure><p>Scenario 1 has a bit of steps, but one ends up with an informative graph showing how all the inputs feeds into the network and how the features are created. In the next section we will use a single custom layer to create the same features as above. We will however not be able to plot the same graph as below as the feature layer will be contained in one.</p><h4>Scenario 2: Single custom layer</h4><p>In this section we will implement a simpler feature layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4a483f25e414f422be751f69a2e5909/href">https://medium.com/media/d4a483f25e414f422be751f69a2e5909/href</a></iframe><p>This is all we need if we use only one layer. Lets compile and build our model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ec2a60f3ddb51e5a766035d4d3296fd/href">https://medium.com/media/3ec2a60f3ddb51e5a766035d4d3296fd/href</a></iframe><p>In conclusion we showed two ways to implemented custom layers for feature engineering. Scenario 1 used multiple layers and involved more steps to implement, but also produced an informative graph displaying the flow of features. Scenario 2 was quicker and had less steps to implement.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aead2b89ee06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering using Keras Lambda Layers for complete training pipeline.]]></title>
            <link>https://fdnieuwveldt.medium.com/feature-engineering-using-keras-lambda-layers-ae0c6d3c904f?source=rss-1a1ed1ae9d3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae0c6d3c904f</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Fernando Nieuwveldt]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 12:25:14 GMT</pubDate>
            <atom:updated>2022-01-22T20:01:19.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrvMKrWMhi3HomoiTLPsfw.png" /></figure><p>Often for structured data problems we end up using multiple libraries for preprocessing or feature engineering. We can go as far as having a full ML training pipeline using different libraries for example Pandas for reading data and also feature engineeering, sklearn for encoding features for example OneHot encoding and Normalization. The estimator might be an sklearn classifier, xgboost or it can for example be a Keras model. In the latter case, we would end up with artifacts for feature engineering and encoding and also different artifacts for the saved model. The pipeline is also disconnected and an extra step is needed to feed encoded data to the Keras model. For this step the data can be mapped from a dataframe to something like tf.data.Datasets type or numpy array before feeding it to a Keras model.</p><p>In this post we will consider implementing a training pipeline natively with Keras/Tensorflow. From loading data with tf.data. As the the title suggested we will use Lambda layers for feature engineering. These engineered features will be stateless. For stateful preprocessing we could use something like Keras preprocessing layers. We will end up with a training pipeline where feature engineering will be part of the network architecture and can be persisted and loaded for inference as standalone.</p><p><em>Keep in mind that tf.keras.layers.Lambda layers have (de)serialization limitations because Lambda layers are saved by serializing the python bytecode.</em></p><p>Steps we will follow:</p><ul><li>Load data with tf.data</li><li>Create Input layer</li><li>Create feature layer using Lambda layers</li><li>Train model</li></ul><p>For the example below we will use the heart disease dataset. Lets import tensorflow and read in the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cada9cbfec2df1115fcafc387c549842/href">https://medium.com/media/cada9cbfec2df1115fcafc387c549842/href</a></iframe><p>Create a dictionary of Input objects for each feature:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82a884a29b3949b9f574875b1d340976/href">https://medium.com/media/82a884a29b3949b9f574875b1d340976/href</a></iframe><p>We will be using Lambda layers in this example for feature engineering. Below are the functions that we will use to create our engineered features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44118c311a453aed923734e503175ef5/href">https://medium.com/media/44118c311a453aed923734e503175ef5/href</a></iframe><p>Now that we have our functions lets create the features as Lambda layers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa869d2acc3355ee5dd12bc0034884e2/href">https://medium.com/media/aa869d2acc3355ee5dd12bc0034884e2/href</a></iframe><p>All our engineered feature layers are created and we can now combine it with our other features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c7eac993576003b70bc7d5a87bb4b3d/href">https://medium.com/media/9c7eac993576003b70bc7d5a87bb4b3d/href</a></iframe><p>Our last step is to create and fit our Keras model. For this example we will use a simple model architecture. We will persist the model and load it for inference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc90e112e0acc1c6ab03b4baf930b58f/href">https://medium.com/media/dc90e112e0acc1c6ab03b4baf930b58f/href</a></iframe><p>To conclude we were able to successfully build a model using Keras Lambda layers. This model was saved and loaded for inference. Our feature engineering is part of our saved model(model architecture). <strong>Everything natively in Keras.</strong></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae0c6d3c904f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>