<?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 Drew Hodun on Medium]]></title>
        <description><![CDATA[Stories by Drew Hodun on Medium]]></description>
        <link>https://medium.com/@dhodun?source=rss-b6c4b255828e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yaFMGNotwzg1L6c6A_bvNA.jpeg</url>
            <title>Stories by Drew Hodun on Medium</title>
            <link>https://medium.com/@dhodun?source=rss-b6c4b255828e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:07:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhodun/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[How to extend a Keras Model]]></title>
            <link>https://medium.com/data-science/how-to-extend-a-keras-model-5effc083265c?source=rss-b6c4b255828e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5effc083265c</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Drew Hodun]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 17:22:15 GMT</pubDate>
            <atom:updated>2020-06-24T17:22:15.583Z</atom:updated>
            <content:encoded><![CDATA[<h4>Passing through instance keys and features when using a Keras model</h4><p>Generally, you only need your Keras model to return prediction values, but there are situations where you want your predictions to retain a portion of the input. A common example is forwarding unique ‘instance keys’ while performing batch predictions. In this blog and <a href="https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/blogs/batch_predictions/batch_predictions_keras.ipynb">corresponding notebook code</a>, I’ll demonstrate how to modify the signature of a trained Keras model to forward features to the output or pass through instance keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2QRpOIQZDoMmCdId" /><figcaption>Sorting through instance keys. Photo by <a href="https://unsplash.com/@contradirony?utm_source=medium&amp;utm_medium=referral">Samantha Lam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>How to forward instance keys to the output</h3><p>Sometimes you’ll have a unique instance key that is associated with each row and you want that key to be output along with the prediction so you know which row the prediction belongs to. You’ll need to add keys when executing distributed batch predictions with a service like <a href="http://l/">Cloud AI Platform batch prediction</a>. Also, if you’re performing continuous evaluation on your model and you’d like to log metadata about predictions for later analysis. <a href="https://medium.com/u/247b0630b5d6">Lak Lakshmanan</a> shows <a href="https://towardsdatascience.com/how-to-extend-a-canned-tensorflow-estimator-to-add-more-evaluation-metrics-and-to-pass-through-ddf66cd3047d">how to do this with TensorFlow estimators</a>, but what about Keras?</p><p>Let’s say you have a previously trained model that has been saved with tf.saved_model.save(). Running the following, you can inspect the serving signature of the model and see the expected inputs and outputs:</p><pre>tf.saved_model.save(model, MODEL_EXPORT_PATH)</pre><pre>!saved_model_cli show — tag_set serve — signature_def serving_default — dir {MODEL_EXPORT_PATH}</pre><pre>The given SavedModel SignatureDef contains the following input(s):<br>  inputs[&#39;image&#39;] tensor_info:<br>      dtype: DT_FLOAT<br>      shape: (-1, 28, 28)<br>      name: serving_default_image:0<br>The given SavedModel SignatureDef contains the following output(s):<br>  outputs[&#39;preds&#39;] tensor_info:<br>      dtype: DT_FLOAT<br>      shape: (-1, 10)<br>      name: StatefulPartitionedCall:0<br>Method name is: tensorflow/serving/predict</pre><p>To pass through a unique row key and a previously saved model, load your model, create an alternative serving function, and re-save as follows:</p><pre>loaded_model = tf.keras.models.load_model(MODEL_EXPORT_PATH)</pre><pre>@tf.function(input_signature=[tf.TensorSpec([None], dtype=tf.string),tf.TensorSpec([None, 28, 28], dtype=tf.float32)])<br>def keyed_prediction(key, image):<br>    pred = loaded_model(image, training=False)<br>    return {<br>        &#39;preds&#39;: pred,<br>        &#39;key&#39;: key<br>    }</pre><pre># Resave model, but specify new serving signature<br>KEYED_EXPORT_PATH = &#39;./keyed_model/&#39;</pre><pre>loaded_model.save(KEYED_EXPORT_PATH, signatures={&#39;serving_default&#39;: keyed_prediction})</pre><p>Now when we inspect the serving signature of the model, we will see that it has the key as both input and output:</p><pre>!saved_model_cli show --tag_set serve --signature_def serving_default --dir {KEYED_EXPORT_PATH}</pre><pre>The given SavedModel SignatureDef contains the following input(s):<br>  inputs[&#39;image&#39;] tensor_info:<br>      dtype: DT_FLOAT<br>      shape: (-1, 28, 28)<br>      name: serving_default_image:0<br>  inputs[&#39;key&#39;] tensor_info:<br>      dtype: DT_STRING<br>      shape: (-1)<br>      name: serving_default_key:0<br>The given SavedModel SignatureDef contains the following output(s):<br>  outputs[&#39;key&#39;] tensor_info:<br>      dtype: DT_STRING<br>      shape: (-1)<br>      name: StatefulPartitionedCall:0<br>  outputs[&#39;preds&#39;] tensor_info:<br>      dtype: DT_FLOAT<br>      shape: (-1, 10)<br>      name: StatefulPartitionedCall:1<br>Method name is: tensorflow/serving/predict</pre><p>Your model service will now expect both an image tensor and a key in any prediction call and will output preds and key in its response. An upside to this method is you don’t need access to the code that generated the model, just the serialized SavedModel.</p><h3>How to leverage multiple serving signatures</h3><p>Sometimes it’s handy to save the model with both serving signatures, either for compatibility reasons (i.e the default signature is unkeyed) or so that a single serving infrastructure can handle both keyed and unkeyed predictions and the user decides which to perform. You’ll need to pull the serving function off of the loaded model and indicate that as one of the serving signatures when saved out again:</p><pre>inference_function = loaded_model.signatures[&#39;serving_default&#39;]</pre><pre>loaded_model.save(DUAL_SIGNATURE_EXPORT_PATH, signatures={&#39;serving_default&#39;: keyed_prediction,<br>    &#39;unkeyed_signature&#39;: inference_function})</pre><h3>How to forward input features to the output</h3><p>You may also want to forward certain input features for model debugging purposes, or to compute evaluation metrics on specific slices of data, (e.g. compute RMSE of baby weight based on whether the baby is pre-term or full-term).</p><p>This example presumes you’re using multiple named Inputs, something you would do if you wanted to take advantage of TensorFlow feature columns as described <a href="https://towardsdatascience.com/how-to-build-a-wide-and-deep-model-using-keras-in-tensorflow-2-0-2f7a236b5a4b">here</a>. Your first option would be to train the model as usual and take advantage of the Keras Functional API to create a slightly different model signature while maintaining the same weights:</p><pre>tax_rate = Input(shape=(1,), dtype=tf.float32, name=&quot;tax_rate&quot;)<br>rooms = Input(shape=(1,), dtype=tf.float32, name=&quot;rooms&quot;)</pre><pre>x = tf.keras.layers.Concatenate()([tax_rate, rooms])<br>x = tf.keras.layers.Dense(64, activation=&#39;relu&#39;)(x)<br>price = tf.keras.layers.Dense(1, activation=None, name=&quot;price&quot;)(x)</pre><pre># Functional API model instead of Sequential<br>model = Model(inputs=[tax_rate, rooms], outputs=[price])</pre><pre># Compile, train, etc...<br>#<br>#<br>#</pre><pre>forward_model = Model(inputs=[tax_rate, rooms], outputs=[price, tax_rate])</pre><p>The other alternative, particularly useful if you don’t have the code that generated the model, is modify the serving signature as you did with the keyed prediction model:</p><pre>@tf.function(input_signature=[tf.TensorSpec([None, 1], dtype=tf.float32), tf.TensorSpec([None, 1], dtype=tf.float32)])<br>def feature_forward_prediction(tax_rate, rooms):<br>    pred = model([tax_rate, rooms], training=False)<br>    return {<br>        &#39;price&#39;: pred,<br>        &#39;tax_rate&#39;: tax_rate<br>    }</pre><pre>model.save(FORWARD_EXPORT_PATH, signatures={&#39;serving_default&#39;: feature_forward_prediction})</pre><p>Enjoy!</p><p><em>Thanks to </em><a href="https://medium.com/@lakshmanok"><em>Lak Lakshmanan</em></a><em> for helping me update his original Estimator post to Keras.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5effc083265c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-extend-a-keras-model-5effc083265c">How to extend a Keras Model</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>