<?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 Gei Lin on Medium]]></title>
        <description><![CDATA[Stories by Gei Lin on Medium]]></description>
        <link>https://medium.com/@geilin?source=rss-7c9b19a2fc12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*QTMScDvfLW3MYdSGd3aCBg.jpeg</url>
            <title>Stories by Gei Lin on Medium</title>
            <link>https://medium.com/@geilin?source=rss-7c9b19a2fc12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:51:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@geilin/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[Ensembling Keras Models in R]]></title>
            <link>https://medium.com/@geilin/ensembling-keras-models-in-r-79076a7775a2?source=rss-7c9b19a2fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/79076a7775a2</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[ensembling]]></category>
            <dc:creator><![CDATA[Gei Lin]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 22:08:20 GMT</pubDate>
            <atom:updated>2018-11-03T20:06:38.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-9xrTov6TGY8o6II" /><figcaption>“orchestra playing their piece” by <a href="https://unsplash.com/@gwundrig?utm_source=medium&amp;utm_medium=referral">Manuel Nägeli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What About R?</h3><p>There are lots of examples and tutorials for <em>keras</em> in python, but there’s a good number of data scientists are working in R. One area lacking easy code samples is taking multiple keras models and producing an ensemble of them in R.</p><p>This post is based on <a href="https://medium.com/randomai/ensemble-and-store-models-in-keras-2-x-b881a6d7693f">Ensemble and Store Models in Keras 2.x</a>. for python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*Tm-w8UBlB32E-jQc2FHK-Q.png" /></figure><p>Assuming we have a set of saved models that use the <strong>same</strong> inputs, to ensemble them we need to complete the following steps.</p><ol><li><em>create a shared input layer</em></li><li><em>make our models to use the shared input and store the models in a list</em></li><li><em>create an average layer of the outputs of the model list in step 2</em></li><li><em>build a new keras model using the shared input and the output layer from step 3</em></li></ol><h3>Simple 2 Model Toy Ensemble</h3><pre>library(keras)</pre><pre>model_a &lt;- load_model_hdf5(filepath = &#39;a.h5&#39;)<br>model_b &lt;- load_model_hdf5(filepath = &#39;b.h5&#39;)</pre><pre>shared_input &lt;- layer_input(shape=(get_input_shape_at(model_a, 1) %&gt;% unlist))<br>model_list   &lt;- c(model_a(shared_input), model_b(shared_input))<br>main_output  &lt;- layer_average(model_list)</pre><pre>model &lt;- keras_model(<br>  inputs = c(shared_input), <br>  outputs = c(main_output)<br>)</pre><h3>Did We Do It?</h3><p>To verify that we produced our simple ensemble model correctly, we can compare our ensemble predictions against the average of the predictions among models <em>a</em> and <em>b</em>.</p><pre>pred_a &lt;- model_a %&gt;% predict(test_data)<br>pred_b &lt;- model_b %&gt;% predict(test_data)<br>pred_avg &lt;- model %&gt;% predict(test_data)<br>cbind(pred_a, pred_b, pred_avg, rowMeans(cbind(pred_a, pred_b)))</pre><h3>Reasons for Bagging</h3><blockquote><strong>Bootstrap aggregating</strong>, also called <strong>bagging</strong>, is a <a href="https://en.wikipedia.org/wiki/Ensemble_learning">machine learning ensemble</a> <a href="https://en.wikipedia.org/wiki/Meta-algorithm">meta-algorithm</a> designed to improve the stability and accuracy of <a href="https://en.wikipedia.org/wiki/Machine_learning">machine learning</a> algorithms used in <a href="https://en.wikipedia.org/wiki/Statistical_classification">statistical classification</a> and <a href="https://en.wikipedia.org/wiki/Regression_analysis">regression</a>. It also reduces <a href="https://en.wikipedia.org/wiki/Variance">variance</a> and helps to avoid <a href="https://en.wikipedia.org/wiki/Overfitting">overfitting</a>.</blockquote><p>You may find yourself training keras models of the same network in parallel with the goal of ensembling them together to create an average — removing the random variance among fits (each network has randomized initial weights before training which influence the results).</p><h3>R Functions for Bagging</h3><p>For convenience, you can use the code sample below to gather your sibling networks passed as JSON together into one bagged ensemble average.</p><pre>#&#39; <a href="http://twitter.com/importFrom">@importFrom</a> keras model_from_json set_weights layer_input layer_average keras_model<br>#&#39; <a href="http://twitter.com/importFrom">@importFrom</a> purrr map2<br>#&#39; <a href="http://twitter.com/export">@export</a><br>bag_keras_models_from_json &lt;- function(model_json_list, weights_json_list) { <br> # this does not k_clear -- you must load models in the same session to bind them together<br> # tensors must be from the same graph<br> instantiate_model &lt;- function(model_json, weights_json) {<br>    model &lt;- model_from_json(model_json)<br>    weights &lt;- weights_from_json(weights_json)<br>    set_weights(model, weights)<br>    model<br> }</pre><pre>force_sharing &lt;-function(model_list, input_layer) {<br>  n &lt;- length(model_list)<br>  lapply(1:n, function(x) model_list[[x]](shared_input)) <br> }</pre><pre>model_list   &lt;- map2(.x = model_json_list, .y = model_weights_list, ~instantiate_model(.x, .y))<br> shared_input  &lt;- layer_input(shape=(get_input_shape_at(model_list[[1]], 1) %&gt;% unlist))<br> community   &lt;- force_sharing(model_list, shared_input)</pre><pre>main_output  &lt;- layer_average(community)</pre><pre>model &lt;- keras_model(<br>   inputs = c(shared_input), <br>   outputs = c(main_output)<br> )</pre><pre>model<br>}</pre><pre># transform a list of json weights so it is readable by keras<br>#&#39; <a href="http://twitter.com/importFrom">@importFrom</a> jsonlite fromJSON<br>#&#39; <a href="http://twitter.com/export">@export</a><br>weights_from_json &lt;- function(weights_json) { <br>  fromJSON(weights_json) %&gt;% <br>   lapply(FUN = function(x) if (!is.matrix(x)) {array(x)} else {x})<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79076a7775a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>