<?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 Alexey Zinoviev on Medium]]></title>
        <description><![CDATA[Stories by Alexey Zinoviev on Medium]]></description>
        <link>https://medium.com/@zaleslaw?source=rss-74b87b849973------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*RZCWLMrdC-J_vTSFvUQXyA.jpeg</url>
            <title>Stories by Alexey Zinoviev on Medium</title>
            <link>https://medium.com/@zaleslaw?source=rss-74b87b849973------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:59:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zaleslaw/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[KotlinDL 0.4]]></title>
            <link>https://zaleslaw.medium.com/kotlindl-0-4-c7d79060ddc6?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7d79060ddc6</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlindl]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 13:23:28 GMT</pubDate>
            <atom:updated>2022-06-09T13:23:28.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>KotlinDL 0.4 Is Out With Pose Detection API, EfficientDet for Object Detection, and EfficientNet for Image Recognition</h3><p>Version 0.4 of our deep learning library, <a href="https://github.com/JetBrains/KotlinDL">KotlinDL</a>, is out!</p><p>KotlinDL 0.4 is now available on <a href="https://search.maven.org/artifact/org.jetbrains.kotlinx/kotlin-deeplearning-api">Maven Central</a> with a variety of new features — check out all of the <a href="https://github.com/JetBrains/KotlinDL/blob/release_0.4/CHANGELOG.md">changes</a> that are coming to the new release! We’re currently introducing new models in ModelHub (including the EfficientNet and EfficientDet model families), the experimental high-level Kotlin API for Pose Detection, new layers and preprocessors contributed by the community members, and many other changes.</p><p>In this post, we’ll walk you through the changes to the Kotlin Deep Learning library in the 0.4 release:</p><ol><li>Pose Detection</li><li>NoTop models in the ModelHub</li><li>New models: EfficientDet and EfficientNet</li><li>Multiple callbacks</li><li>Breaking changes in the Image Preprocessing DSL</li><li>4 new layers and 2 new activation functions</li><li>Learn more and share your feedback</li></ol><h3>Pose Detection</h3><p>Pose detection is using an ML model to detect the pose of a person from an image or a video by detecting the spatial locations of key body joints (keypoints).</p><p>We’re excited to launch the MoveNet family of pose detection modes with our new pose detection API in KotlinDL. MoveNet is a fast and accurate model that detects 17 keypoints on the body. The model is offered on <em>ONNXModelHub </em>with two variants, <em>MoveNetSinglePoseLighting </em>and <em>MoveNetSinglePoseThunder</em>. <em>MoveNetSinglePoseLighting </em>is intended for latency-critical applications, while <em>MoveNetSinglePoseThunder </em>is intended for applications that require high accuracy.</p><p>If you need to detect a few poses on a given image or video frame, try <em>MoveNetMultiPoseLighting</em>. This model is able to detect multiple people in the image frame at the same time, while still achieving real-time speed.</p><p>There are two ways to detect poses within the KotlinDL: parsing the model output manually or using our LightAPI for Pose Detection (the recommended way).</p><p>Just load the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b5c1cce2622967ea405452cbd463abe/href">https://medium.com/media/2b5c1cce2622967ea405452cbd463abe/href</a></iframe><p>Run the predictions and print out the pose landmarks and edges connecting the detected pose landmarks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29aee9a18b578b714e72e313da848806/href">https://medium.com/media/29aee9a18b578b714e72e313da848806/href</a></iframe><p>Some visualization examples, where we drew landmarks and edges on the given images, are below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*CF6uJI3v_Q0sWHwbYm5TgQ.png" /></figure><p>The complete example can be found <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/examples/src/main/kotlin/examples/onnx/posedetection/singlepose/PoseDetectionMoveNetLightAPI.kt">here</a>.</p><p>If you want to run the MoveNet model to detect multiple poses on the given image, you need to make some minor changes to your code.</p><p>First, load the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/658baf2435f31c0a4637b136c9acab7f/href">https://medium.com/media/658baf2435f31c0a4637b136c9acab7f/href</a></iframe><p>Secondly, run the model and get the <em>MultiPoseDetectionResult </em>object, which contains the list of pairs <em>&lt;DetectedObject, DetectedPose&gt;</em>. As a result, we have access not only to the landmarks’ coordinates and labels, but also to the coordinates of the bounding box for the whole person.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbee70d6dc3e8889aa9869a2d6c56f46/href">https://medium.com/media/bbee70d6dc3e8889aa9869a2d6c56f46/href</a></iframe><p>Some visualization examples, where we drew the bounding boxes, landmarks, and edges on the images are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*ExkIpw0Cv_wlxmZJLtfWdw.png" /></figure><p>The complete example can be found <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/examples/src/main/kotlin/examples/onnx/posedetection/multipose/multiPoseDetectionMoveNetLightAPI.kt">here</a>.</p><h3>NoTop models in the ModelHub</h3><p>Running predictions on ready-made models is good, but what about fine-tuning them for your tasks?</p><p>The classic approach to Transfer Learning is to freeze all layers except the last few and then train the top few layers (the fully connected layers at the top of the network) on a new piece of data, often changing the number of model outputs.</p><p>Before the 0.4 release, KotlinDL users needed to remove the last layers manually, but with the 0.4 release, TensorFlowModelHub provides an option to download “noTop” models — equivalent to earlier available models, but without weights and configurations for the last few layers.</p><p>The following “noTop” models are now available:</p><ul><li>VGG’16</li><li>VGG’19</li><li>ResNet50</li><li>ResNet101</li><li>ResNet152</li><li>ResNet50V2</li><li>ResNet101V2</li><li>ResNet152V2</li><li>MobileNet</li><li>MobileNetV2</li><li>NasNetMobile</li><li>NasNetLarge</li><li>DenseNet121</li><li>DenseNet169</li><li>DenseNet201</li><li>Xception</li><li>Inception</li></ul><p>In the example below, we load the ResNet50 model from our TensorFlowModelHub and fine-tune it to classify cats and dogs (using the embedded Dogs-vs-Cats dataset):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b872ae9239b559072b6ec596ff747be/href">https://medium.com/media/1b872ae9239b559072b6ec596ff747be/href</a></iframe><p>The <em>topModel</em> is the simplest neural network and can be trained quickly, as it has few parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cdee2e01326a805afe878c08c1ff658/href">https://medium.com/media/7cdee2e01326a805afe878c08c1ff658/href</a></iframe><p>The new helper function could join two models together: noTop and topModel: val model = Functional.of(pretrainedModel = noTopModel, topModel = topModel)</p><p>After that, load weights for the frozen layers from the noTop model, and the weights for the unfrozen layers from the topModel will be initialized during the fit method call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a7d45f11f0490b9d15c294c2ca62e7a/href">https://medium.com/media/0a7d45f11f0490b9d15c294c2ca62e7a/href</a></iframe><p>The complete example can be found <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/examples/src/main/kotlin/examples/transferlearning/modelhub/resnet/Example_6_ResNet50_prediction_additional_training_noTop_with_helper.kt">here</a>.</p><h3>New models: EfficientDet and EfficientNet</h3><p>Until v0.4, our ModelHub contained only one model (SSD) suitable for solving the Object Detection problem. Starting with this release, we’re gradually expanding the library’s capabilities for solving the Object Detection problem. We’d like to introduce to you a new family of object detectors, called <a href="https://arxiv.org/abs/1911.09070">EfficientDet</a>, which consistently achieve much better efficiency than prior object detectors across a wide spectrum of resource constraints.</p><p>All models from this family have the same internal architecture which scales for different inputs (image resolution). The final user has a choice of models: from the smallest EfficientDet-D0, model with 3.9 million parameters and 10.2 ms latency on the V100 up to the EfficientDet-D7, with 52 million parameters and 122 ms latency on the V100.</p><p>Internally, EfficientDet models use another famous model, EfficientNet, as a backbone. It extracts features from input images and passes them to the next component of the Object Detection model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PwzSL3C8xUPgrY84y59kg.png" /></figure><p>An example of EfficientDet-D2 usage can be found <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/examples/src/main/kotlin/examples/onnx/objectdetection/efficientdet/EfficientDetD2LightAPI.kt">here</a>.</p><p>The EfficientNet model family is also available in the ONNXModelHub. There are 8 different types of models and each model is presented in two variants: full and “noTop” for fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ubr29W0gc04rgGiv3v_4BQ.png" /></figure><p>These models achieve better accuracy on the ImageNet dataset with 10x fewer parameters than ResNet or NasNet. If you need fast and accurate image recognition, EfficientNet is a good choice.</p><p>An example of EfficientNet0 usage can be found <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/examples/src/main/kotlin/examples/onnx/cv/efficicentnet/lightAPI/EfficientNetB0LightAPI.kt">here</a>.</p><h3>Multiple callbacks</h3><p>Earlier, Callback support for KotlinDL was pretty simple and not fully compatible with Keras. As a result, users faced difficulties in implementing their neural networks, building the custom validation process, and monitoring the neural network’s training.</p><p>The callback object was passed during compilation and was unique for each stage in the model’s lifecycle. However, model compilation can be located in very different places in the code than fit/predict/evaluate, meaning that users may need to create different callbacks for different purposes.</p><p>Let’s assume that we need to define EarlyStopping and TerminateOnNaN for training to handle exceptional cases, and also add two custom callbacks for the prediction and evaluation phases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25fd405d4b2a488e28e9d5a01ca7e7e2/href">https://medium.com/media/25fd405d4b2a488e28e9d5a01ca7e7e2/href</a></iframe><p>Let’s pass these callbacks to the model methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcd298d389e55ed2a954ae1796b46bb5/href">https://medium.com/media/dcd298d389e55ed2a954ae1796b46bb5/href</a></iframe><p>Found below in the logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDReIH8Oxbwea_e1XUYUyw.png" /></figure><p>The complete example can be found <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/examples/src/main/kotlin/examples/cnn/mnist/advanced/LeNetWithMultipleCallbacks.kt">here</a>.</p><h3>4 new layers and 2 new activation functions</h3><p>Many contributors to this release have added layers to Kotlin for performing non-trivial logic. With these added layers, you can start working with autoencoders and load the GAN models:</p><ul><li>Dot layer (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>Conv1DTranspose, Conv2DTranspose, and Conv3DTranspose layers (by <a href="https://github.com/juliabeliaeva">Julia Beliaeva</a>)</li></ul><p>There are also two new activation functions:</p><ul><li>Sparsemax activation function (by <a href="https://github.com/cagriyildirimR">Cagri Yildirim</a>)</li><li>Soft shrink activation function (by <a href="https://github.com/michalharakal">Michal Harakal</a>)</li></ul><p>These activation functions are not available in the TensorFlow core package, but we decided to add them after seeing how they’ve been widely used in recent papers.</p><p>We’d be delighted to look at your pull requests if you’d like to contribute a layer, activation function, callback, or initializer from a recent paper!</p><h3>Breaking changes in the Image Preprocessing DSL</h3><p>There are a few major changes in the Image Preprocessing DSL:</p><ul><li>CustomPreprocessor was removed.</li><li>The loading section was moved from image preprocessing to the Dataset API</li></ul><p>A few new Preprocessors were added:</p><ul><li>Padding</li><li>CenterCrop</li><li>Convert</li><li>Grayscale</li><li>Normalizing</li></ul><p>Here is an example of some of the new operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82c058f32b96dfd7a563a0edf1bfe725/href">https://medium.com/media/82c058f32b96dfd7a563a0edf1bfe725/href</a></iframe><p>Because of the removal of the loading section, the same preprocessing instance could now be used in several datasets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba80a58d3479a4042566ac96e8e60653/href">https://medium.com/media/ba80a58d3479a4042566ac96e8e60653/href</a></iframe><h3>Learn more and share your feedback</h3><p>We hope you enjoyed this brief overview of the new features in KotlinDL 0.4! For more information, including the up-to-date <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/README.md">Readme file</a>, visit the project’s home on <a href="https://github.com/Kotlin/kotlindl">GitHub</a>. Be sure to check out the KotlinDL <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/docs/quick_start_guide.md">guide</a>, which contains detailed information about the library’s basic and advanced features and covers many of the topics mentioned in this blog post in more detail.</p><p>If you’ve previously used KotlinDL, use the <a href="https://github.com/Kotlin/kotlindl/blob/release_0.4/CHANGELOG.md">changelog</a> to find out what has changed and how to upgrade your projects to the stable release.</p><p>We’d be very thankful if you’d report any bugs you find to our issue tracker. We’ll try to fix all of the critical issues in the 0.4.1 release.</p><p>You’re also welcome to join the <a href="https://app.slack.com/client/T09229ZC6/C01DZU7PW73">#kotlindl channel</a> in Kotlin Slack (get an invite <a href="http://slack.kotlinlang.org/?_ga=2.28360636.1631899419.1619088615-984759609.1618823233">here</a>). In this channel, you can ask questions, participate in discussions, and get notifications about the new preview releases and models in ModelHub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7d79060ddc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection with KotlinDL and Ktor]]></title>
            <link>https://zaleslaw.medium.com/object-detection-with-kotlindl-and-ktor-eb49d4a8027c?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb49d4a8027c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 10:01:18 GMT</pubDate>
            <atom:updated>2022-01-27T11:07:07.606Z</atom:updated>
            <content:encoded><![CDATA[<h4>Intro</h4><p>I presented the <a href="https://www.youtube.com/watch?v=wXpEKouOV3E&amp;t=1349s">webinar</a> “Object Detection and Image Recognition with Kotlin” where I explored a deep learning library written in Kotlin, described how to detect objects of different types in images, and explained how to create a Kotlin Web Application using Ktor and KotlinDL that recognizes cars and persons on photos. I have decided there is more that I would like to share with you on the subject, and so here is an extended article.</p><p>If you are new to Deep Learning, don’t worry about it. You don’t need any high-level calculus knowledge to start using the Object Detection Light API in the KotlinDL library.</p><p>However, when writing this article, I did assume you would be familiar with basic Kotlin web-development fundamentals, e.g., HTML, web-server, HTTP, and client-server communications.</p><p>This article will take you through how to detect objects in different images and create a Kotlin Web Application using Ktor and KotlinDL.</p><h3>What is Object Detection?</h3><p>It’s a pretty simple term from the Deep Learning world and just means the task of detecting instances of objects of a certain class within an image.</p><p>You are probably already familiar with Image Recognition, where the idea is to recognize the class or type of only one object within an image, without having any coordinates for the recognized object.</p><p>Unlike the Image Recognition, during Object Detection, we are trying to detect a few objects (sometimes it could be a significant number, 100 or even 1,000, for example), and their locations, which are usually presented as four coordinates of a rectangle (x_min, x_max, y_min, y_max) containing the detected object.</p><p>For example, this screenshot of the example application shows how a few objects have been recognized, and their positions annotated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*ducGP0RfzPHZPMwP5ndCag.png" /></figure><p>OK — now for the fun stuff! It’s time to write some Kotlin code to detect objects within an image.</p><h3>Object Detection Example</h3><p>Let’s say we have the following image. We see a typical street: several cars, pedestrians crossing, traffic lights, and even someone using the pedestrian crossing on a bicycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXelsWXxDQm6oSuCnFZjLg.png" /></figure><p>With a few rows of code, we can obtain a list of the detected objects, sorted by score or probability (the degree of confidence of the model that a certain rectangle contains an object of a certain type).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e402e964c99b4a895ded8b58acbafbd/href">https://medium.com/media/5e402e964c99b4a895ded8b58acbafbd/href</a></iframe><p>This code prints the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a56b3770acdc37853ccde8c02b31d384/href">https://medium.com/media/a56b3770acdc37853ccde8c02b31d384/href</a></iframe><p>OK, it looks like the model can detect objects, just like our eyes can do, but how do we go about marking the objects?</p><p>We can use the Swing framework to draw rectangles over the image. This also requires simple image preprocessing before visualization.</p><p>First, we need to add a simple visualization using JPanel, BufferedImage, and Graphics2D objects in the <strong><em>visualise </em></strong>function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3573c1db3372d71bbb0711009e478a3a/href">https://medium.com/media/3573c1db3372d71bbb0711009e478a3a/href</a></iframe><p>Drawing rectangles on an image with the Graphics2D API may not be the best approach, but we can use it as a good starting point for our research.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae09fed46f783868383ac3497da407e/href">https://medium.com/media/cae09fed46f783868383ac3497da407e/href</a></iframe><p>The result is the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipZxmiV3L19QfaHieL4gHA.png" /></figure><p>As you can see, the Object Detection Light API returns not only the class label and score but the relative image coordinates, which can be used for drawing rectangles or boxes around the detected objects.</p><p>Also, we could play a little bit with the paint palette and use different colors to differentiate people, bicycles, cars, and traffic lights:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d7aa3d7f22cfa1900e8ca8023530c28/href">https://medium.com/media/5d7aa3d7f22cfa1900e8ca8023530c28/href</a></iframe><p>That looks significantly better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5P7i4crhuZ1bGdHqnOlaw.jpeg" /></figure><p>You can continue experimenting with the visualization, but we need to move on!</p><h3>Client-Server Application with Ktor</h3><p>In this section, I will use Ktor to write two simple programs: client and server. The client application will send the image to the server application. If you have never used Ktor before, it’s an excellent time to see how easy it is to deal with classic web stuff like HTTP requests, headers, MIME types, and so on.</p><p>When the code below is run, the client application sends a POST request via the <strong><em>submitFormWithBinaryData </em></strong>method. You can read more about how this works in <a href="https://ktor.io/docs/request.html#upload_file">Ktor documentation</a>. The result with the added boxes for the detected objects can be found in the <strong><em>clientFiles </em></strong>folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc21371ca1c06c15ee2102d1233f3a3f/href">https://medium.com/media/fc21371ca1c06c15ee2102d1233f3a3f/href</a></iframe><p>Unfortunately, Ktor has no special API for receiving files from the server side. But we’re programmers, right? Let’s just write the bytes obtained over the network to the File object.</p><p>The server part is a little more difficult. I’ll need to explain some parts of the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1fbb4ba161ccd9d0b649dc1a8bc313f/href">https://medium.com/media/e1fbb4ba161ccd9d0b649dc1a8bc313f/href</a></iframe><p>Because model creation is a time-consuming step (due to loading and initializing), we need to create the model before we can run the server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db1a8445ea140e1c4a97cb627f3f94d8/href">https://medium.com/media/db1a8445ea140e1c4a97cb627f3f94d8/href</a></iframe><p>The intermediate result will be saved to the <strong><em>serverFiles </em></strong>folder. After that, the server application will send this file back to the client.</p><p>To send form data in a test POST/PUT request, you must set the Content-Type header and specify the request body. To do this, you can use the <strong><em>addHeader </em></strong>and <strong><em>setBody </em></strong>functions, respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6bacf881c5b92014f96885be54392b7/href">https://medium.com/media/b6bacf881c5b92014f96885be54392b7/href</a></iframe><p>At the end, we need to close our model to release all the resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb0c841604be49b87e34216099d75603/href">https://medium.com/media/eb0c841604be49b87e34216099d75603/href</a></iframe><p>Run the server, and after that, try to make multiple runs of the client with the different images. Check <strong><em>clientFiles </em></strong>and <strong><em>serverFiles </em></strong>folders to find all the images that were sent with detected objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ylzsQL7yeeB6O84XusPxcw.jpeg" /><figcaption>Yet another image with detected objects</figcaption></figure><p>The complete example, including drawing and saving files to the <strong><em>serverFiles </em></strong>folder, can be found <a href="https://github.com/zaleslaw/Ktor-KotlinDL-Object-Detection-examples/tree/master/src/main/kotlin/demo/ktor/example_2">here</a> in the GitHub repository.</p><h3>Web Application</h3><p>It’s time to write the whole Web Application with an HTML page rendered on the server, a few inputs, and a button. I’d like to upload an image, fill some input fields with the parameters, and press a button to download the image with the detected objects on my laptop.</p><p>The application will contain only the server part, but it has a few interesting aspects we will need to consider. It should handle two HTTP requests: the POST request, which handles multipart data with FileItem and FormItem handlers, and the GET request, which returns a simple HTML page.</p><p>From <strong><em>multipartData </em></strong>we can not only extract binary data like in the previous example but the values of the form parameters, too. These parameters, <strong><em>topK</em></strong><em>,</em> and <strong><em>classLabelNames</em> </strong>will be explained later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c44caa7553dbdcbccbaf768e75c892a/href">https://medium.com/media/5c44caa7553dbdcbccbaf768e75c892a/href</a></iframe><p>To describe the HTML page with this nice DSL, Ktor uses <a href="https://github.com/Kotlin/kotlinx.html">kotlinx.html</a> as written in the <a href="https://ktor.io/docs/html-dsl.html">documentation</a>. This integration allows you to respond to a client with HTML blocks. With HTML DSL, you can write pure HTML in Kotlin, interpolate variables into views, and build complex HTML layouts using templates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2876f4ca063170843a4b71a159b8e5c/href">https://medium.com/media/c2876f4ca063170843a4b71a159b8e5c/href</a></iframe><p>Run the server and open the page <a href="http://localhost:8002/">http://localhost:8002</a>. Here you’ll find a form. Simply upload the image, fill inputs with the request parameters (or leave them empty), and press the button “Detect objects.” The new image will start downloading in a few seconds.</p><p>You also could play with the parameters <strong><em>topK</em></strong><em>,</em> and <strong><em>classLabelNames </em></strong>to obtain different results. The <strong><em>topK </em></strong>parameter is used to determine how many detected objects (sorted by a score from highest to lowest) will be drawn on the image. The classLabelNames parameter takes as an input a list of labels (from the following <a href="https://github.com/JetBrains/KotlinDL/blob/master/api/src/main/resources/datasets.cocoa/coco.names.txt">list</a>) separated by commas to filter categories of detected objects in the picture that will be enclosed in a rectangle.</p><p>The complete example can be found <a href="https://github.com/zaleslaw/Ktor-KotlinDL-Object-Detection-examples/tree/master/src/main/kotlin/demo/ktor/example_3">here</a> in the GitHub repository.</p><p>This represents only a small fraction of what you can do with the full power of Ktor. For example, you can also build a REST API for Object Detection, Image Recognition, or build a helpful microservice. It is your choice!</p><h3>In conclusion</h3><p>Release 0.3 was shipped with only one effective object detection model: SSD. The new release, 0.4, brings seven new object detection models with different characteristics of velocity and accuracy as well as the ability to detect complex objects.</p><p>We strongly recommend using Compose for Desktop, instead of Swing, for your visualization needs. The community is working on moving <a href="https://github.com/zaleslaw/Ktor-KotlinDL-Object-Detection-examples/pull/3">these examples to the new framework</a>.</p><p>This is not the only improvement you can expect in the Object Detection Light API. In future releases, we will add some helpful methods for filtering and unioning different boxes in the YOLO style to avoid having places in the image where a single object has multiple rectangles drawn on it.</p><p>If you have any thoughts or user experience related to this use case, just make an issue on <a href="https://github.com/JetBrains/KotlinDL/issues">GitHub</a> or ask in the Kotlin Slack (<a href="https://app.slack.com/client/T09229ZC6/C01DZU7PW73">kotlindl channel</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb49d4a8027c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sure, I've experimented with a few PyTorch models, loading them via ONNX.]]></title>
            <link>https://zaleslaw.medium.com/sure-ive-experimented-with-a-few-pytorch-models-loading-them-via-onnx-3974cc6e5ef3?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/3974cc6e5ef3</guid>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 09:25:46 GMT</pubDate>
            <atom:updated>2022-01-27T09:25:46.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Sure, I&#39;ve experimented with a few PyTorch models, loading them via ONNX. In the new 0.4 release will be availalbe a few models converted this way. Please feel free to share any details of your experiment in issues here https://github.com/JetBrains/KotlinDL/issues</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3974cc6e5ef3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KotlinDL 0.3]]></title>
            <link>https://zaleslaw.medium.com/kotlindl-0-3-43fffd3cb94?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/43fffd3cb94</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[onnx-runtime]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 15:03:28 GMT</pubDate>
            <atom:updated>2021-09-29T11:20:39.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>KotlinDL 0.3 Is Out With ONNX Integration, Object Detection API, 20+ New Models in ModelHub, and Many New Layers</h3><p>Introducing version 0.3 of our deep learning library, <a href="https://github.com/JetBrains/KotlinDL">KotlinDL</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ufLD9WIGLTM-ZDVhE5otjw.gif" /></figure><p>KotlinDL 0.3 is available now on <a href="https://search.maven.org/artifact/org.jetbrains.kotlinx/kotlin-deeplearning-api">Maven Central</a> with a variety of new features — check out all the <a href="https://github.com/JetBrains/KotlinDL/blob/master/CHANGELOG.md">changes</a> that are coming to the new release! We’re currently introducing a lot of new models in ModelHub (including the first Object Detection and Face Alignment models), the ability to fine-tune the Image Recognition models saved in ONNX format from Keras and PyTorch, the experimental high-level Kotlin API for image recognition, a lot of new layers contributed by the community members and many other changes.</p><p>In this post, we’ll walk you through the changes to the Kotlin Deep Learning library in the 0.3 release:</p><ol><li>ONNX integration</li><li>Fine-tuning of ONNX models</li><li>ModelHub: support for the DenseNet, Inception, and NasNet model families</li><li>Object detection with the SSD model</li><li>Sound classification with the SoundNet architecture</li><li>Experimental high-level API for Image Recognition</li><li>23 new layers, 6 new activation functions, and 2 new initializers</li><li>How to add KotlinDL to your project</li><li>Learn more and share your feedback</li></ol><h3>ONNX integration</h3><p>Over the past year, library users have been asking us to add support for working with models saved in the ONNX format.</p><p>Open Neural Network Exchange (ONNX) is an open-source format for AI models. It defines an extensible computation graph model and definitions of built-in operators and standard data types. It works well with both of today’s most popular frameworks, TensorFlow and PyTorch.</p><p>We use the <a href="https://github.com/microsoft/onnxruntime/tree/master/java">ONNX Runtime Java API</a> to parse and execute models saved in the `.onnx` file format. You could read more about this API in the <a href="https://onnxruntime.ai/docs/api/java/index.html">documentation</a> of the project.</p><p>KotlinDL has a separate `onnx` module that provides the ONNX integration support. To use it in your project, you should add a different <a href="https://search.maven.org/artifact/org.jetbrains.kotlinx/kotlin-deeplearning-onnx/0.3.0-alpha-3/jar">dependency</a>.</p><p>There are two ways to run predictions on the ONNX model. If you want to use LeNet-5, one of our models from ModelHub, you can load it in the following manner:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/689fcf21f10149fb2e19b63064366c58/href">https://medium.com/media/689fcf21f10149fb2e19b63064366c58/href</a></iframe><p>To load a model that is in the ONNX format, instantiate OnnxInferenceModel and run the predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a84a248ec2990cfe6c580046f8f6fe/href">https://medium.com/media/a4a84a248ec2990cfe6c580046f8f6fe/href</a></iframe><p>If the model has a very complex output, for example, a few tensors like YOLOv4 or SSD (which can be loaded from ModelHub, too), you may want to call a <em>predictRaw </em>method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160526dbf52e2c00caef691f398c2799/href">https://medium.com/media/160526dbf52e2c00caef691f398c2799/href</a></iframe><p>to get access to all the output and parse the output manually.</p><p>Finding an appropriate model in <em>ONNXModelHub </em>is easy: just start your search from the top-level object <em>ONNXModels </em>and go deeper to <em>CV </em>or <em>ObjectDetection</em>. Use this chain of inner objects like a unique model identifier to obtain the model itself or its preprocessing method. For example, the SOTA model from 2020 for the Image Recognition task, called EfficientNet, can be found by following <em>ONNXModels.CV.EfficientNet4Lite</em>.</p><h3>Fine-tuning of ONNX models</h3><p>Of course, running predictions on ready-made models is good, but what about fine-tuning them a little for our tasks?</p><p>Unfortunately, the ONNX Java API does not support training mode for models, but we do not need to train the entire model as a whole to perform Transfer Learning tasks.</p><p>The classical approach to the Transfer Learning task is to freeze all layers, except for the last few, and then train the top few layers (the fully connected layers at the top of the network) on a new piece of data, often changing the number of model outputs.</p><p>These top layers can be viewed as a small neural network whose input is the output of a model consisting of frozen layers. These frozen layers can be considered as preprocessing of a small top model.</p><p>We have implemented this approach in our library, which has an ONNX model as a preprocessing stage and a top model as a small KotlinDL neural network.</p><p>Suppose you have a huge model in Keras or PyTorch that you want to fine-tune in KotlinDL: cut off the last layers from it, export to the ONNX format, load into KotlinDL as an additional preprocessing layer via <em>ONNXModelPreprocessor</em>, describe the missing layers using the KotlinDL API, and train it.</p><figure><img alt="Figure 1. ONNX model’s fine-tuning." src="https://cdn-images-1.medium.com/max/402/1*_8xNElgJVpHh2Ig6hgEbeQ.png" /><figcaption>Figure 1. ONNX model’s fine-tuning.</figcaption></figure><p>In the example below, we load the ResNet50 model from our <em>ONNXModelHub </em>and fine-tune it to classify cats and dogs (the embedded Dogs-vs-Cats dataset is used):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/070df772b0cbb20245126d676bca5215/href">https://medium.com/media/070df772b0cbb20245126d676bca5215/href</a></iframe><p>The <em>topModel</em> is just the simplest neural network and can be trained quickly as it has few parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07db10a82953db5f8f402c02dade2f5e/href">https://medium.com/media/07db10a82953db5f8f402c02dade2f5e/href</a></iframe><p>The complete example can be found <a href="https://github.com/JetBrains/KotlinDL/blob/master/examples/src/main/kotlin/examples/onnx/cv/custom/additionalTrainingWithTensorFlow.kt">here</a>.</p><blockquote>Since there is no API for cutting layers and weights from the model saved in the ONNX format, you need to perform these operations yourself before exporting to the ONNX format. We’re going to add to ModelHub a lot of models from PyTorch and Keras prepared this way in the 0.4 release.</blockquote><h3>ModelHub: support for the DenseNet, Inception, and NasNet model families</h3><p>In the 0.2 release, KotlinDL added storage of models, which could be loaded from JetBrains S3 storage and cached on disk. We first called it ModelZoo and have since renamed it to ModelHub.</p><p>ModelHub contains a collection of Deep Learning models that are pre-trained on large datasets like <a href="https://www.image-net.org/">ImageNet</a> or <a href="https://cocodataset.org/#home">COCO</a>.</p><p>There are two ModelHubs currently: the basic <em>TFModelHub</em>, available in the `<em>api</em>` module, and an additional ONNXModelHub, available in the `<em>onnx</em>` module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*DL2uGsHq5FHUBdsLy8adjg.png" /><figcaption>Figure 2. ModelHub class hierarchy.</figcaption></figure><p><em>TFModelHub </em>currently supports the following models:</p><ul><li>VGG’16</li><li>VGG’19</li><li>ResNet18</li><li>ResNet34</li><li>ResNet50</li><li>ResNet101</li><li>ResNet152</li><li>ResNet50v2</li><li>ResNet101v2</li><li>ResNet152v2</li><li>MobileNet</li><li>MobileNetv2</li><li>Inception</li><li>Xception</li><li>DenseNet121</li><li>DenseNet169</li><li>DenseNet201</li><li>NASNetMobile</li><li>NASNetLarge</li></ul><p><em>ONNXModelHub </em>currently supports the following models:</p><p><strong>CV</strong></p><ul><li>Lenet</li><li>ResNet18</li><li>ResNet34</li><li>ResNet50</li><li>ResNet101</li><li>ResNet152</li><li>ResNet50v2</li><li>ResNet101v2</li><li>ResNet152v2</li><li>EfficientNet4Lite</li></ul><p><strong>ObjectDetection</strong></p><ul><li>SSD</li></ul><p><strong>FaceAlignment</strong></p><ul><li>Fan2d106</li></ul><p>All models in <em>TFModelHub </em>include a special loader of model configs and model weights, as well as the special data preprocessing function that was applied when the models were trained on the <a href="http://www.image-net.org/">ImageNet dataset</a>.</p><p>Here’s an example of how you can use one of these models, ResNet50, for prediction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5771c7f25c78cc3fc81a3eadeb9ca7/href">https://medium.com/media/3d5771c7f25c78cc3fc81a3eadeb9ca7/href</a></iframe><p>Now you’ve got a model and weights, and you can use them in KotlinDL.</p><blockquote>Don’t forget to apply model-specific preprocessing for the new data. All the preprocessing functions are included in ModelHub and can be called via the <strong>preprocessInput </strong>function:</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90dbf625f16c7b02483997c18094ad9e/href">https://medium.com/media/90dbf625f16c7b02483997c18094ad9e/href</a></iframe><p>A complete example of how to use ResNet’50 for prediction and transfer learning with additional training on a custom dataset can be found in <a href="https://github.com/JetBrains/KotlinDL/blob/master/docs/transfer_learning_functional.md">this tutorial</a>.</p><blockquote>When working with ONNX models, you do not have to load the weights separately (see the ONNX integration section above).</blockquote><h3>Object detection with the SSD model</h3><p>Until v0.3, our ModelHub contained models suitable for solving the Image Recognition problem. But starting with this release, we are gradually expanding the library’s capabilities for working with images. We’d like to introduce to you the <a href="https://arxiv.org/pdf/1512.02325.pdf">Single Shot MultiBox Detector (SSD)</a> model, which is capable of solving the Object Detection problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*NPrhvaJoNZXgdIxi" /><figcaption>Figure 3. The architecture of a convolutional neural network with an SSD detector (<a href="https://developers.arcgis.com/python/guide/how-ssd-works/">from</a>)</figcaption></figure><p>Object detection is the task of detecting instances of objects of a certain class within an image.</p><p>The SSD model is trained on the <a href="https://paperswithcode.com/dataset/coco">COCO dataset</a>, which consists of 328,000 images, each with bounding boxes and per-instance segmentation masks in 80 object categories. The model can be used in real-time prediction to detect objects.</p><p>We designed an API for Object Detection, which hides the details of image post- and preprocessing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66f09ca8dd33056c6d85e449d86010cd/href">https://medium.com/media/66f09ca8dd33056c6d85e449d86010cd/href</a></iframe><p>The result of the object detection is drawn on a Swing Panel; the image is preprocessed for SSD input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CAYyoy9tWtXsG325FR9TQQ.gif" /><figcaption>Figure 4. Car detector via ObjectDetection API.</figcaption></figure><p>The famous YOLOv4 model is also available in ONNXModelHub. However, we haven’t added the <a href="https://github.com/onnx/models/tree/master/vision/object_detection_segmentation/yolov4#postprocessing-steps">postprocessing of YOLOv4 output</a> because some operations are missing in the <a href="https://github.com/Kotlin/multik">Multik</a> library (the Kotlin analog of NumPy). We’re looking for contributions from the community, so please don’t hesitate to join the effort!</p><blockquote>Of course, you can load the standard API to load the model and call the <strong>predictRaw </strong>method to handle the result manually, but we suggest avoiding these difficulties.</blockquote><h3>Experimental high-level API for Image Recognition</h3><p>For the Object Detection task, we offered a simplified API for predictions. Likewise, for the Image Recognition task, we can simplify the interaction with models loaded from ModelHub by hiding the image preprocessing, compilation, and model initialization from the user.</p><p>To illustrate how this works, let’s load and store on disk a pre-trained model of the particular type <em>ImageRecognitionModel</em>. Models of this type are not capable of additional training — they can only make predictions. On the other hand, they are extremely easy to work with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ce5ff59c9c2286b9476d5592a278bfa/href">https://medium.com/media/7ce5ff59c9c2286b9476d5592a278bfa/href</a></iframe><p>The syntax for working with pre-trained models uses brackets, which is nice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3633214fdbdc509d6958a67ab66bcef5/href">https://medium.com/media/3633214fdbdc509d6958a67ab66bcef5/href</a></iframe><p><em>ImageRecognitionModel </em>has methods that immediately return human-readable labels and accept image files as input.</p><p>This is an experimental API for hardcore backend engineers, for whom the model is a black box with entry and exit. We’d love to hear about your experience with this API and your thoughts about this approach.</p><h3>Sound classification with the SoundNet architecture</h3><p>The KotlinDL library is taking its first steps in the audio domain. This release adds a few layers required for building a SoundNet-like model, such as Conv1D, MaxPooling1D, Cropping1D, UpSampling1D, and other layers with the “1D” suffix.</p><p>Let’s build a toy neural network inspired by the SoundNet model’s architecture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc88e70f053279120cbcc8c2d2ac8234/href">https://medium.com/media/fc88e70f053279120cbcc8c2d2ac8234/href</a></iframe><p>This is a CNN that uses only 1D parts for convolutions and max-pooling of the input sound data. This network was able to achieve approximately 55% accuracy on test data from FSDD after ten epochs and approximately 85% after 100 epochs.</p><p>SoundBlock is a pretty simple composition of the two Conv1D and one MaxPool1D layer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c7e4de7904926e829916b76b2a0752e/href">https://medium.com/media/5c7e4de7904926e829916b76b2a0752e/href</a></iframe><p>When the model is ready, we can load the <a href="https://github.com/Jakobovski/free-spoken-digit-dataset">Free Spoken Digits Dataset</a> (FSDD) and train the model. The FSDD dataset is a simple audio/speech dataset consisting of recordings of spoken digits in <em>.wav</em> files at 8 kHz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*RpbXn2U53UmfVb3l" /><figcaption>Figure 5. WavFile visualization (randomly sampled from FSDD).</figcaption></figure><p>The trained model will recognize the digit from the sound recorded as a .wav file correctly. Feel free to train your pronunciation with our toy SoundNet model!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edbaaea75a10369d3e2eac920b009e92/href">https://medium.com/media/edbaaea75a10369d3e2eac920b009e92/href</a></iframe><p>The complete code of the example can be found <a href="https://github.com/JetBrains/KotlinDL/blob/release_0.3/examples/src/main/kotlin/examples/cnn/fsdd/SoundNet.kt">here</a>.</p><h3>23 new layers, 6 new activation functions, and 2 new initializers</h3><p>Many of the contributors to this release have added layers to KotlinDL for performing non-trivial logic. With these added layers, you can start working with neural networks that process not only photos but also sound, video, and 3D images:</p><ul><li>Softmax activation layer (by <a href="https://github.com/d-lowl">D. Lowl</a>)</li><li>LeakyReLU activation layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>PReLU activate layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>ELU activation layer (by <a href="https://github.com/avan1235">Maciej Procyk</a>)</li><li>ThresholdedReLU activation layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>Conv1D layer (by <a href="https://github.com/avan1235">Maciej Procyk</a>)</li><li>MaxPooling1D layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>AveragePooling1D layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>GlobalMaxPooling1D layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>GlobalAveragePooling1D layer (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>Conv3D layer (by <a href="https://github.com/avan1235">Maciej Procyk</a>)</li><li>MaxPooling3D layer (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>AveragePooling3D layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>GlobalAveragePooling3D layer (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>GlobalMaxPool2D layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>GlobalMaxPool3D layer (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>Cropping1D and Cropping3D layers (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li><li>Permute layer (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>RepeatVector layer (by <a href="https://github.com/dosier">Stan van der Bend</a>)</li><li>UpSampling1D, UpSampling2D, and UpSampling3D layers (by <a href="https://github.com/mkaze">Masoud Kazemi</a>)</li></ul><p>Two new initializers:</p><ul><li>Identity initializer (by <a href="https://github.com/hbrammer">Hauke Brammer</a>)</li><li>Orthogonal initializer (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li></ul><p>And six new activation functions:</p><ul><li>Gelu activation function (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>HardShrink activation function (by <a href="https://github.com/therealansh">Ansh Tyagi</a>)</li><li>LiSHT activation function (by <a href="https://github.com/knok16">Veniamin Viflyantsev</a>)</li><li>Mish activation function (by <a href="https://github.com/digantamisra98">Xa9aX ツ</a>)</li><li>Snake activation function (by <a href="https://github.com/cagriyildirimR">cagriyildirimR</a>)</li><li>TanhShrink activation function(by <a href="https://github.com/femialaka">Femi Alaka</a>)</li></ul><p>These activation functions are not available in the TensorFlow core package, but we decided to add them, seeing how they’ve been widely used in recent papers.</p><p>In the next release, we’re going to achieve layer parity with the <a href="https://keras.io/api/layers/">current set of layers in Keras</a> and, perhaps, go further by adding several popular layers from the SOTA implementations of recent models that are not yet included in the main Keras distribution.</p><p>We would be delighted to look at your pull requests if you would like to contribute a layer, activation function, callback, or initializer from the recent paper!</p><h3>How to add KotlinDL to your project</h3><p>To use the full power of KotlinDL (including the `onnx` and `visualization` modules) in your project, add the following dependencies to your <em>build.gradle</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d7e76190c495c4dc7786059377f3285/href">https://medium.com/media/3d7e76190c495c4dc7786059377f3285/href</a></iframe><p>Or add just one dependency if you don’t need ONNX and visualization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eac2b021d21670ffca0a54b7ac84a180/href">https://medium.com/media/eac2b021d21670ffca0a54b7ac84a180/href</a></iframe><p>You can also take advantage of KotlinDL’s functionality in any existing Java project, even if you don’t have any other Kotlin code in it yet. <a href="https://github.com/JetBrains/KotlinDL/blob/master/examples/src/main/java/LeNetClassic.java">Here</a> is an example of the LeNet-5 model entirely written in Java.</p><h3>Learn more and share your feedback</h3><p>We hope you enjoyed this brief overview of the new features in KotlinDL 0.3! For more information, including the up-to-date <a href="https://github.com/JetBrains/KotlinDL/blob/master/README.md">Readme file</a>, visit the project’s home on <a href="https://github.com/JetBrains/KotlinDL">GitHub</a>. Be sure to check out the KotlinDL <a href="https://github.com/JetBrains/KotlinDL/blob/master/docs/quick_start_guide.md">guide</a>, which contains detailed information about the library’s basic and advanced features and covers many of the topics mentioned in this blog post in more detail.</p><p>If you have previously used KotlinDL, use the <a href="https://github.com/JetBrains/KotlinDL/blob/master/CHANGELOG.md">changelog</a> to find out what has changed and how to upgrade your projects to the stable release.</p><p>We’d be very thankful if you would report any bugs you find to our issue tracker. We’ll try to fix all the critical issues in the 0.3.1 release.</p><p>You are also welcome to join the <a href="https://app.slack.com/client/T09229ZC6/C01DZU7PW73">#kotlindl channel</a> in Kotlin Slack (get an invite <a href="http://slack.kotlinlang.org/?_ga=2.28360636.1631899419.1619088615-984759609.1618823233">here</a>). In this channel, you can ask questions, participate in discussions, and get notifications about the new preview releases and models in ModelHub.</p><p>Let’s Kotlin!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43fffd3cb94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin DL Version 0.2:]]></title>
            <link>https://zaleslaw.medium.com/kotlin-dl-version-0-2-da2ed079f567?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/da2ed079f567</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Mon, 17 May 2021 12:40:45 GMT</pubDate>
            <atom:updated>2021-05-18T14:12:04.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin DL Version 0.2: Functional API, Model Zoo With ResNet and MobileNet, Idiomatic Kotlin DSL for Image Preprocessing</h3><p>Introducing version 0.2 of our deep learning library, <a href="https://github.com/JetBrains/KotlinDL">KotlinDL</a>.</p><p>KotlinDL 0.2 is available now on <a href="https://search.maven.org/artifact/org.jetbrains.kotlinx/kotlin-deeplearning-api">Maven Central</a> with a variety of new features — check out all the <a href="https://github.com/JetBrains/KotlinDL/blob/master/CHANGELOG.md">changes</a> coming to the new release! New layers, a special Kotlin-idiomatic DSL for image preprocessing, a few types of Datasets, a great Model Zoo with support for the ResNet and MobileNet model families, and many more changes are now receiving a final polish.</p><p>In this post, we’ll walk you through the changes to the Kotlin Deep Learning library in the 0.2 release:</p><ol><li>Functional API</li><li>Model Zoo: support for the ResNet and MobileNet model families</li><li>DSL for image preprocessing</li><li>New layers</li><li>Dataset API and its implementations: OnHeapDataset &amp; OnFlyDataset</li><li>Embedded datasets</li><li>Adding KotlinDL to your project</li><li>Learning more &amp; giving feedback</li></ol><h3>Functional API</h3><p>With the previous version of the library, you could only use the Sequential API to describe your model. Using the <em>Sequential.of(..)</em> method call, it has been possible to build a sequence of layers to describe models in a style similar to <a href="https://arxiv.org/abs/1409.1556">VGG</a>.</p><p>Since 2014, many new architectures have addressed the disadvantages inherent in simple layer sequences, such as vanishing gradients or the degradation (accuracy saturation) problem. The famous residual neural networks (ResNet) use skip connections or shortcuts to jump over layers. In version 0.2, we’ve added a new Functional API that makes it possible for you to build models such as ResNet or MobileNet.</p><p>The Functional API provides a way to create models that are more flexible than the Sequential API. The Functional API can handle models with non-linear topology, shared layers, and even multiple inputs or outputs.</p><p>The main idea behind it is that a deep learning model is usually a directed acyclic graph (DAG) of layers. So the Functional API is a way to build graphs of layers.</p><p>Let’s build a ToyResNet model for the FashionMnist dataset to demonstrate this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef7ac9b2011236f8e28190f1c4694998/href">https://medium.com/media/ef7ac9b2011236f8e28190f1c4694998/href</a></iframe><p>Here’s a summary of the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*nGYJflAHnUvk9l-F" /></figure><p>And here is a representation of the model architecture typical of the whole ResNet model family:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*JNPrtqRDUCvXHTvo" /></figure><p>The main design of this API is borrowed from the Keras library, but it is not a complete copy. If you find any discrepancies between our API and the Keras library API, please refer to our documentation.</p><h3>Model Zoo: ResNet and MobileNet models families support</h3><p>Starting with the 0.2 release, Kotlin DL will include a Model Zoo, a collection of deep convolutional networks pre-trained on a large image dataset known as ImageNet.</p><p>The Model Zoo is important because modern architectures of convolutional neural networks can have hundreds of layers and tens of millions of parameters. Training models to an acceptable accuracy level (~70–80%) on ImageNet may require hundreds or thousands of hours of computation on a cluster of GPUs. With the Model Zoo, there is no need to train a model from scratch every time you need one. You can get a ready, pre-trained model from our repository of models and immediately use it for image recognition or transfer learning.</p><p>The following models are currently supported:</p><ul><li>VGG’16</li><li>VGG’19</li><li>ResNet50</li><li>ResNet101</li><li>ResNet152</li><li>ResNet50v2</li><li>ResNet101v2</li><li>ResNet152v2</li><li>MobileNet</li><li>MobileNetv2</li></ul><p>All the models in the Model Zoo include a special loader of model configs and model weights, as well as the special data preprocessing function that was applied when the models were trained on the <a href="http://www.image-net.org/">ImageNet dataset</a>.</p><p>Here’s an example of how to use one of these models, ResNet50, for prediction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e8065d7571223c4156fc079b558a762/href">https://medium.com/media/7e8065d7571223c4156fc079b558a762/href</a></iframe><p>Now, you’ve got a model and weights, and you can use it in KotlinDL.</p><blockquote>NOTE: Don’t forget to apply model-specific preprocessing for the new data. All the preprocessing functions are included in the Model Zoo and can be called via the preprocessInput function.</blockquote><p>If you want to train VGG or ResNet models from scratch, you can simply load the model configuration or start from the full model code written in Kotlin. All Model Zoo models are available via top-level functions located in the <em>org.jetbrains.kotlinx.dl.api.core.model </em>package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d42251b793ab2094780013b428dcc0/href">https://medium.com/media/e4d42251b793ab2094780013b428dcc0/href</a></iframe><p>A full example of how to use VGG’19 for prediction and transfer learning with additional training on a custom dataset can be found in <a href="https://github.com/JetBrains/KotlinDL/blob/master/docs/transfer_learning.md">this tutorial</a>.</p><h3>DSL for image preprocessing</h3><p>Python developers have access to a huge number of utilities and libraries for data preprocessing. However, in JVM languages, there are specific difficulties with preprocessing images, videos, and music. Most libraries for image preprocessing in Java and Kotlin use the BufferedImage class, whose methods are sometimes inconsistent and at a very low level of abstraction. We decided to simplify the lives of Kotlin developers by making an easy and straightforward DSL using lambdas with receivers for setting the image preprocessing pipeline.</p><p>The DSL for image preprocessing can use the following operations:</p><ul><li>Load</li><li>Crop</li><li>Resize</li><li>Rotate</li><li>Rescale</li><li>Sharpen</li><li>Save</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ad7b6153e4dd0340129874da495c10/href">https://medium.com/media/11ad7b6153e4dd0340129874da495c10/href</a></iframe><p>As a result, basic augmentation can be implemented manually. Below you can find several images obtained by the preprocessing application mentioned above, changing the rotation angle and image size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*QKCnl4i-r83tQsEa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*8rOpanlgZZWE-OnU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*ofFwWwc_i1SwFyHn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/0*Xdy_0MM2DlroClc5" /></figure><p>If you use additional image preprocessing steps, please feel free to make a feature request in <a href="https://github.com/JetBrains/KotlinDL/issues">our issue tracker</a>.</p><h3>New layers</h3><p>We’ve implemented a variety of new layers that are required for ResNet and MobileNet models:</p><ul><li>BatchNorm</li><li>ActivationLayer</li><li>DepthwiseConv2D</li><li>SeparableConv2D</li><li>Merge (Add, Subtract, Multiply, Average, Concatenate, Maximum, Minimum)</li><li>GlobalAvgPool2D</li><li>Cropping2D</li><li>Reshape</li><li>ZeroPadding2D*</li></ul><p>*Kudos to <a href="https://github.com/AntKos">Anton Kosyakov</a> for implementing ZeroPadding2D!</p><p>If you would like to contribute a layer, we would be delighted to take a look at your pull requests.</p><h3>Dataset API and its implementations: OnHeapDataset &amp; OnFlyDataset</h3><p>The standard way to run data through a neural network in <em>forward </em>mode is to load batches one by one into RAM and then into the memory area controlled by the TensorFlow computational graph.</p><p>We support this approach with an on-the-fly dataset (OnFlyDataset). It sequentially loads batch after batch into RAM during one training epoch, applying the preprocessing described in advance (if it was defined).</p><p>But what if our data fits into RAM? You can use an OnHeapDataset to load and keep all this data in RAM without reading it repeatedly from the disk at each epoch.</p><h3>Embedded datasets</h3><p>For those of you who are just starting your journey in deep learning, we recommend practicing building your first neural networks on well-known datasets, such as a set of handwritten numbers (MNIST dataset), a similar set of images of fashion items from Zalando (FashionMNIST), the famous Cifar’10 dataset (50,000 images), or a collection of photos of cats and dogs from one of the most popular Kaggle competitions (25,000 images of various sizes).</p><p>All these datasets are stored remotely and, if necessary, can be downloaded to a folder on your disk. If the dataset has already been downloaded, it will be not downloaded again and loaded immediately from the disk.</p><h3>Adding KotlinDL to your project</h3><p>To use KotlinDL in your project, you need to add the following dependency to your <em>build.gradle</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01b18f303e4f89bf5d22721156d63dad/href">https://medium.com/media/01b18f303e4f89bf5d22721156d63dad/href</a></iframe><p>You can also take advantage of Kotlin DL functionality in any existing Java project, even if you don’t have any other Kotlin code in it yet. <a href="https://github.com/JetBrains/KotlinDL/blob/master/examples/src/main/java/LeNetClassic.java">Here</a> is an example of the LeNet-5 model written completely in Java.</p><h3>Learning more &amp; giving feedback</h3><p>We hope you enjoyed this brief overview of the new features in KotlinDL version 0.2! For more information, including the up-to-date <a href="https://github.com/JetBrains/KotlinDL/blob/master/README.md">Readme file</a>, visit the project’s home on <a href="https://github.com/JetBrains/KotlinDL">GitHub</a>. Be sure to check out the KotlinDL <a href="https://github.com/JetBrains/KotlinDL/blob/master/docs/quick_start_guide.md">guide</a>, which contains detailed information about the library’s basic and advanced features and covers many of the topics mentioned in this blog post in more detail.</p><p>If you have previously used KotlinDL, use the <a href="https://github.com/JetBrains/KotlinDL/blob/master/CHANGELOG.md">changelog</a> to find out what has changed and how to upgrade your projects to the stable release.</p><p>If you would like an exclusive behind-the-scenes look at KotlinDL, you can also check out <a href="https://www.youtube.com/watch?v=jCFZc97_XQU&amp;t=61s">this talk</a> from Alexey Zinoviev, which offers a closer look at the library’s design, ideology, potential audience, and behavior.</p><p>We’d be very thankful if you would report any bugs you find to our issue tracker. We’ll try to fix all the critical issues in the 0.2.1 release.</p><p>You are also welcome to join the <a href="https://app.slack.com/client/T09229ZC6/C01DZU7PW73">#kotlindl channel</a> in Kotlin Slack (get an invite <a href="http://slack.kotlinlang.org/?_ga=2.28360636.1631899419.1619088615-984759609.1618823233">here</a>). In this channel, you can ask questions, participate in discussions, and get notifications about the new preview releases and models in the Model Zoo.</p><p>Let’s Kotlin!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da2ed079f567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theory and practice of hyperparameter tuning with Apache Ignite ML]]></title>
            <link>https://zaleslaw.medium.com/theory-and-practice-of-hyperparameter-tuning-with-apache-ignite-ml-2059d2f50329?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/2059d2f50329</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[apache-ignite]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Wed, 09 Dec 2020 16:12:21 GMT</pubDate>
            <atom:updated>2020-12-09T16:12:21.255Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to build the best model</h3><p>Data scientists train models by running training algorithms. There are many different ways to build a Linear Regression model or a Decision Tree model. And, each training algorithm (trainer) has several tunable settings, the values of which can be changed before a training starts. Every value can affect the final result (that is, the trained model).</p><p>What happens if we try to find the tunable settings’ best values and re-use them to train the best model?</p><p>Before we start, we need to answer a few questions:</p><ul><li>How do we determine that a given set of tunable settings is the best?</li><li>Where are the boundaries of what is a tunable setting, and isn’t a tunable setting?</li><li>How do we find the best values for the tunable settings?</li><li>How can we ensure that our search for the best values for tunable settings is compatible with the modern practice of training models?</li></ul><p>Let’s keep in mind that such settings are known, in machine learning, as “hyperparameters” and that the task of a value search for optimal hyperparameters is known as “HPO” (Hyperparameter Optimization Problem).</p><h3>Hyperparameters and model parameters</h3><p>Let’s start from the basic definition: What is and is not a hyperparameter?</p><p>Newbies in ML are often confused about the model parameters and hyperparameters of training algorithms.</p><p>Model parameters are learned during training, and hyperparameters, on the contrary, must be set by a data scientist or AutoML before training.</p><p>A good example of model parameters is a slope and intercept in linear regression or a weight tensor in the convolutional layer — we are trying to find the best parameters during one training. On the opposite side, the initial learning rate in the SGD optimization algorithm or the number of trees in Random Forest should be defined before training and can be different in different training runs.</p><p>The main idea of HPO is to find the hyperparameters of a given ML algorithm or of the pipeline that returns the best metric value, as measured on a validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*cE4bjpHdvA4aQTc5" /></figure><p>Yes, we could treat the best hyperparameters as parameters that are learned from the validation dataset rather than directly from within ML algorithms. And, I suppose that, with the AutoML era (in the near future), the difference between model parameters and hyperparameters will be erased.</p><h3>Math description of HPO (Hyperparameter Optimization Problem)</h3><p>Hyperparameter optimization can be formulated as a bilevel (two-level) optimization problem, where the optimal parameters on the training set depend on the hyperparameters.</p><p>Let w denote parameters (e.g., weights and biases) and λ denote hyperparameters (e.g., dropout probability). Let L_t and L_v be functions mapping parameters and hyperparameters to training and validation losses, respectively. We aim to solve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*xqd-2z6DWEt5fjNG" /></figure><p>subjects to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/0*3612IRixHIQg_pHo" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*QHfWA3S0ZdJsOr0S" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*UzfhH4uUJthNzCcb" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N2j_K3jLY8NFYUr8" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*47LOiPq7CGsr7P1L" /></figure><p>From [<a href="https://openreview.net/pdf?id=r1eEG20qKQ">1</a>]</p><p>A bilevel optimization problem consists of two sub-problems called the <em>upper-level</em> and <em>lower-level </em>problems, where the upper-level problem must be solved subject to the optimality of the lower-level problem. Minimax problems are an example of bilevel programs where the upper-level objective equals the negative lower-level objective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*RliE-mHXhyXap3jU" /></figure><p>Bilevel programs were first studied in economics to model leader/follower firm dynamics (Von Stackelberg, 2010) and have since found uses in various fields (see Colson et al. (2007) for an overview). In machine learning, many problems can be formulated as bilevel programs, including hyperparameter optimization, GAN training (Goodfellow et al., 2014), meta-learning, and neural architecture search (Zoph &amp; Le, 2016)</p><p>Even if all objectives and constraints are linear, bilevel problems are strongly NP-hard (Hansen et al., 1992; Vicente et al., 1994). NP-hard complexity of the HPO task is a reason why we should avoid direct methods or brute-force technique and prefer heuristic algorithms with polynomial complexity (even if these heuristics do not have proven upper bounds for polynomial complexity but are only observable as such).</p><h3>ML algorithms that are supported in the Apache Ignite ML framework</h3><p>Let’s list all the currently available Ignite ML training algorithms and the algorithms’ tunable hyperparameters.</p><p>I will start with algorithms that are based on different versions of SGD (stochastic gradient descent).</p><p><a href="https://ignite.apache.org/docs/latest/machine-learning/regression/linear-regression#sgd-trainer">LinearRegressionSGDTrainer</a></p><ul><li><strong>maxIterations</strong> — the maximum number of iterations before the training will be stopped</li><li><strong>batchSize</strong> — the batch size for the SGD-based updating algorithm</li><li><strong>locIterations</strong> — the maximum number of local iterations before synchronization</li><li><strong>seed</strong> — just seed</li><li><strong>updatesStgy</strong> — an analog of the optimizer in DL frameworks</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/binary-classification/logistic-regression">LogisticRegressionSGDTrainer</a></p><ul><li><strong>maxIterations</strong> — the maximum number of iterations before the training will be stopped</li><li><strong>batchSize</strong> — the batch size for the SGD-based updating algorithm</li><li><strong>locIterations</strong> — the maximum number of local iterations before synchronization</li><li><strong>seed</strong> — just seed</li><li><strong>updatesStgy</strong> — an analog of the optimizer in DL frameworks</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/binary-classification/linear-svm">SVMLinearClassificationTrainer</a></p><ul><li><strong>amountOfIterations </strong>— the number of outer SDCA algorithm iterations</li><li><strong>amountOfLocIterations </strong>— the number of local SDCA algorithm iterations</li><li><strong>lambda </strong>— a regularization parameter</li><li><strong>seed</strong> — just seed</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/binary-classification/multilayer-perceptron">MLPTrainer</a></p><ul><li><strong>arch </strong>— a neural network architecture that defines layers and activation functions</li><li><strong>loss </strong>— a loss function to be minimized during the training</li><li><strong>maxIterations</strong> — the maximum number of iterations before the training will be stopped</li><li><strong>batchSize</strong> — the batch size for the SGD-based updating algorithm</li><li><strong>locIterations</strong> — the maximum number of local iterations before synchronization</li><li><strong>seed</strong> — just seed</li><li><strong>updatesStgy</strong> — an analog of the optimizer in DL frameworks</li></ul><p>The sets of hyperparameters for the four algorithms are similar because all of the algorithms use an iterative optimization algorithm internally. The number of iterations and the type of optimizer play an essential role. Even minor changes in the hyperparameters can produce significant differences in the predictive abilities of the resulting models.</p><p>Now, let’s now move on to the widely used family of metric clustering and classification algorithms.</p><p><a href="https://ignite.apache.org/docs/latest/machine-learning/clustering/k-means-clustering">KMeansTrainer</a></p><ul><li><strong>k </strong>— the number of clusters to be discovered</li><li><strong>maxIterations </strong>— the number of iterations</li><li><strong>epsilon </strong>— the numerical value that is used to check the convergence on each iteration</li><li><strong>distance</strong> — an ML framework distance measure, such as Euclidean, Hamming, or Manhattan</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/clustering/gaussian-mixture">GmmTrainer</a></p><ul><li><strong>maxCountOfClusters </strong>— the number of possible clusters</li><li><strong>maxCountOfIterations </strong>— the number of iterations, a stop criteria (the other stop criteria is epsilon)</li><li><strong>epsilon </strong>— delta between the values of the old and new centroids</li><li><strong>countOfComponents </strong>— the number of components</li><li><strong>maxLikelihoodDivergence </strong>— the maximum divergence between the maximum of the likelihood of each of two vectors in the datasets for anomalies identification;</li><li><strong>minElementsForNewCluster </strong>— the minimum number of required anomalies, in terms of maxLikelihoodDivergence, for creating a cluster</li><li><strong>minClusterProbability </strong>— the minimum cluster probability</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/binary-classification/knn-classification">KNNClassificationTrainer</a> and <a href="https://ignite.apache.org/docs/latest/machine-learning/regression/knn-regression">KNNRegressionTrainer</a></p><ul><li><strong>k </strong>— the number of nearest neighbors</li><li><strong>distanceMeasure </strong>— an ML framework’s distance metric, such as Euclidean, Hamming, or Manhattan</li><li><strong>isWeighted </strong>— false by default; if true, this hyperparameter enables a weighted KNN algorithm.)</li><li><strong>dataCache </strong>— a holder for a set of training objects for which the class is known</li><li><strong>indexType </strong>— a distributed spatial index that has three values: ARRAY, KD_TREE, and BALL_TREE</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/binary-classification/ann">ANNClassificationTrainer</a></p><ul><li><strong>k </strong>— the number of candidate points for the prediction phase of the search of nearest neighbors</li><li><strong>maxIterations </strong>— the number of iterations</li><li><strong>epsilon </strong>— the numerical value that is used to check the convergence on each iteration</li><li><strong>distance</strong> — an ML framework’s distance measure, such as Euclidean, Hamming, or Manhattan</li></ul><p>Let’s move on to growing trees and forest thickets. Gardening has the specificity that is tied to the amount of information and entropy.</p><p><a href="https://ignite.apache.org/docs/latest/machine-learning/binary-classification/decision-trees">DecisionTreeClassificationTrainer</a> and <a href="https://ignite.apache.org/docs/latest/machine-learning/regression/decision-trees-regression">DecisionTreeRegressionTrainer</a></p><ul><li><strong>maxDeep </strong>— the maximum depth of the tree</li><li><strong>minImpurityDecrease </strong>— the minimum impurity decrease</li><li><strong>usingIdx </strong>— a setting that enables the use of an index structure instead of using sorting while learning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5IQ2wQd8PoyJfzEU" /></figure><p><a href="https://ignite.apache.org/docs/latest/machine-learning/ensemble-methods/random-forest">RandomForestClassifierTrainer</a></p><ul><li><strong>featuresCountSelectionStrgy </strong>— a strategy that defines the count of random features for one tree learning</li><li><strong>maxDepth </strong>— the maximum depth of the tree</li><li><strong>minImpurityDelta </strong>— a node in a decision tree is split into two nodes if the delta between impurity values on the two nodes is less than the unspilt node’s minImpurityDecrease value.</li><li><strong>subSampleSize </strong>— the value that lies in the [0; MAX_DOUBLE] interval; a parameter that defines the count of sample repetitions during uniform sampling with replacement</li><li><strong>seed </strong>— the seed value that is used in random generators</li></ul><p><a href="https://ignite.apache.org/docs/latest/machine-learning/ensemble-methods/gradient-boosting">GDBBinaryClassifierOnTreesTrainer and GDBRegressionOnTreesTrainer</a></p><ul><li><strong>maxDeep </strong>— the maximum depth of the tree</li><li><strong>minImpurityDecrease </strong>— the minimum impurity decrease</li><li><strong>usingIdx </strong>— a setting that enables the use of index structure instead of using sorting while learning;</li><li><strong>gradStepSize </strong>— the constant weight of each model in composition</li><li><strong>cntOfIterations </strong>— the maximum number of iterations</li><li><strong>checkConvergenceFactory </strong>— the factory for construction of the convergence checker that is used to prevent the overfitting and learning of useless models during training</li></ul><p>Consider the latest representative of ensemble algorithms, bagging, which used different trainer algorithms (not only trees).</p><p><a href="https://ignite.apache.org/docs/latest/machine-learning/ensemble-methods/bagging">BaggedTrainer</a></p><ul><li><strong>ensembleSize — </strong>the number of trained models in the ensemble</li><li><strong>subsampleRatio — </strong>the subsample ratio of the dataset</li><li><strong>aggregator </strong>— the type of ensemble model prediction aggregation</li><li><strong>featureVectorSize </strong>— feature vector dimensionality</li><li><strong>featuresSubspaceDim </strong>— feature subspace dimensionality</li></ul><p>The following training algorithms do not have hyperparameters:</p><ul><li><a href="https://ignite.apache.org/docs/latest/machine-learning/regression/linear-regression#lsqr-trainer">LinearRegressionLSQRTrainer</a></li><li><a href="https://ignite.apache.org/docs/latest/machine-learning/ensemble-methods/stacking">StackedVectorDatasetTrainer</a></li></ul><p>No need to remember all the parameters, but I hope that you are impressed by the number of tunable settings in the Apache Ignite ML framework.</p><h3>Preprocessors</h3><p>The training process in Ignite ML is not limited by training only. Various preprocessors can help normalize numbers or convert strings to numbers.</p><p>Ignite ML now supports the tuning of the hyperparameters of the preprocessor trainers. For example, in <a href="https://ignite.apache.org/docs/latest/machine-learning/preprocessing#normalization-preprocessor">NormalizationTrainer</a>, a user can tune the hyperparameter ‘p’ (the parameter that is responsible for normalization in L^p space), and, in <a href="https://ignite.apache.org/docs/latest/machine-learning/preprocessing#normalization-preprocessor">ImputerTrainer</a>, the user can input strategy.</p><blockquote><strong>NOTE</strong>: The right choice of column scaler is a well-known hyperparameter tuning issue. Currently, Ignite ML offers a few scalers: <a href="https://ignite.apache.org/docs/latest/machine-learning/preprocessing#minmax-scaler-preprocessor">MinMax Scaler</a>, <a href="https://ignite.apache.org/docs/latest/machine-learning/preprocessing#maxabsscaler-preprocessor">MaxAbsScaler</a>, and StandardScaler. Unfortunately, the ability to tune a column scaler as a hyperparameter is not yet supported.</blockquote><blockquote>When the AutoML elements are added to the ML framework, the issue of column-scaler choice will be resolved.</blockquote><h3>Model evaluation</h3><p>Apache Ignite ML provides a suite of classification and regression metrics to evaluate the prediction accuracy of ML models.</p><p>There are many classification algorithms. However, classification models are evaluated in similar ways. For each data point in a supervised classification problem, there are two outputs, a true output and a model-generated, predicted output. Therefore, the results for each data point can be assigned to one of four categories:</p><ul><li><strong>True Positive (TP) </strong>— The label is positive, and the prediction is also positive.</li><li><strong>True Negative (TN)</strong> — The label is negative, and the prediction is also negative.</li><li><strong>False Positive (FP)</strong> — The label is negative, but the prediction is positive.</li><li><strong>False Negative (FN)</strong> — The label is positive, but the prediction is negative.</li></ul><p>The following is a list of the binary classification metrics that are supported in Apache Ignite ML:</p><ul><li>Accuracy</li><li>Balanced accuracy</li><li>F-Measure</li><li>FallOut</li><li>FN</li><li>FP</li><li>FDR</li><li>MissRate</li><li>NPV</li><li>Precision</li><li>Recall</li><li>Specificity</li><li>TN</li><li>TP</li></ul><p>The explanations and formulas for these metrics can be found <a href="https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/283982116926f47f74ec84cef7cb2c92/href">https://medium.com/media/283982116926f47f74ec84cef7cb2c92/href</a></iframe><blockquote><strong>NOTE: </strong>In Apache Ignite ML, multiclass classification evaluation is not yet supported.</blockquote><p>When a continuous output variable is predicted from several independent variables, regression analysis is used.</p><p>The following is a list of the regression metrics that are supported in Apache Ignite ML:</p><ul><li>MAE</li><li>R2</li><li>RMSE</li><li>RSS</li><li>MSE</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3ac3b0a9fe9a6cf717b42b516ee0cf6/href">https://medium.com/media/a3ac3b0a9fe9a6cf717b42b516ee0cf6/href</a></iframe><blockquote><strong>NOTE: </strong>The metric calculations run distributedly, without collecting all predicted or actual (ground truth) labels on one client node.</blockquote><h3>Test-train splitting</h3><p>It is not good practice to learn and validate the model parameters on the same data. This practice leads to overfitting. One of the most efficient solutions is to save and use part of the training data as a test set.</p><p>A test-train splitting term in Apache Ignite ML means to filter the data that is stored in a cache into two parts (the training part used to train the model and the test part used to estimate the model quality). The filtering is performed according to particular conditions. In reality, no data transfer or network shuffle.</p><p>All fit() methods have a parameter that passes a filter condition to each cache.</p><blockquote><strong>NOTE:</strong> Due to the distributed and lazy nature of dataset operations, the dataset split is a lazy operation. The operation could be defined as a filter condition that is applied to the initial cache to form both the train and test datasets.</blockquote><p>In the following example, the model is trained on only 75% of the initial dataset. The value of the filter parameter results from the split.getTrainFilter(), which can continue with or reject a row from the initial dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f82c6c8ff2d508f043f07df5fea3ba1/href">https://medium.com/media/0f82c6c8ff2d508f043f07df5fea3ba1/href</a></iframe><h3>Cross-validation types</h3><p>Okay, test-train splitting helps to avoid overfitting. However, by partitioning the available data and excluding one or more subsets of the data from the training set, we significantly reduce the number of samples that are used to learn the model parameters. The results depend on a particular random choice for the pair of train and validation subsets.</p><p>The cross-validation approach solves this problem. Apache Ignite ML implements K-fold cross-validation:</p><ol><li>The training set is split into multiple sub-datasets. The k parameter defines the number of sub-datasets.</li><li>Ignite ML uses k-1 of the folds (subsets) as training data and trains a model.</li><li>The resulting model is validated on the data that was not used for training.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*KsRU2dEBb6HqYmE5" /></figure><p>Apache Ignite provides cross-validation functionality that enables it to parameterize the trainer that is to be validated, the metrics that are to be calculated for the model, and the number of folds that the training data should be split into.</p><p>You can find more information about cross-validation parameters on <a href="https://ignite.apache.org/docs/latest/machine-learning/model-selection/cross-validation">documentation</a>.</p><p>The user can also pass <em>split.getTrainFilter() </em>to the CrossValidation object to perform cross-validation on only the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*MM46AHEifskWJBB5" /></figure><h3>Hyperparameter tuning process</h3><p>In many cases, manual tuning is not an option because we need to tune multiple parameters. Of course, we could write a few loops inside each other to iterate through all possible combinations of parameters, as in the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/204e732fcbed7cd6c1da8902c60f578c/href">https://medium.com/media/204e732fcbed7cd6c1da8902c60f578c/href</a></iframe><p>And, of course, every software engineer’s first idea is to automate the process of parameter-set generation and injection in training algorithms and preprocessors.</p><p>But, I am happy to announce that, beginning with the 2.8 release of the Ignite ML framework, the automatic hyperparameter tuning feature is available. Now, Ignite ML includes a built-in library for serial and parallel optimization over awkward discrete search spaces.</p><p>Also, on the roadmap, a feature to support search spaces with real-valued, discrete, and conditional dimensions is planned. Highly likely, Apache Ignite 3.0 will ship with this feature onboard.</p><h3>ParamGrid</h3><p>The primary object that keeps all possible values of hyperparameters is the ParamGrid object.</p><p>There are multiple approaches to finding the optimal set of hyperparameters:</p><ul><li><strong>Brute Force (Grid Search)</strong> — The traditional way of performing hyperparameter optimization is grid search ( parameter sweep). Grid search is an exhaustive search through a manually specified subset of the hyperparameter space of a learning algorithm.</li><li><strong>Random search</strong> — Random search replaces the exhaustive enumeration of all combinations by selecting them randomly.</li><li><strong>Evolutionary optimization</strong> — Evolutionary optimization is a methodology for the global optimization of noisy black-box functions. In hyperparameter optimization, evolutionary optimization uses evolutionary algorithms to search the hyperparameter space for a given algorithm.</li></ul><p>The <a href="https://ignite.apache.org/releases/latest/javadoc/index.html">ParamGrid </a>object supports some setter methods that set up the search-strategy parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe22930a667bceec9d282fc10a513f15/href">https://medium.com/media/fe22930a667bceec9d282fc10a513f15/href</a></iframe><p>After the ParamGrid object is created, it can be passed to the CrossValidation object via the <em>withParamGrid()</em> method.</p><p>Firstly, we will consider the basic HPO technique, Grid Search (or Brute Force).</p><p>This approach’s main idea is to run ML Pipeline with all possible combinations of parameters to get the final metric scores. When we have a two-column fulfilled table with the following columns, “Parameter names and values” and “Metric value,” it’s easy to find the best hyperparameter combination to reuse in training from scratch.</p><p>We should keep in mind a combinatorial explosion of the number of parameters’ combinations as the number of hyperparameters and their variants of values grows.</p><p>For example, if we have two hyperparameters with ten variants, 10*10 = 100 training runs are completed. If we increase the number of hyperparameters from 2 to 5, keeping ten variants for each, the 10*10*10*10*10 = 100 000 trainings runs are completed. And, I suppose that nobody would wait long enough for 100 000 training runs to finish.</p><p>You could find a full example <a href="https://github.com/apache/ignite/blob/master/examples/src/main/java/org/apache/ignite/examples/ml/tutorial/Step_8_CV_with_Param_Grid.java">here</a>.</p><h3>Parallel execution</h3><p>When I ran hyperparameter tuning for scikit-learn models, for Random Search and Brute Force cases, I often wrote a handmade parallelization to run a portion of training with parallelization.</p><p>I was confused that a library such as <a href="https://github.com/hyperopt/hyperopt">Hyperopt</a> uses <a href="http://hyperopt.github.io/hyperopt/scaleout/spark/">Apache Spark</a> or <a href="https://github.com/hyperopt/hyperopt/wiki/Parallelizing-Evaluations-During-Search-via-MongoDB">MongoDB </a>to run parallel training and does not have built-in parallelization. Running external JVM executors to start parallel execution is too much for me.</p><p>Of course, when ParamGrid was implemented in Apache Ignite ML, the next station for our developers’ train became a speedup of search by brute force. If you have enough free memory and low CPU utilization, it’s a good idea to start another workout without waiting for the last training run to finish.</p><p>A brute-force search of all possible combinations, where each training runs independently, can be easily parallelized without synchronization barriers.</p><p>To run the parallel version of Cross-Validation, you need to change ParallelismStrategy from NO_PARALLELISM to ON_DEFAULT_POOL in LearningEnvironmentBuilder (CrossValidation parameter), as in the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09ca92538d05c0ecd23b28144c8c0ecd/href">https://medium.com/media/09ca92538d05c0ecd23b28144c8c0ecd/href</a></iframe><p>Imagine that we have a dataset in Ignite’s cache and that we need to run dozens of workouts simultaneously.</p><p>After we call the tuneHyperParameters() method for search by brute force, the following steps are performed:</p><ol><li>The CrossValidation object generates all possible combinations of parameters.</li><li>The CrossValidation object creates a sequence of tasks (one task per each combination of parameters).</li><li>Tasks are submitted to the ThreadPool (with one main thread by default).</li><li>Each task is executed independently, and each result is posted to the shared, thread-safe CrossValidationResult object.</li><li>Inside each task, all parameters are injected into appropriate places of the ML pipeline.</li></ol><p>Each task constructs a new instance of <a href="https://ignite.apache.org/docs/latest/machine-learning/partition-based-dataset">the cache-based dataset</a>, and every partition of the dataset is spread over the Ignite cluster.</p><p>You could find a full example <a href="https://github.com/apache/ignite/blob/master/examples/src/main/java/org/apache/ignite/examples/ml/tutorial/hyperparametertuning/Step_14_Parallel_Brute_Force_Search.java">here</a>.</p><h3>How to make fewer training runs on data (alternative approaches)</h3><p>In [<a href="https://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf">2</a>], Bengio writes that manual search and grid search prevail as state of the art despite decades of research into global optimization and the publishing of several hyperparameter optimization algorithms; Bengio details the reasons for this anomaly:</p><ul><li>There is no technical overhead or barrier to manual optimization.</li><li>Grid search is simple to implement, and parallelization is trivial.</li><li>Typically, Grid Search (with access to a compute cluster) finds a better λ than purely manual sequential optimization finds (in the same amount of time).</li><li>Grid search is reliable in low dimensional spaces (for example, 1-d, 2-d).</li></ul><p>I can add that the performance of Grid Search quickly degrades when it searches the best hyperparameter values in the space of dimension higher than three.</p><h4>Meta-optimization task</h4><p>The parameter space often has a high rank, and a searching surface looks like a pile of dirty clothes in a laundry basket. As a result, the standard methods of convex and non-convex optimization do not apply at searching for global or local optima.</p><h4>Random Search</h4><p>Grid search and manual search are the most widely used strategies for hyperparameter optimization. Paper [<a href="https://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf">2</a>] shows empirically and theoretically that randomly chosen trials are more efficient for hyperparameter optimization than are trials on a grid. When we compare ML algorithms that are configured by a pure grid search with ML algorithms that are configured by random search, we find that Random Search over the same domain can find models that are as good or better and uses a small fraction of the computation time and cluster resources that a Grid Search requires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CgwV-IA1RPlLlEpk" /></figure><p>The Apache Ignite ML implementation does not yet support the generation of random parameters from a range and according to a given distribution, as in paper [<a href="https://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf">2</a>], but the implementation makes random jumps and trials on the discrete grid to ensure no more than a set number of attempts. The calculated metric value on one training run does not influence the choice of hyperparameter set.</p><p>The following example shows how to make ten training runs to find enough good hyperparameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f78ef7533acef5604b9da5929efa6fc4/href">https://medium.com/media/f78ef7533acef5604b9da5929efa6fc4/href</a></iframe><p>Also, Ignite ML includes the parallel version of Random Search optimization. The Ignite’s user could enable it via changing ParallelismStrategy from NO_PARALLELISM to ON_DEFAULT_POOL in LearningEnvironmentBuilder.</p><h4>Genetic algorithms (Evolutionary Optimization)</h4><p>Genetic algorithms, also known as Evolutionary optimization, apply natural selection mechanisms to solve the optimization problem (for example, find the minimum of a function).</p><p>I hope you are familiar with the basic principles of Genetic algorithms, such as population, individuals, fitness function, selection, crossover (crossingover), and mutation. If not, I recommend the following <a href="https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3">article</a> or <a href="https://en.wikipedia.org/wiki/Genetic_algorithm">Wikipedia</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zgrP8kw2Oad6oWQB" /></figure><p>In brief, the adoption of a genetic algorithm to solve the HPO problem includes the following steps:</p><ol><li>The Genetic algorithm (GA) generates an initial population (fixed sets of hyperparameters, with each hyperparameter set representing an individual in the population).</li><li>After that, the GA evaluates the initial population (runs training runs and gets the value of the fitness function; for example, metric value or scores by folds for each set of hyperparameters).</li><li>Via SelectionStrategy (<a href="https://en.wikipedia.org/wiki/Selection_(genetic_algorithm)#Roulette_Wheel_Selection">Roulette Wheel Selection</a>, for example), the genetic algorithm selects the best individuals from the initial population to become the parents of a new generation.</li><li>The GA creates the next generation population with crossover and mutation operators.</li><li>Crossover acts in the following way: To produce a new member of the population, it randomly selects two parents from the previous generation and combines parents’ genes according to the chosen CrossoverStrategy. Ignite ML implements <a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)">Single-point crossover, Two-point crossover, k-point crossover, and Uniform crossover</a>.</li><li>With user-defined mutationProbability, the mutation operator randomly changes a few of the chromosomes of each newly generated child. The mutation operator changes the chromosomes to valid values from the search space.</li><li>The genetic algorithm evaluates the new generation that includes the newly generated children.</li><li>Steps 2 through 6 are repeated until the maximum number of generations is reached or until some other stopping or convergence condition is reached (for example, not enough improvement in fitness function).</li></ol><p>Also, Ignite ML Evolutional strategy supports elitism. Elitism is a practical variant of the general process of constructing a new population. Elitism enables the best organisms from the current generation to carry over to the next generation unaltered.</p><p>This strategy is known as “elitist selection.” The strategy guarantees that the quality of the GA solution does not decrease from one generation to the next. You can set up the number of elite chromosomes in ParamGrid.</p><p>Also, Ignite ML includes the parallel version of Random Search optimization. When you’re working in Ignite, you can enable the parallelization by changing ParallelismStrategy from NO_PARALLELISM to ON_DEFAULT_POOL in LearningEnvironmentBuilder.</p><p>Internally, the parallel version of the GA is implemented as a parallel calculation of fitness functions for all individuals in the population. (one fitness function in one thread). The fitness function calculation is equivalent to the training run with a fixed set of hyperparameters presented as an individual. The end of the evaluation of new individuals is a natural synchronization barrier.</p><p>The following is a practical example of ParamGrid object creation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e44e8a4abcebb62dc3072aabcf6c265/href">https://medium.com/media/8e44e8a4abcebb62dc3072aabcf6c265/href</a></iframe><p>In this three hyperparameter example, each individual in the population will have three chromosomes (genes): <strong>p</strong>, <strong>maxDeep</strong>, and <strong>minImpurityDecrease</strong>. Values from the arrays will be passed to ParamGrid.</p><p>Let’s take a closer look at a couple of individuals in the initial population.</p><p>Suppose that the selection operator selects (1.0; 1.0; 0.0) and (5.0; 2.0; 0.8) as parents and that the parents produce two children via one-point crossover: (1.0; 2.0; 0.8) and (5.0; 1.0; 0.0).</p><p>After that mutation operator changes a gene in the first individual from 0.8 to 0.9. As a result, two children (1.0; 2.0; 0.9) and (5.0; 1.0; 0.0) are added to the new-generation population.</p><p>I hope I have explained some of the tricky things about using genetic algorithms to find the best hyperparameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*lVHHkc3s4zEKf8FQ" /></figure><h3>In conclusion</h3><p>I hope, dear reader, that you now have an idea of how hyperparameter optimization works in Ignite ML.</p><p>In this article, we walked step-by-step through hyperparameter optimization in Apache Ignite ML.</p><p>Automated hyperparameter tuning of ML models can be accomplished by using an Ignite ML HPO implementation. In contrast to Random Search, Evolutionary optimization chooses hyperparameters by applying natural selection mechanisms and, thus, by spending more time evaluating promising values. The outcome can be fewer evaluations of the fitness function and better generalization performance on the test set, as compared to Random Search and Grid Search.</p><p>Of course, there is much work here for Ignite ML contributors: addition of optimization methods such as Bayesian optimization or Gradient-based optimization and improvements such as EarlyStopping logic, which is based on conditions that are implemented via callbacks.</p><p>But, existing methods can significantly reduce the number of training runs and the amount of burned CPU time and occupied memory size.</p><h3>Reference list</h3><p>[1] <a href="https://arxiv.org/abs/1903.03088">Matthew MacKay, Paul Vicol, Jon Lorraine, David Duvenaud, Roger Grosse. <em>Self-Tuning Networks: Bilevel Optimization of Hyperparameters using Structured Best-Response Functions</em>, arXiv:1903.03088 [cs.LG]</a></p><p>[2] <a href="https://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf">James Bergstra and Yoshua Bengio. <em>Random search for hyper-parameter optimization</em>. Journal of Machine Learning Research, 13:281–305, 2012.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2059d2f50329" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Ignite ML Performance Experiment]]></title>
            <link>https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/4036dc0386a3</guid>
            <category><![CDATA[apache-ignite]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 15:20:55 GMT</pubDate>
            <atom:updated>2021-09-01T11:15:26.044Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Spoiler</strong>: The reported data is not an official benchmark with reproducible results and shared code, but the numbers can help with performance estimation.</blockquote><p>A few months ago, I did a time-consuming performance experiment with the new version of Apache® Ignite™ (release 2.8).</p><p>This is the third story in a series of stories about the Apache Ignite ML.</p><ol><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202">Apache Ignite ML: origins and development</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe">Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3">Apache Ignite ML Performance Experiment</a></li></ol><p>First, I wrote a script that generates a dataset in Ignite caches with 15 columns (The dataset contained categorical and numerical features in a 40-to-60 proportion) and a variable number of rows as a parameter. Observations were generated in accordance with the predefined function, which is the sum of linear and nonlinear functions of arguments with the added noise.</p><p>The primary goal (prior to the 2.8 release) was to test performance in most of the presented algorithms, check the scalability effect, compare them with each other, and identify possible bottlenecks.</p><p>I had five machines shipped, each with eight cores and 100GB of RAM onboard. Four machines were used as servers, and one of the machines was used as a client. I deployed Ignite 2.8-SNAPSHOT on all of the machines and ran the ML algorithms with various parameters.</p><p>I ran the Ignite nodes with various settings, but the most common was</p><p><strong><em>-Xmx80G </em></strong><em>and </em><strong><em>DataRegionConfiguration.maxSize* = 10G (OffHeap, </em></strong><em>shortly in the text below</em><strong><em>)</em></strong></p><p>I tested the following next trainers:</p><ul><li>Random forest</li><li>Linear regression with LSQR solver</li><li>Linear regression with SGD solver</li><li>Decision tree for classification and regression tasks</li><li>SVM</li><li>KNN</li><li>ANN</li><li>K-means</li><li>GMM</li><li>Logistic regression</li><li>Boosted logistic regression</li><li>GBT</li></ul><p>When possible, each training was repeated multiple times (10 times on for each machine, then 10 times on two machines, and then 10 times on four machines to get average numbers) with 10³, 10⁴, 10⁵, 10⁶, 10⁷, and 10⁸ rows. Also, each pair &lt; number of machines and number of rows&gt; was copied for perf testing. For each test, hyperparameters that were most appropriate for the current algorithm was used. Wow! A lot of runs.</p><blockquote>And, don’t forget about an important implementation detail — the number of partitions in the initial cache and, as a result, in the partitioned-based dataset. To obtain maximum performance for most algorithms, there should be ~ 1_000–10_000 rows per partition, but I tested with a fixed number of partitions for 10_000 and 10_000_000 rows.</blockquote><p>In the following sections, I share some notes about how to run Ignite ML algorithms to get the best performance.</p><ul><li>DataRegionConfiguration.maxSize = 10G could be set up via configuring of <em>ignite-server.xml</em>, for example:</li></ul><p>You could find more information in the <a href="http://dataregionconfiguration.maxsize/">official documentation</a>.</p><pre>&lt;property name=&quot;dataStorageConfiguration&quot;&gt;<br>            &lt;bean class=&quot;org.apache.ignite.configuration<br>.DataStorageConfiguration&quot;&gt;<br>                &lt;!-- Redefining the default region&#39;s settings --&gt;<br>                &lt;property name=&quot;defaultDataRegionConfiguration&quot;&gt;<br>                    &lt;bean class=&quot;org.apache.ignite.configuration<br>.DataRegionConfiguration&quot;&gt;<br>                        &lt;property name=&quot;maxSize&quot; <br>                                  value=&quot;#{10L * 1024L * 1024L * 1024L}&quot;/&gt;<br>                    &lt;/bean&gt;<br>                &lt;/property&gt;<br>            &lt;/bean&gt;<br> &lt;/property&gt;</pre><h3>Random Forest</h3><p>In Apache Ignite 2.8, I’ve run Ignite ML with the following hyperparameters: 100 trees in ensemble and default settings of Random forest.</p><p>In the following table, I posted the data with initial settings of 1024 partitions on 4 machines with <strong><em>-Xmx80G OffHeap = 10G </em></strong>on the client and server nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/443ec31c327dbdf4791df2cb52b2210c/href">https://medium.com/media/443ec31c327dbdf4791df2cb52b2210c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FSZT3Ps-gxx8jNvSvFJczA.png" /></figure><h3>Linear Regression with LSQR</h3><p>Training time on this super-fast solver doesn’t depend on the amount of data. I tested the solver on various datasets, each with a different number of columns. I found that both required RAM and training time are linearly dependent on the number of features (columns in the dataset). To find the coefficients of linear regression, this trainer is the best choice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/015e4229925d3273a4b2e2af6c876b05/href">https://medium.com/media/015e4229925d3273a4b2e2af6c876b05/href</a></iframe><h3><strong>Linear Regression with SGD Optimizer</strong></h3><p>In distributed systems, SGD is a workhorse, but SGD is a relatively slow optimization method.</p><p>I ran it with the following hyperparameters: maxIterations = 1000, batchSize = 100, locIterations = 100 on 1, 2, 4 nodes. In each case, the training time was close to<strong> linear scalability</strong> (<strong>n</strong> times faster on <strong>n </strong>nodes)</p><p>The following table displays the results of performance testing on 4 nodes with a total of 10 dataset partitions and a variable number of features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c089b8d5bd340b15aee999f2f146c224/href">https://medium.com/media/c089b8d5bd340b15aee999f2f146c224/href</a></iframe><p>The following table reports results for a run with ten features, rather than with a variable number of features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/499e17d9d7c3d49e80f80af341324c7e/href">https://medium.com/media/499e17d9d7c3d49e80f80af341324c7e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9gy1i-fN7Kg3DZTXCtryMA.png" /></figure><p>LinReg with LSQR or SGD can be run on four nodes (with each node requiring 100Gb of RAM) and be trained on 10⁸ rows in one to two minutes.</p><h3>Decision Tree (for Classification)</h3><p>Decision Tree trainer is used to train the tree model in random forest. Unlike with Random Forest, when the decision-tree trainer is used alone, it trains on all the observed data without using sub-sampling techniques.</p><p>I tested this algorithm with two hyperparameters: maxDeep=5, minImpurity=0.</p><p>In the following table, you find the performance testing results on 4 4 machines, with a total of 10 dataset partitions and a variable number of features: 10, 100, 1000.</p><blockquote>I should note that the decision-tree trainer does not scale well and that the best choice is to use random forest, with scaling on the number of trees, instead of on a single decision tree.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee1ee66bd526b4a4a1fb253145c308dc/href">https://medium.com/media/ee1ee66bd526b4a4a1fb253145c308dc/href</a></iframe><p>Unfortunately, I didn’t take the barrier with 10⁷ rows on four machines, each with 100GB RAM.</p><h3>SVM</h3><p>The SVM linear-classification trainer is based on the communication-efficient, distributed, dual coordinate ascent algorithm (CoCoA). In my case, working with 10⁸ rows was easy, but for 10⁹ rows, there was not enough RAM on a few nodes.</p><p>I ran the trainer for 10, 100, and 1024 partitions and found that 10 partitions are better for 0–10⁵ rows, 100 partitions are better for 10⁵ — 10⁶ rows, and 1024 is better for more than 10⁶ rows.</p><p>The following results were produced on a cluster with 4 nodes, a cache with 1024 partitions, and default SVM hyperparameters.</p><p>For example, 10⁸ rows with 10 features were handled within one minute, and the produced model was good enough (acc ~ 90%).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94809ad7fa7ab0e742865d18720cbe79/href">https://medium.com/media/94809ad7fa7ab0e742865d18720cbe79/href</a></iframe><p>Also, I observed that the duration was not dependent on the number of features. At the very end, I encountered issues with garbage collection and the speed of memory allocation, which caused a significant but not a great increase in training time.</p><p>With eight machines with 200GB each, I expect that you will beat 10⁹ rows with ease.</p><h3>KNN</h3><p>This algorithm is special because there is no training phase and the time required for batch prediction depends on the batch size (with n² being the worst case). But, we keep this algorithm in our library because the models that it provides are very accurate and very fast on medium-size datasets.</p><p>I highly recommend that you run this algorithm on an average number of partitions: 50–200.</p><p>Show me the numbers, dude! Catch your numbers, guys!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9245f08b70b2202e10fc7a5ce11a776/href">https://medium.com/media/e9245f08b70b2202e10fc7a5ce11a776/href</a></iframe><h3>K-Means</h3><p>K-means is the most popular clustering algorithm. It is an iterative algorithm, and we could try to find the best clusters (best clusters are clusters that minimizing the pairwise squared deviations of points in the same cluster) until the sun goes supernova.</p><p>This is a reason why I share settings to run. If you run with the same settings, you have a chance to finish close to my time numbers on the same iterative algorithm with a finite number of iterations.</p><p>This distributed implementation is close to linear scalability, and increasing the number of features by 10 times leads to an increase in the time spent on training by 10.</p><p>The following results were produced on an Ignite cluster with 4 nodes, a cache with 1024 partitions. The algorithm was launched with default settings in the task of searching for two clusters in the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2313d2b852671f9de3f1e3266ace2159/href">https://medium.com/media/2313d2b852671f9de3f1e3266ace2159/href</a></iframe><p>The following table focuses on trainings on a dataset with 10 features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f99051ab8bc2a39c81b14826f69d2a4/href">https://medium.com/media/2f99051ab8bc2a39c81b14826f69d2a4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HBy_WhlcWUq-oXUhY7rz3Q.png" /></figure><p>This algorithm is used internally in the following crazy mix of KNN and clustering ideas, the ANN algorithm.</p><h3>ANN</h3><p>I really like this algorithm and am proud to have it in the toolbox of our framework.</p><p>During the prediction phase, ANN’s behavior is similar to KNN’s behavior. However, the number of nearest neighbors doesn’t include the whole dataset but is limited with the value of hyperparameter <strong>k</strong>[<a href="https://ignite.apache.org/releases/latest/javadoc/org/apache/ignite/ml/knn/ann/ANNClassificationTrainer.html#withK-int-">doc</a>] (internally, it uses the k-means algorithm during the training phase to find these k neighbors).</p><p>During the prediction phase, ANN’s behavior is similar to KNN’s behavior. However, the number of the nearest neighbors is limited by the centers of clusters found by k-means during the training phase.</p><p>As a result, training time depends on the number of clusters, and the number of clusters defines how accurate the model will be. Like in strategy games, you need to find the balance between desired accuracy and available resources you can use to train a model.</p><p>The following results were produced on Ignite cluster with 4 nodes, a dataset with 10 columns, a cache with 100 partitions. The ANN trainer was run with two different hyperparameters, <strong>k</strong> — 100 and 1000 nearest neighbors, to compare training times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e04ba9a8c66460281b7b5555367953e6/href">https://medium.com/media/e04ba9a8c66460281b7b5555367953e6/href</a></iframe><p>The accuracy of ANN is close to the accuracy of KNN, but ANN can be trained on datasets that are up to 100 times larger.</p><h3>GMM</h3><p>This algorithm was added at the end of 2019 when it joined the family of clustering algorithms.</p><p>The Gaussian mixture model (GMM) is not like k-means. GMM requires more memory and CPU ops, but GMM can be used to build more accurate models and take into account the distribution characteristics of the generated data.</p><p>GMM almost reaches linear scalability, and training time depends on how many features are close to linear dependence.</p><p>The following results were produced on an Ignite cluster with 4 nodes, a dataset with 10 or 50 or 100 columns, and a cache with 100 partitions. The algorithm was run with default hyperparameter values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8b925bc0177dff338521e2eeef3bf06/href">https://medium.com/media/d8b925bc0177dff338521e2eeef3bf06/href</a></iframe><p>The following table displays the results of training on a dataset with 10 features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0af496601d2ba8072bcafbd28932552/href">https://medium.com/media/e0af496601d2ba8072bcafbd28932552/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*K1GuOXswXzyQofa2O_FBGQ.png" /></figure><h3>Logistic Regression</h3><p>The current implementation of LogReg is a one-layered multilayered perceptron with fixed parameters and an SGD solver.</p><p>As a result, this algorithm has linear scalability for several nodes, and training time is proportional to the number of features.</p><p>Moreover, Logistic Regression is a super-fast, binary classification trainer that can train the model on 100 000 000 rows (with 10 columns per row = 1 000 000 000 doubles) within 1.5 minutes on a cluster with four nodes and a total of 400GB of RAM.</p><p>The following results were produced on an Ignite cluster with 4 nodes, a dataset with 10 or 100 or 1000 columns, a cache with 1024 partitions. The algorithm was run with default hyperparameter values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/725da6d61d15089c42c6a86d98f5c0b4/href">https://medium.com/media/725da6d61d15089c42c6a86d98f5c0b4/href</a></iframe><p>The following table focuses on trainings on a dataset with 10 features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9c022b5ff679550d4b615e05b6b40f6/href">https://medium.com/media/d9c022b5ff679550d4b615e05b6b40f6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Aj4O9rnRjbC8PQHyTIx1Wg.png" /></figure><h3>Boosted Logistic Regression</h3><p>Also, I tested one of the most popular ensemble techniques, boosting, with the best trainer — LogReg.</p><p>The following results were produced on an Ignite cluster with 4 nodes, a dataset with 10,100, 1000 columns, a cache with 100 partitions. The algorithm was run with default hyperparameter values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50997c3e41c068481c71c2c08b2165cf/href">https://medium.com/media/50997c3e41c068481c71c2c08b2165cf/href</a></iframe><h3>GBT (Gradient Boosted Trees)</h3><p>Also, we have our own implementation of gradient boosted trees, a widely known ensemble algorithm.</p><p>The following results were produced on a cluster with 4 nodes, a dataset with 10 columns, and a cache with 1024 partitions. The default GBT hyperparameters were used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e6a8529f00e30be4f188649abdf5393/href">https://medium.com/media/6e6a8529f00e30be4f188649abdf5393/href</a></iframe><p>The following results were produced on a cluster with 4 nodes, a dataset with 10 columns, and a cache with 10 partitions. The default GBT hyperparameters were used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9112985595fd04806c36fbcdfc302dfb/href">https://medium.com/media/9112985595fd04806c36fbcdfc302dfb/href</a></iframe><p>So, this is the end of our performance journey. I hope that our journey will be helpful to you in your own performance experiments.</p><p>P.S. In many cases, algorithms fail (with GC limit exceeded and OutOfMemory errors) because more and more memory is required. Each algorithm has its own memory requirement for intermediate calculations, depending upon how many rows are in the training dataset.</p><p>This is the third story in a series of stories about the Apache Ignite ML.</p><ol><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202">Apache Ignite ML: origins and development</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe">Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3">Apache Ignite ML Performance Experiment</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4036dc0386a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future]]></title>
            <link>https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/2145993f36fe</guid>
            <category><![CDATA[apache-ignite]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apache-spark-ml]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 10:42:59 GMT</pubDate>
            <atom:updated>2020-11-27T15:23:46.713Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, distributed programmers! This is the second post in a series of posts about Ignite ML library.</p><p>Today I would like to talk about possible scenarios for using Ignite ML framework, compare its capabilities with Apache Spark ML, talk about future plans.</p><p>This is the second story in a series of stories about the Apache Ignite ML.</p><ol><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202">Apache Ignite ML: origins and development</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe">Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3">Apache Ignite ML Performance Experiment</a></li></ol><h3>Possible usage scenarios in Big Data architecture and use cases in 2020</h3><p>Okay, ambition is great, you say, but to what scenarios can this Distributed ML framework be applied? When is it time to stop clinging to the Python data-science community and take a decisive step toward Ignite ML?</p><ol><li>Batch training on large datasets and batch predictions on data from Ignite caches</li><li>Batch training on large datasets and real-time prediction on numerous cluster nodes</li><li>Real-time training and real-time prediction</li><li>External training on Apache Spark or on an XGBoost model, model loading to Ignite ML, and batch or real-time predictions.</li><li>External training on Apache Spark or XGBoost model, model loading and updating that is based on Ignite data, and real-time predictions</li><li>Use of preprocessors to calculate basic statistics about data in Ignite tables</li></ol><p>If an item from the bulleted list can solve your problem, I’ll be happy.</p><p>If we need to go deeper into possible use cases, I can safely say that in the same way for which you could use any other machine learning library.</p><p>Classification algorithms can help in a model building in the following areas:</p><ul><li>transaction analysis</li><li>spam detection</li><li>credit scoring</li><li>disease identification</li></ul><p>Regression algorithms can build models that are good in the following areas:</p><ul><li>drug responses</li><li>stock prices</li><li>supermarket revenues</li></ul><p>Clustering algorithms typically are good in next competitions:</p><ul><li>customer segmentation</li><li>grouping of experiment outcomes</li><li>grouping of shopping items</li></ul><p>Recommendation algorithms are newcomers that can help in building simple recommendation systems.</p><blockquote>Maybe the most recent case that I faced will be of interest: The customer kept all the data in an old, on-disk database with an embedded Random Forest algorithm.</blockquote><blockquote>The training, which each time was performed on hundreds of thousands of rows, required lots of hours. The customer had moved his model training and its data mart to Ignite and trained with Ignite ML Random Forest.</blockquote><blockquote>Now, he could repeat his training on a few million rows every ten minutes (if he allocated enough heap memory for JVM, of course, my friends). Performance speed increased by ~ 50–80x (depending on RF hyperparameters).</blockquote><h3>Apache Spark ML versus Apache Ignite ML (feature comparison)</h3><p>The following table identifies and compares the main features of Ignite ML 2.9 and Spark ML 3.0. At the moment, there is a strategic parity of capabilities between the two frameworks.</p><p>Spark is stronger in data preprocessing but weaker in regard to integration with other frameworks, support for model ensembles, and advanced methods for hyperparameter tuning. The weaknesses within the Spark framework are strengths within the Ignite ML framework.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d70570aaaa5df5415343966744b5376b/href">https://medium.com/media/d70570aaaa5df5415343966744b5376b/href</a></iframe><h3>The API guarantees and stability</h3><p>In this section, I discuss how stable the current API is. During the past year, model-training methods and model interfaces and classes, such as decision trees and logistic regression, have changed little. And, I think, they are unlikely to change in the future.</p><p>On the other hand, everything related to the model (fine-tuning of the hyperparameters, model evaluation, model export/import, and integration bridges with other ML frameworks is a hot place for change. So, we don’t guarantee that there will be no breaking changes in the current ML API.</p><p>Also, you need to keep in mind that the number of users is growing and that users find bugs and submit proposals for development of functionality. These user actions lead to improvements. The field of machine learning is also rapidly changing. What seemed unnecessary yesterday may now be present in all frameworks. Therefore, you have to make changes for the sake of user convenience and early access to new features.</p><h3>What’s next?</h3><p>The previous two years have been very turbulent in terms of new and experimental functionality. Some features did not last long; they left under the pressure of the community and of the first users. Some features were added in a hurry and were not backed up by sufficiently deep research (especially with regard to hasty integration with MLeap and TensorFlow 1.14 via the TensorFlow Java API).</p><p>Now, the main functionality from the roadmap is implemented, and it is the time to slow the rapid development of the framework and the rapid addition of new features and hear from the first adopters from the community — to understand what things are important and necessary for users.</p><p>We have many algorithms, good support for ensembles and hyperparameter tuning, basic elements of AutoML, examples are the best among all Apache projects, but there is a lack of functionality related to the MLOps [<a href="https://towardsdatascience.com/ml-ops-machine-learning-as-an-engineering-discipline-b86ca4874a3f">1</a>].</p><p>I read the user-list and dev-list and hear the voices of people who post issues about model export/import, the addition of new preprocessing algorithms, and various minor improvements. Hope to present some solutions for these problems in the next release.</p><p>This is the second story in a series of stories about the Apache Ignite ML.</p><ol><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202">Apache Ignite ML: origins and development</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe">Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3">Apache Ignite ML Performance Experiment</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2145993f36fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Ignite ML: origins and development]]></title>
            <link>https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49a19e67202</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apache-ignite]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 08:13:26 GMT</pubDate>
            <atom:updated>2020-11-27T15:23:23.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, distributed programmers! Nice to see you here, in my technical blog. Gird your loins and read this long, long article about Apache® Ignite™ Machine Learning framework.</p><p>Do you know what Apache Ignite is? It is a horizontally scalable, fault-tolerant, distributed, in-memory computing platform for building real-time applications that can process terabytes of data with in-memory speed [<a href="https://apacheignite.readme.io/docs/what-is-ignite">1</a>].</p><p>De facto, Ignite is a distributed, in-memory database. It’s not like Apache Spark (a distributed ETL framework but not a database with reading/writing on disk and intermediate results in-memory). It’s not like Cassandra (a distributed NoSQL database, keeps indices in memory and data on disk).</p><p>This is the first story in a series of stories about the Apache Ignite ML.</p><ol><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202">Apache Ignite ML: origins and development</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe">Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3">Apache Ignite ML Performance Experiment</a></li></ol><p>In this article, I’m going to describe in detail all the main points of the machine-learning framework that is built at the top of Apache Ignite.</p><p>Let’s go, machine teachers!</p><h3>What Apache Ignite ML is and is not?</h3><p>You can think about the machine-learning (ML) framework as a distributed version of scikit-learn, written in Java.</p><p>First, it’s a distributed machine learning framework, and, as a result, not all classic ML algorithms can be easily and effectively* ported to the distributed universe.</p><blockquote>For example, the SGD algorithm can be easily parallelized or distributed, but DBSCAN, for instance, is not distributed at all.</blockquote><p>Second, it’s not a deep-learning framework, and the support of neural networks (NNs) is limited for both training and inference because it requires a lot of NN ops implementations or importation of TensorFlow or MXNet runtimes.</p><p>Third, it’s not the right choice for exploratory data analysis or data-science experiments. It’s a tool for training and model inference in situations when you know which model or model ensemble you want in production, and you have a choice — to train the model from zero to hero or load a pre-trained model.</p><p>The authors of this ML framework were inspired by ideas that lie in the foundation of scikit-learn, Apache Spark ML, Apache Flink ML, and Apache Mahout. We tried to make the API as simple as possible and easily recognizable for persons who had dealt with the mentioned above frameworks.</p><p>*<em> Algorithm could be ported if it has low complexity (lower than n² in Big O notation for CPU and memory ops), and amount of transferred via network data is not dependent on n (amount of data to train on)</em></p><h3>Motivation (to do yet another framework)</h3><p>Why do people create frameworks? What drives them? Ambition, thirst for knowledge, questions from users, challenges of fate?</p><p><strong>First motivation:</strong> Honestly, I think that, initially, the idea was to create a simple framework at the top of Apache Ignite with models like Linear Regression and Decision Trees to compete with other distributed systems, like Redis or Apache Spark or Oracle, which have their data-science tools. Purely for show.</p><p><strong>Second motivation:</strong> As I remember, some Ignite users asked about making fast predictions in memory by using <strong>pre-trained models</strong>. But all of the models were trained in Python, and, as a result, serialized Python models could be easily used for prediction on Ignite caches.</p><p><strong>Third motivation:</strong> Users much consider the effect that scalability can have on performance. Just like Apache Spark and Apache Mahout, Apache Ignite can be scaled and trained on data partitions.</p><blockquote>With Apache Ignite ML, 1000 nodes with 10000 data partitions are required to train a Decision Tree or NaiveBayes classifiers.</blockquote><p><strong>Fourth motivation:</strong> There are not many useful ML libraries in the JVM world. Unlike with scikit-learn in Python, there is no community-driven gold standard. However, the creation of ML libraries (whether distributed or non distributed) brings new possibilities. Because the Java, Scala, and Kotlin languages use a standard JVM bytecode, libraries that are written in any of the languages can be easily called and reused for data processing.</p><blockquote>As a result, we could reduce network traffic, CPU operations, and volumes of allocated memory if all these actions: data source reading, preprocessing, training, model deployment, and prediction could be made on one platform.</blockquote><blockquote>If data-source reading, preprocessing, training, model deployment, and prediction can be made on one platform, then network traffic, CPU operations, and size of allocated memory can be reduced.</blockquote><p><strong>Fifth motivation:</strong> If you are using a distributed system, probably your data is too large to fit on one server or, in the case of Apache Ignite, within the memory of one server. If you have a lot of data, training on the data might require a good deal of time. If you lose a node, you might lose your calculations and have to restart the training. Apache Ignite Machine Learning is <strong>tolerant of node failures</strong>. Therefore, if a node fails during the learning process, recovery procedures are transparent to you, your training processes aren’t interrupted, and you obtain results relatively quickly, almost the same as if all nodes were working as they should. For detailed information, see Partition Based Dataset [<a href="https://ignite.apache.org/docs/latest/machine-learning/partition-based-dataset">2</a>].</p><p><strong>Sixth motivation.</strong> Last but not least: Be honest, all main <strong>Big Data</strong> tools are written in JVM languages like Java or Scala (not to mention Kafka, Spark, Hadoop, Flink, Ignite, and Cassandra), and all of the languages are developed under the Apache community rules. But, the data-analysis pipeline has a <strong>missing link</strong>. It lacks the ML and data-science tools that integrate well with other JVM Big Data tools. This deficiency caused the Flink and Spark communities to implement its ML frameworks and played a significant role in creating the Apache Ignite ML framework.</p><p>What was the motivation for me, personally, to participate in the Ignite ML project during the past three years and continue my job?</p><p>The main reason was to create competition for the Apache Spark ML framework, which offers a lot of advantages and is widely known but provides limited support for model ensembles, integration with other ML frameworks, and online-learning [<a href="https://medium.com/@zaleslaw/weakness-of-the-apache-spark-ml-library-41e674103591">3</a>]. After a few fruitless attempts to change something within the Apache Spark, I joined the Apache Ignite community, which began the development of the Ignite ML framework by trying to utilize the basics of Apache Mahout at the top of Apache Ignite.</p><h3>What is Apache Ignite in 2020 for me?</h3><p>I’m in since 2017, and I remember the prototype, which had only Linear Regression and distributed matrices. During the next two years, the very friendly community of ML developers (such as Alexey Platonov, Anton Dmitriev, Yury Babak, Artem Malykh, Ravil Galeev, and your humble servant Alexey Zinoviev) did a lot of work together.</p><p>During the past two years, I became first a committer and then a PMC in Apache Ignite (responsible for the ML module and its future).</p><p>Personally, I created and added the following algorithms and ML techniques: SVM, KNN, Logistic Regression, one-hot encoding and other preprocessors, evaluation (including cross-validation, hyperparameter tuning based on random search and genetic algorithms, and metrics calculations), and model loading from Spark.</p><p>As a comitter and PMC, I completed more than two-hundred reviews and PRs, writing the documentation for the last two releases. I also presented talks about Ignite ML at ten events and conferences.</p><p>I hope to continue my work here and hope to involve you, my dear reader, in active use and development of this wonderful ML library.</p><h3>Educational Resources</h3><p>The first most popular question on user-lists is “How to start with Ignite ML? Ignite is quite difficult; ML requires mathematical background. Ignite ML is probably doubly difficult. How to start?”</p><p><strong>First</strong>, dear friends, read the documentation. The official site [<a href="https://ignite.apache.org/docs/latest/machine-learning/machine-learning">4</a>] contains up-to-date documentation on all the main features of the machine learning framework. Everything necessary is described in dry and concise language, and code snippets that you can copy and play with are provided.</p><p><strong>Second</strong>, make this long, long article your guiding star star for learning about the framework. All insights about and reasons for using different architectural solutions are described in this article. You need no other books or articles. Only here. Here.</p><p><strong>Third</strong>, watch videos.</p><p>On my YouTube channel:</p><ol><li>[En, 2019] <a href="https://www.youtube.com/watch?v=3CmnV6IQtTw">Ensembles of ML algorithms &amp; distributed online ML</a></li><li>[Ru, 2019] <a href="https://www.youtube.com/watch?v=etPm3no9eb0&amp;t=819s">Apache Spark and Apache Ignite are building a bright ML future together</a></li><li>[Ru, 2019] <a href="https://www.youtube.com/watch?v=dv4gyJUkDLQ&amp;">Not all ML algorithms go to distributed heaven</a></li><li>[En, 2019] <a href="https://www.youtube.com/watch?v=Tp7-TMlVTaU&amp;t=728s">Distributed ML/DL with Ignite using Spark as data-source</a></li><li>[Ru, 2018] <a href="https://www.youtube.com/watch?v=MMb_0V4cKNs">Nuances of Machine Learning with Apache Ignite ML</a></li><li>[En, 2018] <a href="https://www.youtube.com/watch?v=D0R21TcpbqA">Nuances of Machine Learning with Apache Ignite ML</a></li></ol><p>From Ken Cotrell (GridGain), <a href="https://www.youtube.com/watch?v=eGlmZoBSS8g">Architect’s Guide for Continuous Machine Learning Platforms</a>.</p><p>Fourth, consult the examples folder [<a href="https://github.com/apache/ignite/tree/master/examples/src/main/java/org/apache/ignite/examples/ml">5</a>], the main entry point for experiments and learning. Give special attention to the Titantic Tutorial [<a href="https://github.com/apache/ignite/tree/master/examples/src/main/java/org/apache/ignite/examples/ml/tutorial">6</a>], where the ML pipeline is implemented from CSV parsing to hyperparameter tuning.</p><p>I hope that these resources will be enough for a start, and I hope that the community creates more educational materials in the near future!</p><p>This is the first story in a series of stories about the Apache Ignite ML.</p><ol><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-origins-and-development-d49a19e67202">Apache Ignite ML: origins and development</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-possible-use-cases-racing-with-spark-ml-plans-for-the-future-2145993f36fe">Apache Ignite ML: possible use cases, racing with Spark ML, plans for the future</a></li><li><a href="https://zaleslaw.medium.com/apache-ignite-ml-performance-experiment-4036dc0386a3">Apache Ignite ML Performance Experiment</a></li></ol><h3>Reference list</h3><p>[1] <a href="https://apacheignite.readme.io/docs/what-is-ignite">What is Apache Ignite?</a></p><p>[2] <a href="https://ignite.apache.org/docs/latest/machine-learning/partition-based-dataset">Partition-Based Dataset</a></p><p>[3] <a href="https://medium.com/@zaleslaw/weakness-of-the-apache-spark-ml-library-41e674103591">Weakness of the Apache Spark ML library</a></p><p>[4] <a href="https://ignite.apache.org/docs/latest/machine-learning/machine-learning">Machine Learning in Apache Ignite</a></p><p>[5] <a href="https://github.com/apache/ignite/tree/master/examples/src/main/java/org/apache/ignite/examples/ml">ML examples</a></p><p>[6] <a href="https://github.com/apache/ignite/tree/master/examples/src/main/java/org/apache/ignite/examples/ml/tutorial">Titanic Tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49a19e67202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeNet-5 in Kotlin with TensorFlow]]></title>
            <link>https://zaleslaw.medium.com/lenet-5-in-kotlin-with-tensorflow-b84a8ce7b6a7?source=rss-74b87b849973------2</link>
            <guid isPermaLink="false">https://medium.com/p/b84a8ce7b6a7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Alexey Zinoviev]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 10:45:00 GMT</pubDate>
            <atom:updated>2022-04-21T07:19:00.468Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article, I showed how you can train a linear regression model in Kotlin using Tensorflow API. This time I decided to tackle something a bit more complex, like convolutional networks. In this article I’ll show you how you can train a LeNet model in Kotlin.</p><h4>Article Contents:</h4><ol><li>Introduction</li><li>LeNet-5 layers</li><li>The updated LeNet-4-zaleslaw layers</li><li>First Convolutional layer</li><li>First pooling layer</li><li>Second Convolutional layer and Pooling Layer</li><li>Flatten the 2d input</li><li>Dense layers and the output</li><li>Training: loss function, gradient descent</li><li>Evaluation: meet the Accuracy Queen!</li><li>Conclusion</li><li>References</li></ol><h3>Introduction:</h3><p>The LeNet-5 architecture was published in 1998, more than 20 years ago, but it remains the cornerstone of all Convolutional Networks. Its building blocks (layers and activation functions) are used in more complex architectures to this day.</p><blockquote>“5” — it is very common for the names of neural networks to be derived from the number of <strong><em>convolutional</em> </strong>and <strong><em>fully connected</em></strong> layers that they have.</blockquote><p>The original<a href="http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf"> paper</a> contains an architecture diagram that is widely known and you probably saw it many times before.</p><figure><img alt="LeNet-5 original image" src="https://cdn-images-1.medium.com/max/877/1*lvvWF48t7cyRWqct13eU0w.jpeg" /><figcaption>LeNet-5 original image</figcaption></figure><p>I prefer modern visualization like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*U0NdvNBHe-FVSXgzQjKToA.png" /><figcaption>Image from the article <a href="https://towardsdatascience.com/illustrated-10-cnn-architectures-95d78ace614d">https://towardsdatascience.com/illustrated-10-cnn-architectures-95d78ace614d</a></figcaption></figure><p>It has 2 convolutional (conv) and 3 fully-connected (dense) layers. It also contains avg-pool blocks that are sub-sampling layers.</p><p>This pattern (conv layer + pooling, repeated a few times, plus a few dense layers at the end) became a common pattern in more complex Convolutional Networks and we will see it in the next articles about VGG or AlexNet.</p><h3>LeNet-5 layers:</h3><ol><li>Convolution #1. Input = 32x32x1. Output = 28x28x6 conv2d</li><li>SubSampling #1. Input = 28x28x6. Output = 14x14x6. SubSampling is simply Average Pooling so we use avg_pool</li><li>Convolution #2. Input = 14x14x6. Output = 10x10x16 conv2d</li><li>SubSampling #2. Input = 10x10x16. Output = 5x5x16 avg_pool</li><li>Fully Connected #1. Input = 5x5x16. Output = 120 dense</li><li>Fully Connected #2. Input = 120. Output = 84 dense</li><li>Output 10 dense</li></ol><blockquote>I will use LeNet-5 network to train a model on<a href="http://yann.lecun.com/exdb/mnist/"> MNIST dataset</a> that identifies handwritten digits. My architecture will be a little different from the original architecture to reach the local minimum faster.</blockquote><p>In Keras, this model looks <a href="https://medium.com/@mgazar/lenet-5-in-9-lines-of-code-using-keras-ac99294c8086">very simple</a>, but the Keras API is not available yet on JVM, and this model will be presented as a TensorFlow Graph.</p><p>Time passed and the original model was eroded by doubts. Recently, classical architecture has undergone cosmetic changes, which I applied in my example on Kotlin. Let me list the main ones:</p><ul><li>ReLU as an activation function instead of Tanh or Sigmoid</li><li>MaxPooling instead of AvgPooling</li><li>32 filters instead of 6 in the first conv2d layer and 64 filters instead of 16 in the second conv2d layer to extract more patterns (and because I can train on a cool GPU that was not available to Yann LeCun in 1998).</li><li>one dense layer goes out the door (it will be correct to rename this model to LeNet-4 again)</li></ul><h3><strong>The updated LeNet-4-zaleslaw layers:</strong></h3><ol><li>Convolution #1. Input = 28x28x1. Output = 28x28x32 conv2d</li><li>SubSampling #1. Input = 28x28x32. Output = 14x14x32. SubSampling is simply Max Pooling so we use max_pool</li><li>Convolution #2. Input = 14x14x32 Output = 14x14x64 conv2d</li><li>SubSampling #2. Input = 14x14x64. Output = 7x7x64 max_pool</li><li>Fully Connected #1. Input = 7x7x64. Output = 512dense</li><li>Output 10 dense</li></ol><p>First of all, lets define the hyper-parameters and other useful constants, download the MNIST dataset and define placeholders for our data:</p><pre><em>// Hyper-parameters<br></em>private const val <em>LEARNING_RATE </em>= 0.2f<br>private const val <em>EPOCHS </em>= 10<br>private const val <em>TRAINING_BATCH_SIZE </em>= 500<br><br><em>// Image pre-processing constants<br></em>private const val <em>NUM_LABELS </em>= 10L<br>private const val <em>NUM_CHANNELS </em>= 1L<br>private const val <em>IMAGE_SIZE </em>= 28L<br><br>private const val <em>VALIDATION_SIZE </em>= 0<br>private const val <em>SEED </em>= 12L<br>private const val <em>PADDING_TYPE </em>= &quot;SAME&quot;<br><br><em>// Tensor names<br></em>private const val <em>INPUT_NAME </em>= &quot;input&quot;<br>private const val <em>OUTPUT_NAME </em>= &quot;output&quot;<br>private const val <em>TRAINING_LOSS </em>= &quot;training_loss&quot;</pre><pre>...</pre><pre>val dataset = ...<br><br>Graph().<em>use </em><strong>{ </strong>graph <strong>-&gt;<br>    </strong>val tf = Ops.create(graph)<br><br>    <em>// Define placeholders<br>    </em>val images = tf.withName(<em>INPUT_NAME</em>).placeholder(<br>        Float::class.<em>javaObjectType</em>,<br>        Placeholder.shape(<br>            Shape.make(<br>                -1,<br>                <em>IMAGE_SIZE</em>,<br>                <em>IMAGE_SIZE</em>,<br>                <em>NUM_CHANNELS<br>            </em>)<br>        )<br>    )<br><br>    val labels = tf.placeholder(Float::class.<em>javaObjectType</em>)</pre><p>What are these numbers in the images tensor shape?</p><p>The inputs from MNIST dataset are grayscale images, hence they are in the dimension of [height, width, num_channels] ([28, 28, 1]).</p><p>The first dimension is filled with -1 that stands for unknown amount of images for the input of our CNN.</p><h3>First Convolutional layer</h3><p>The typical conv2d layer declaration consist of following steps:</p><ul><li>matrix weights and bias variables declaration;</li><li>matrix weights and bias initializers declaration;</li><li>matrix weights and bias assignment (filling variables via initializers);</li><li>conv2d layer declaration;</li><li>linear combination of matrix and bias, wrapped into an activation function call.</li></ul><pre>val conv1Weights: Variable&lt;Float&gt; =<br>    tf.variable(Shape.make(5L, 5L, <em>NUM_CHANNELS</em>, 32), Float::class.<em>javaObjectType</em>)</pre><pre>val conv1Biases: Variable&lt;Float&gt; = tf.variable(Shape.make(32), Float::class.<em>javaObjectType</em>)</pre><pre><em>// Generate random data to fill the weight matrix<br></em>val truncatedNormal = tf.random.truncatedNormal(<br>    tf.constant(<em>longArrayOf</em>(5, 5, <em>NUM_CHANNELS</em>, 32)),<br>    Float::class.<em>javaObjectType</em>,<br>    TruncatedNormal.seed(<em>SEED</em>)<br>)</pre><pre>val conv1WeightsInit = tf.assign(<br>       conv1Weights, <br>       tf.math.mul(truncatedNormal,tf.constant(0.1f)))</pre><pre>val conv1BiasesInit = tf.assign(<br>    conv1Biases, tf.zeros(<br>        <em>constArray</em>(<br>            tf,<br>            32<br>        ), Float::class.<em>javaObjectType<br>    </em>)<br>)</pre><pre>val conv1 = tf.nn.conv2d(<br>    images, conv1Weights, <em>mutableListOf</em>(1L, 1L, 1L, 1L),<br>    <em>PADDING_TYPE<br></em>)</pre><pre>val relu1 = tf.nn.relu(tf.nn.biasAdd(conv1, conv1Biases))</pre><p>Ok, but what is conv2d layer doing with input image?</p><p>It just transforms the input applying the special convolution function: takes the piece of input pixels and multiples by kernel (special matrix with small size). The weights of this kernel are parameters of the CNN and can be found by the Gradient Descent or other optimizers like Adam or RMSprop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_vdUIwn3_pjRzlihKxgxw.jpeg" /></figure><blockquote>The correct shape calculation is the hardest thing when you are working with the TensorFlow Graph. I’ll try to give some recommendation and common practices here.</blockquote><p>For any 2D convolution layer, assuming it receives input <strong><em>X</em></strong> with dimension of: <strong><em>X</em></strong> — [batch_size, input_height, input_width, input_depth].</p><p>Then the weights <strong>w </strong>of this convolution layer would have a dimension of: <strong><em>w </em></strong>— [filter_height, filter_width, input_depth, output_depth].</p><p>This convolution layer outputs a <strong><em>y </em></strong>in dimension of: <strong><em>y </em></strong>— [batch_size, output_height, output_width, output_depth].</p><p>The input_depth for this layer is equal to 1 (amount of channels), the output_depth is 32 (amount of wished filters to extract the low-level patterns like lines or pieces of primitive curves).</p><p>Need to describe a few numbers in this code snippet:</p><ul><li>the [5;5] is a kernel size (or filter size);</li><li>the <em>mutableListOf</em>(1L, 1L, 1L, 1L) is just strides (the rate at which the kernel passes over the input image. A stride of 2 moves the kernel in 2-pixel increments).</li></ul><h3>First pooling layer</h3><blockquote>Once a feature has been detected, its exact location becomes less important. Only its approximate position relative to other features is relevant. For example, once we know that the input image contains the endpoint of a roughly horizontal segment in the upper left area, a corner in the upper right area, and the endpoint of a roughly ver tical segment in the lower portion of the image, we can tell the input image is a 7. A simple way to reduce the precision with which the position of distinc tive features are encoded in a feature map is to reduce the spatial resolution of the feature map. This can be achieved with a socalled subsampling layers which performs a local averaging and a subsampling, reducing the resolution of the feature map, and reducing the sensitivity of the output to shifts and distortions. [1].</blockquote><p>I prefer MaxPooling to the original AvgPooling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m89YSbipkxDvZlzcMAceFQ.jpeg" /></figure><p>The declaration is very simple:</p><pre>val pool1 = tf.nn.maxPool(<br>    relu1,<br>    tf.constant(<em>intArrayOf</em>(1, 2, 2, 1)),<br>    tf.constant(<em>intArrayOf</em>(1, 2, 2, 1)),<br>    <em>PADDING_TYPE<br></em>)</pre><p>Two intArrays are just packed kernel and stride sizes for each dimension of the input tensor. In reality only middle two (kernel[2]; kernel[3]; strides[2]; strides[3]) play a significant role in TensorFlow CNN training. The values at the edges of the array generally remain filled units.</p><h3>Second Convolutional layer and Pooling Layer</h3><p>This layer is a copy of the previous with a changed amount of input and output filters. The input_depth is 32 due to 32 filters from the first conv2d layer.</p><p>The 64 is a new value for filters in the second conv2d layer (could be increased if you wish).</p><pre>val truncatedNormal2 = tf.random.truncatedNormal(<br>    tf.constant(<em>longArrayOf</em>(5, 5, 32, 64)),<br>    Float::class.<em>javaObjectType</em>,<br>    TruncatedNormal.seed(<em>SEED</em>)<br>)<br><br>val conv2Weights: Variable&lt;Float&gt; =<br>    tf.variable(Shape.make(5, 5, 32, 64), Float::class.<em>javaObjectType</em>)<br><br>val conv2WeightsInit = tf.assign(conv2Weights, tf.math.mul(truncatedNormal2, tf.constant(0.1f)))<br><br>val conv2 = tf.nn.conv2d(<br>    pool1, conv2Weights, <em>mutableListOf</em>(1L, 1L, 1L, 1L),<br>    <em>PADDING_TYPE<br></em>)<br><br>val conv2Biases: Variable&lt;Float&gt; = tf.variable(Shape.make(64), Float::class.<em>javaObjectType</em>)<br><br>val conv2BiasesInit = tf.assign(<br>    conv2Biases, tf.zeros(<br>        <em>constArray</em>(<br>            tf,<br>            64<br>        ), Float::class.<em>javaObjectType<br>    </em>)<br>)<br><br>val relu2 = tf.nn.relu(tf.nn.biasAdd(conv2, conv2Biases))</pre><p>The second MaxPooling layer could be added in the same manner as a previous one.</p><pre>val pool2 = tf.nn.maxPool(<br>    relu2,<br>    tf.constant(<em>intArrayOf</em>(1, 2, 2, 1)),<br>    tf.constant(<em>intArrayOf</em>(1, 2, 2, 1)),<br>    <em>PADDING_TYPE<br></em>)</pre><h3>Flatten the 2d input</h3><p>The next step includes the flattenization of the squared input to the plain vector with the size 3136 (7 * 7 * 64 — shape of the preivous max pooling layer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*_Cb1dzBhciwRi9y1-J6qjQ.png" /></figure><p>The flatten operation is just a reshape along two axis.</p><pre>val slice: Slice&lt;Int&gt; = tf.slice(<br>    tf.shape(pool2),<br>    tf.constant(<em>intArrayOf</em>(0)),<br>    tf.constant(<em>intArrayOf</em>(1))<br>)<br><br>val mutableListOf: MutableList&lt;Operand&lt;Int&gt;&gt; = <em>mutableListOf</em>(slice, tf.constant(<em>intArrayOf</em>(-1)))<br><br>val flatten = tf.reshape(<br>    pool2,<br>    tf.concat(<br>        mutableListOf,<br>        tf.constant(0)<br>    )<br>)</pre><p>The result of applying the flatten operand is the input for the dense layer.</p><h3>Dense layers and the output</h3><p>It’s time for good old fully-connected layers.</p><blockquote>In reality, the combination of Flatten operand and first dense layer is not exactly the typical fully-connected layer (in the [1] it is described as a convolutional layer with kernel 1x1).</blockquote><p>Each unit is connected to a 5x5 neighborhood on all 64 features maps (filters).</p><p>The dense layer includes:</p><ul><li>weight and bias variable declaration;</li><li>weight and bias initialization;</li><li>weight and bias assignment;</li><li>linear combination of matrix and bias, wrapped to activation function call.</li></ul><p>Similar to conv2d layer, I agree, but it operates with vectors not matrices and has no special operation to apply to the input like convolution function.</p><pre>val truncatedNormal3 = tf.random.truncatedNormal(<br>    tf.constant(<em>longArrayOf</em>(<em>IMAGE_SIZE </em>* <em>IMAGE_SIZE </em>* 4, 512)),<br>    Float::class.<em>javaObjectType</em>,<br>    TruncatedNormal.seed(<em>SEED</em>)<br>)<br><br>val fc1Weights: Variable&lt;Float&gt; =<br>    tf.variable(Shape.make(<em>IMAGE_SIZE </em>* <em>IMAGE_SIZE </em>* 4, 512), Float::class.<em>javaObjectType</em>)<br><br>val fc1WeightsInit = tf.assign(fc1Weights, tf.math.mul(truncatedNormal3, tf.constant(0.1f)))<br><br>val fc1Biases: Variable&lt;Float&gt; = tf.variable(Shape.make(512), Float::class.<em>javaObjectType</em>)<br><br>val fc1BiasesInit = tf.assign(fc1Biases, tf.fill(tf.constant(<em>intArrayOf</em>(512)), tf.constant(0.1f)))<br><br>val relu3 = tf.nn.relu(tf.math.add(tf.linalg.matMul(flatten, fc1Weights), fc1Biases))</pre><p>The second dense layer forms the outputs for 10 classes in multi-classification task:</p><pre>val truncatedNormal4 = tf.random.truncatedNormal(<br>    tf.constant(<em>longArrayOf</em>(512, <em>NUM_LABELS</em>)),<br>    Float::class.<em>javaObjectType</em>,<br>    TruncatedNormal.seed(<em>SEED</em>)<br>)<br><br>val fc2Weights: Variable&lt;Float&gt; =<br>    tf.variable(Shape.make(512, <em>NUM_LABELS</em>), Float::class.<em>javaObjectType</em>)<br><br>val fc2WeightsInit = tf.assign(fc2Weights, tf.math.mul(truncatedNormal4, tf.constant(0.1f)))<br><br>val fc2Biases: Variable&lt;Float&gt; = tf.variable(Shape.make(<em>NUM_LABELS</em>), Float::class.<em>javaObjectType</em>)<br><br>val fc2BiasesInit =<br>    tf.assign(fc2Biases, tf.fill(tf.constant(<em>intArrayOf</em>(<em>NUM_LABELS</em>.toInt())), tf.constant(0.1f)))<br><br>val logits = tf.math.add(tf.linalg.matMul(relu3, fc2Weights), fc2Biases)</pre><p>There is no activation function due to special metric that will be used later (it includes the last step with sigmoid activation).</p><h3>Training: loss function, gradient descent</h3><p>To calculate the loss function value I decided to use the special function <em>softmaxCrossEntropyWithLogits </em>on each batch and average it across the whole dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wM2hLqEmylkmh7rConpfpA.png" /></figure><pre>val batchLoss = tf.nn.softmaxCrossEntropyWithLogits(logits, labels)<br><br>val loss = tf.withName(<em>TRAINING_LOSS</em>).math.mean(batchLoss.loss(), tf.constant(0))</pre><p>After that, we can set up the Gradient Descent manually:</p><ul><li>define learning rate;</li><li>define gradient variables to accumulate gradients;</li><li>initializer variables via initializers.</li></ul><pre><em>// Define gradients<br></em>val learningRate = tf.constant(<em>LEARNING_RATE</em>)<br><br>val variables = <em>listOf</em>(conv1Weights, conv1Biases, conv2Weights,   conv2Biases, fc1Weights, fc1Biases, fc2Weights, fc2Biases)<br><br>val gradients = tf.gradients(loss, variables)<br><em><br></em>val variablesGD = variables.<em>mapIndexed </em><strong>{ </strong>index, variable <strong>-&gt;<br>    </strong>tf.train.applyGradientDescent(variable, learningRate, gradients.dy(index))<br><strong>}<br><br></strong>val variablesInit = <em>listOf</em>(conv1WeightsInit, conv1BiasesInit, conv2WeightsInit, conv2BiasesInit, fc1WeightsInit, fc1BiasesInit, fc2WeightsInit, fc2BiasesInit)</pre><pre>fun &lt;T, E&gt; T.applyF(f: T.(E) -&gt; T, ls: Iterable&lt;E&gt;) =   ls.<em>fold</em>(this,f)</pre><pre>Session(graph).<em>use </em><strong>{ </strong>session <strong>-&gt;<br></strong><br>    <em>// Initialize graph variables<br>    </em>session.runner()<br>        .<em>applyF</em>(Session.Runner::addTarget, variablesInit)<br>        .run()</pre><p>When all variables are ready to be recalculated by Backward Propagation, we run the main training loop for N epochs with yet once more internal cycle by batches during each epoch.</p><pre><em>// Train the graph<br></em>for (i in 1..<em>EPOCHS</em>) {<br>    val batchIter: ImageDataset.ImageBatchIterator = dataset.trainingBatchIterator(<br>        <em>TRAINING_BATCH_SIZE<br>    </em>)<br><br>    while (batchIter.hasNext()) {<br>        val batch: ImageBatch = batchIter.next()<br>        Tensor.create(<br>            <em>longArrayOf</em>(<br>                batch.size().toLong(),<br>                <em>IMAGE_SIZE</em>,<br>                <em>IMAGE_SIZE</em>,<br>                <em>NUM_CHANNELS<br>            </em>),<br>            batch.images()<br>        ).<em>use </em><strong>{ </strong>batchImages <strong>-&gt;<br>            </strong>Tensor.create(<em>longArrayOf</em>(batch.size().toLong(), 10), batch.labels()).<em>use </em><strong>{ </strong>batchLabels <strong>-&gt;</strong></pre><pre><strong>                </strong>val lossValue = session.runner()<br>                    .<em>applyF</em>(Session.Runner::addTarget, variablesGD)<br>                    .feed(images.asOutput(), batchImages)<br>                    .feed(labels.asOutput(), batchLabels)<br>                    .fetch(<em>TRAINING_LOSS</em>)<br>                    .run()[0].floatValue()</pre><pre>                <em>println</em>(&quot;epochs: $i lossValue: $lossValue&quot;)<br>            <strong>}<br>        }<br>    </strong>}<br>}</pre><h3>Evaluation: meet the Accuracy Queen!</h3><p>Not much of a use to train the model without metric calculation on test dataset.</p><p>Let’s form the evaluation TensorFlow graph with Accuracy Metric to evaluate the trained model on the test part of MNIST dataset.</p><pre>val prediction = tf.withName(<em>OUTPUT_NAME</em>).nn.softmax(logits)</pre><pre>val predicted: Operand&lt;Long&gt; = tf.math.argMax(<br>    prediction, tf.constant(1))</pre><pre>val expected: Operand&lt;Long&gt; = tf.math.argMax(labels, tf.constant(1))<br><br><em>// Define multi-classification metric<br></em>val accuracy = tf.math.mean(<br>    tf.dtypes.cast(<br>        tf.math.equal(predicted, expected),<br>        Float::class.<em>javaObjectType<br>    </em>), <em>constArray</em>(tf, 0)<br>)</pre><p>Here, we should apply the Softmax activation function to the logits node, because the Softmax could give us the probabilities for image to be image of the given class (for each class).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*aCH15R_IGuWafhYWdtV05g.png" /></figure><p>At the end we run our test data through the model’s tensors without gradient calculations to predict on test data and compare with ground truths.</p><pre>val testBatch: ImageBatch = dataset.testBatch()<br>Tensor.create(<br>    <em>longArrayOf</em>(<br>        testBatch.size().toLong(),<br>        <em>IMAGE_SIZE</em>,<br>        <em>IMAGE_SIZE</em>,<br>        <em>NUM_CHANNELS<br>    </em>),<br>    testBatch.images()<br>).<em>use </em><strong>{ </strong>testImages <strong>-&gt;<br>    </strong>Tensor.create(testBatch.shape(10), testBatch.labels()).<em>use </em><strong>{ </strong>testLabels <strong>-&gt;</strong></pre><pre><strong>        </strong>session.runner()<br>            .fetch(accuracy)<br>            .feed(images.asOutput(), testImages)<br>            .feed(labels.asOutput(), testLabels)<br>            .run()[0].<em>use </em><strong>{ <br>               </strong>value <strong>-&gt; </strong><em>println</em>(&quot;Accuracy: &quot; + value.floatValue()) <br>             <strong>}<br>    }<br>}</strong></pre><h3>Conclusion</h3><p>Happy to see you at the end of this article. The full Kotlin code, for this example, is available here [<a href="https://github.com/zaleslaw/KotlinDeepLearningTutorial/blob/master/tensorflow1/src/main/kotlin/training/mnist/lenet/LeNetMnistWithoutRefactoring.kt">2</a>]. The Java version of this code is available here [<a href="https://github.com/zaleslaw/KotlinDeepLearningTutorial/blob/master/tensorflow1/src/main/java/LeNetMnistJava.java">3</a>].</p><p>Today, we reviewed the classic model of handwriting recognition. Of course, to distinguish moving cats from standing 3D dogs, it is not suitable in this form. But the basic concepts and pieces of a programmed computational graph presented in this article may well be reused to write more complex models in Kotlin or Java.</p><p>P.S. I’m sure that without a deep understanding of TensorFlow computational graph and manual shape calculation, no matter how good you are with Keras, it would prove challenging to create something really new and ready for production.</p><h3>References</h3><ol><li><a href="http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf">Yann LeCun’s original paper</a>;</li><li><a href="https://github.com/zaleslaw/KotlinDeepLearningTutorial/blob/master/tensorflow1/src/main/kotlin/training/mnist/lenet/LeNetMnistWithoutRefactoring.kt">Kotlin LeNet-5 code</a>;</li><li><a href="https://github.com/zaleslaw/KotlinDeepLearningTutorial/blob/master/tensorflow1/src/main/java/LeNetMnistJava.java">Java LeNet-5 code</a>;</li><li><a href="https://towardsdatascience.com/illustrated-10-cnn-architectures-95d78ace614d">LeNet-5 architecture diagram</a>;</li><li><a href="https://github.com/zaleslaw/KotlinDeepLearningTutorial">Kotlin Deep Learning Tutorial (DL4j, TensorFlow)</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b84a8ce7b6a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>