<?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 Eugene Stsefankou on Medium]]></title>
        <description><![CDATA[Stories by Eugene Stsefankou on Medium]]></description>
        <link>https://medium.com/@stefjen07?source=rss-12391c476fb7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DivvSuVFpb9FhSCEOkUfyA.jpeg</url>
            <title>Stories by Eugene Stsefankou on Medium</title>
            <link>https://medium.com/@stefjen07?source=rss-12391c476fb7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:25:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefjen07/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[Visualizing Rotations of 4D Objects in Swift]]></title>
            <link>https://medium.com/better-programming/visualizing-rotations-of-4d-objects-in-swift-a83f4461c7ea?source=rss-12391c476fb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a83f4461c7ea</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[scenekit]]></category>
            <category><![CDATA[4d]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Eugene Stsefankou]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 09:50:45 GMT</pubDate>
            <atom:updated>2023-02-22T11:29:46.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>Projecting 4D objects on 3D and rendering them in Swift playground</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVS_Pva_X0_JHM4aGfcS0Q.jpeg" /><figcaption>120-cell and 600-cell rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><h3>Introduction</h3><p>This article is about my submission for Apple Swift Student Challenge 2021. By the way, this submission made me one of 350 winners of the competition and I really recommend you take part in it if you are eligible. During the New Year’s holidays, I’ve seen a lot of videos about 4D rendering on YouTube. The idea of it got me and I started diving deeper into it.</p><p>First, we have to find out what is 4D space. So, as we can see in the name, it consists of 4 dimensions. The first three are X, Y, Z, this is usual for us. And the fourth is W.</p><p>There are several implementations of 4D rendering in our world. In the videos I watched, people made 4D games with objects disappearing while changing position on W. This 4D rendering type uses cross-sections of 4D objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Y3ug8Avh6eo8_vbRHJF9zQ.png" /><figcaption>Cross-sections of 3D object. Image from <a href="http://eusebeia.dyndns.org/4d/vis/04-xsec">eusebeia.dyndns.org</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*xEkl-gutJ0dY_NJNRw34yA.png" /><figcaption>Cross-sections of 4D object. Image from <a href="http://eusebeia.dyndns.org/4d/vis/04-xsec">eusebeia.dyndns.org</a></figcaption></figure><p>In my visualization, I use projection of 4D space on the 3D space. There are 2 common types of these projections: orthographic and perspective. For example, our eyes use perspective projection, and it suits well for our use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCZZrO3evKmsVQeLkG2otg.png" /><figcaption>Various projections and how they are produced. Image from <a href="https://en.wikipedia.org/wiki/3D_projection#/media/File:Various_projections_of_cube_above_plane.svg">wikipedia.org</a></figcaption></figure><h3>Implementation in Swift</h3><p>For a quick start, you can copy the code from <a href="https://github.com/stefjen07/WWDC21-4DVisualization">my GitHub repository</a> with the Swift playground I created.</p><p>We will use SceneKit for rendering because we decided to implement rendering by projecting 4D space on the 3D space. So, our aim is to render 4D vertices and edges in the projected 3D coordinates.</p><p>We will use the golden ratio in our computations (the coordinates of objects depend on that), so we should create a constant for that. Also, we must give each axis a number and define the desired field of view. The render mode is used to control the objects displayed (whether to display vertices and edges).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f78b525375013676314e9506aa225b/href">https://medium.com/media/d3f78b525375013676314e9506aa225b/href</a></iframe><p>My project uses some basic Double extensions for rounding values, converting Bool to Double and getting a square of a number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f2c7e206c3714f3df32ec9f2f57b78c/href">https://medium.com/media/8f2c7e206c3714f3df32ec9f2f57b78c/href</a></iframe><p>We will work with coordinates, and we have to make a structure for storing them — Vector.</p><h3>Working with vectors</h3><p>I wanted 3 types of vectors: 2D, 3D, and 4D. I decided to use one structure for all of them (for convenience).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6175e107a7c2af2ca611a4f045479c8f/href">https://medium.com/media/6175e107a7c2af2ca611a4f045479c8f/href</a></iframe><p>We use SceneKit, and it has its own vectors, so I had to create a function for converting my vectors to SceneKit ones.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34d5be860df11cf37d11db5774eed616/href">https://medium.com/media/34d5be860df11cf37d11db5774eed616/href</a></iframe><p>Then I created a function that does a simple mathematical operation — <a href="https://en.wikipedia.org/wiki/Scalar_multiplication">scalar multiplication</a>. We will need it later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/663da978d958c041d8b9d52a06d12ed6/href">https://medium.com/media/663da978d958c041d8b9d52a06d12ed6/href</a></iframe><p>Also, we need a method for calculating Euclidean distance and a method for checking the parity of a permutation. We will use the first for generating edges and the second for finding even permutations of the vector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b55ef51d8b8610ccc82618b0a27726ab/href">https://medium.com/media/b55ef51d8b8610ccc82618b0a27726ab/href</a></iframe><p>Also, we need a method for finding unique vectors in the vector array. We will use it to remove duplicate vertices of the object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52a9ed62e3ece829b204450f32d9e89a/href">https://medium.com/media/52a9ed62e3ece829b204450f32d9e89a/href</a></iframe><h3>Working with matrices</h3><p>Projecting 4D coordinates on 3D space and rotating objects requires working with matrices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80cdeb93b6b994cd7bd5041645f1028b/href">https://medium.com/media/80cdeb93b6b994cd7bd5041645f1028b/href</a></iframe><p>We must provide a constructor for creating a zero matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d6bbc63e3344dca1ff89e4c9fdb01b7/href">https://medium.com/media/6d6bbc63e3344dca1ff89e4c9fdb01b7/href</a></iframe><p>Also, we have to make a map function. Its behavior will be similar to the default map function (for arrays) of Swift. But it also will provide our closure with the coordinates of the current element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/430fb719493b0d5ee1110d7be2e3b2f7/href">https://medium.com/media/430fb719493b0d5ee1110d7be2e3b2f7/href</a></iframe><p>4D object&#39;s double rotations need matrix multiplication and some matrix generators (<a href="https://en.wikipedia.org/wiki/Identity_matrix">identity matrix</a>, <a href="https://en.wikipedia.org/wiki/Rotation_matrix">rotation matrix</a>, projection matrix, and perspective matrix).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7212311c3360b8b3c2be11304e62dd3e/href">https://medium.com/media/7212311c3360b8b3c2be11304e62dd3e/href</a></iframe><h3><strong>4D Edges</strong></h3><p>Objects consist of edges and vertices. Edges connect two vertices. We must create a struct for it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b1abb6c8cfd3fe87a91f502cc119f87/href">https://medium.com/media/3b1abb6c8cfd3fe87a91f502cc119f87/href</a></iframe><p>Also, we must create an edge group generator that will try every possible combination of vertices to make an edge and if this edge has the distance we need, it will save it to the result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5956999c56d4175bb2041a2e264806ee/href">https://medium.com/media/5956999c56d4175bb2041a2e264806ee/href</a></iframe><h3>4D Object structure</h3><p>We must create a class for objects to have all the necessary data (object’s name, vertices, edges, and camera distance). Also, I created a simple function for generating an object’s description.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05418380d1708cf483354f3b5b267401/href">https://medium.com/media/05418380d1708cf483354f3b5b267401/href</a></iframe><h3>4D View</h3><p>As I mentioned before, we will use SceneKit to render the projected 4D objects in 3D space. So, we must make a subclass of SCNView. It is dedicated to projecting and drawing the vertices on the screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a609b7c5c80ae7899a79075c4eb2402/href">https://medium.com/media/3a609b7c5c80ae7899a79075c4eb2402/href</a></iframe><p>We must write functions for adding and removing the vertices of the object. It will be called when the object is being switched.</p><p>The function for adding vertices just creates SceneKit objects (in our case nodes with SCNSphere geometry), gives them a color, and adds them to the scene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d02e8e1e2c1c4f4195aac87b792eb02/href">https://medium.com/media/6d02e8e1e2c1c4f4195aac87b792eb02/href</a></iframe><p>The function for removing vertices just removes nodes from both the container and the scene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43c3dff6f6c05ea22a2b5f4893d6f13a/href">https://medium.com/media/43c3dff6f6c05ea22a2b5f4893d6f13a/href</a></iframe><p>One of the most important fragments of code is a rotation of the object. It receives the object and the axes&#39; speeds, rotates the object, and projects it on the axes.</p><p>We make a rotation by multiplying the point matrix (coordinate vector as a matrix) by the rotation matrix (for each axis&#39;s pair). After rotating the points, we apply the perspective projection by multiplying the point matrix by the projection matrix according to the preferred FOV (field of view) and w-coordinate.</p><p>In the end, we scale projected points by some constant to make an object bigger.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3345d604073584845cc07ae3ce7be41a/href">https://medium.com/media/3345d604073584845cc07ae3ce7be41a/href</a></iframe><p>After that, we must create a function for drawing the object so we could update the frame according to the updates on the objects’ coordinates. It applies a rotation by calling a function, we wrote before, creates line geometry for edges, and updates nodes’ positions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28ba3ea21cffc454fa685dd7dd921a79/href">https://medium.com/media/28ba3ea21cffc454fa685dd7dd921a79/href</a></iframe><p>Our frame updating will be triggered by a timer. The update interval is 1/24 ≈ 0.04167 seconds. 24 is our frame rate, it is common for cinematic videos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe6343883a297ad05a16794c3f9a5ff/href">https://medium.com/media/dfe6343883a297ad05a16794c3f9a5ff/href</a></iframe><p>We will use keyDown and keyUp functions for user interaction. Some keys will be dedicated to changing the speed, key C (code 0x08) will be used for resetting the current rotation and key N (code 45) will switch to the next object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddddda4fd6015797336a6fdcfa33b1c5/href">https://medium.com/media/ddddda4fd6015797336a6fdcfa33b1c5/href</a></iframe><p>The keyUp function is used to reduce the speed when the key is not pressed anymore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86ee82d60e7480f3ae379d9427852613/href">https://medium.com/media/86ee82d60e7480f3ae379d9427852613/href</a></iframe><p>The mouseDown function will be used for selecting and deselecting the vertices. The information for the current object will be printed to the console output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa7d878ffa86cd67b47e13d80a317ec/href">https://medium.com/media/6aa7d878ffa86cd67b47e13d80a317ec/href</a></iframe><h3>Vertices generation</h3><p>Vertices in all objects (except 5-cell) are based on permutations and sign combinations. For example, tesseract coordinates are (±1, ±1, ±1, ±1). So, we use sign combinations to find all the vertices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93add1f1fbe3a89e4291f5728375f47/href">https://medium.com/media/f93add1f1fbe3a89e4291f5728375f47/href</a></iframe><p>The permutations are used in every object except 5-cell. So it&#39;s a must-have function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76d89cfc12fec960b0641d8f6998dc1a/href">https://medium.com/media/76d89cfc12fec960b0641d8f6998dc1a/href</a></iframe><p>The vertices of 120-cell and 600-cell are based on even permutations. We must implement a filter for finding only even permutations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc1d7e4fedef44bc19ae22d71ad36f42/href">https://medium.com/media/dc1d7e4fedef44bc19ae22d71ad36f42/href</a></iframe><h3>Objects</h3><p>In my implementation, you can see all six convex regular 4-polytopes.</p><h4>Tesseract</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*UcGNlSaNJ5_yLJscT-ny2g.png" /><figcaption>Tesseract rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93f336e84c3d4c147ca2879b25f27c3/href">https://medium.com/media/f93f336e84c3d4c147ca2879b25f27c3/href</a></iframe><h4>5-cell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*n4-ZNIvR_jrdfNkpQ4embw.png" /><figcaption>5-cell rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa0ff61e7979138f80299066ad722b84/href">https://medium.com/media/aa0ff61e7979138f80299066ad722b84/href</a></iframe><h4>16-cell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*5ZOBElUVFi2QEVnzj4HhAg.png" /><figcaption>16-cell rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b58ad0308b0300c0e6738164cdbdc508/href">https://medium.com/media/b58ad0308b0300c0e6738164cdbdc508/href</a></iframe><h4>24-cell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FnLuKewDSHNnvYaZE5nHJw.png" /><figcaption>24-cell rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ee9e1ab60587b9c5e81224b9dfeed01/href">https://medium.com/media/7ee9e1ab60587b9c5e81224b9dfeed01/href</a></iframe><h4>120-cell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*5DdP_0O-ZaSQqKDyr5C00w.png" /><figcaption>120-cell rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef9da6a230b3fd1dcffd50a85803a9e9/href">https://medium.com/media/ef9da6a230b3fd1dcffd50a85803a9e9/href</a></iframe><h4>600-cell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*YXYKCg6zc-wui5pk1CSeuQ.png" /><figcaption>600-cell rendered in Swift. Image by Yauheni Stsefankou</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0b54160229ad8f7ea2397cde53e9d5/href">https://medium.com/media/ba0b54160229ad8f7ea2397cde53e9d5/href</a></iframe><h3>Conclusion</h3><p>We have created a visualization for double rotations of 4D objects in Swift. We applied such frameworks as SceneKit for rendering and some math concepts for generating and rotating the objects. Here is the link to a git repository with all the source code: <a href="https://github.com/stefjen07/WWDC21-4DVisualization">https://github.com/stefjen07/WWDC21-4DVisualization</a>.</p><p>If you have any tips, or you found any mistakes in this article, please leave your feedback. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a83f4461c7ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/visualizing-rotations-of-4d-objects-in-swift-a83f4461c7ea">Visualizing Rotations of 4D Objects in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Neural Network in Swift using Metal shaders]]></title>
            <link>https://medium.com/data-science/building-neural-network-in-swift-using-metal-shaders-aa1fd75d715b?source=rss-12391c476fb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1fd75d715b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Eugene Stsefankou]]></dc:creator>
            <pubDate>Sat, 05 Jun 2021 17:52:43 GMT</pubDate>
            <atom:updated>2021-06-05T17:52:43.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Metal Performance Shaders framework in building Neural Network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eWmKMGwl6oqe6o53" /><figcaption>Photo by <a href="https://unsplash.com/@krishna2803?utm_source=medium&amp;utm_medium=referral">Krishna Pandey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In <a href="https://towardsdatascience.com/neural-networks-on-swift-ba181dcdfde5">the previous article</a>, I implemented neural network framework from scratch. It supports CPU multi-threading, but doesn’t support GPU computations. In this article I’ll implement similar framework, but with use of <em>Metal Performance Shaders</em>. <a href="https://developer.apple.com/wwdc19/614">WWDC19 session 614</a> inspired me to write this article.</p><blockquote>The Metal Performance Shaders framework contains a collection of highly optimized compute and graphics shaders that are designed to integrate easily and efficiently into your Metal app. These data-parallel primitives are specially tuned to take advantage of the unique hardware characteristics of each GPU family to ensure optimal performance.</blockquote><p><em>Metal Performance Shaders</em> provide high-level programming of neural networks with much flexibility.</p><h3>Neural Network Data Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*g-Y1-7BUW6ChsNhGSY5u9Q.png" /><figcaption>Data model. Image by Yauheni Stsefankou.</figcaption></figure><p>Our neural network model consists of layers, graphs, and parameters of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*B5EkZVkQeobgY_DVc-EEtg.png" /><figcaption>Parameters of neural network. Image by Yauheni Stsefankou.</figcaption></figure><p>Parameters are a batch size and a number of epochs per training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*NLjOYKUFlQ1GUruSbqmU8w.png" /><figcaption>Graphs of neural network. Image by Yauheni Stsefankou.</figcaption></figure><p>There are two graphs in our model: training graph and inference graph. Both have the same weights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a892571e35d600c2c07bd4948820eb0/href">https://medium.com/media/1a892571e35d600c2c07bd4948820eb0/href</a></iframe><p>Our neural network framework will have a lot of layers, such as Dense, Dropout, Flatten, Convolutional 2D, Pooling Max and Average, Sigmoid and ReLU activations.</p><p>For convenience, you can find all the code in <a href="https://github.com/stefjen07/ShadersNeuralNetwork">my GitHub repository</a>.</p><h3>Non-trainable layers</h3><p>Implementation of these layers is so simple, cause they don’t have weights. They constantly transform input without changing the strategy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2840f51cb2ca30d970eb5323e83cd628/href">https://medium.com/media/2840f51cb2ca30d970eb5323e83cd628/href</a></iframe><p>Basic layer class is empty because all the layers have nothing in common.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c3edf2f0afba89237a62af29db09737/href">https://medium.com/media/9c3edf2f0afba89237a62af29db09737/href</a></iframe><p>Pooling layer has padding and pooling modes, a filter size and a stride.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5c49ff68a3293a083f62cd5b618cbca/href">https://medium.com/media/f5c49ff68a3293a083f62cd5b618cbca/href</a></iframe><p>Dropout layer is very simple, and it has only a probability of input’s values keeping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6ae306451faf708f9f2c70e448da1d6/href">https://medium.com/media/d6ae306451faf708f9f2c70e448da1d6/href</a></iframe><p>Flatten layer is also very simple. We must provide a width of flattening (input size).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07a2d69fd4d883f4d19d56bb08a53d95/href">https://medium.com/media/07a2d69fd4d883f4d19d56bb08a53d95/href</a></iframe><p>Activation layers don’t require storing any data, so they’ll be as empty as basic Layer class.</p><p>There are only 2 non-implemented layers left: Dense and Convolutional 2D. For them we need to implement Data Source class. It comprises neurons’ weights and biases and layer parameters.</p><h3>Data Source for Convolution and Dense layers</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a3671349574ae5ab9e5052d79102236/href">https://medium.com/media/6a3671349574ae5ab9e5052d79102236/href</a></iframe><p>We have to store weights, biases and their velocities and momentums in the specific Metal vectors. Also, we keep pointers on these vectors and optimizer’s parameters.</p><p>MPSCNNConvolutionDataSource protocol is forcing us to implement some functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06da432ceebe59fc1f33a289d774a044/href">https://medium.com/media/06da432ceebe59fc1f33a289d774a044/href</a></iframe><p>The first one returns data type of our weights. We’ll keep our weights’ values as 32-bit float.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa430fa56dcd1bf8c3191f7db09ab4f/href">https://medium.com/media/4fa430fa56dcd1bf8c3191f7db09ab4f/href</a></iframe><p>The second one return the convolution descriptor, which was created on class initialization with given parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed9eceb8441d4118ecfba28700190dbc/href">https://medium.com/media/ed9eceb8441d4118ecfba28700190dbc/href</a></iframe><p>These return pointers to vectors with layer weights and biases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd80a1d3a71132f42dff38033e141e0a/href">https://medium.com/media/cd80a1d3a71132f42dff38033e141e0a/href</a></iframe><p>This method loads weights and biases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3e01f0395ee8557242ce63087a64fac/href">https://medium.com/media/e3e01f0395ee8557242ce63087a64fac/href</a></iframe><p>These two functions are plugs because they are unnecessary for our tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cda5e0bba3a6be7e7faeeb377bbd64a/href">https://medium.com/media/2cda5e0bba3a6be7e7faeeb377bbd64a/href</a></iframe><p>And this is the last function in ConvDataSource class. It returns the label of the data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2cf5735ab1117486633649bf8dd465/href">https://medium.com/media/eb2cf5735ab1117486633649bf8dd465/href</a></iframe><p>Weights for Convolution and Dense layers are initialized using common convolution parameters such as kernel size, number of input channels and filters, stride and learning rate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/363a7516a9f052d394bc3ae2b977f4fb/href">https://medium.com/media/363a7516a9f052d394bc3ae2b977f4fb/href</a></iframe><p>The fundamental things here are optimizer and convolution descriptor. They store our main parameters of layer and update weights while training with them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8177282c8fd8981a25a5e7852a29040f/href">https://medium.com/media/8177282c8fd8981a25a5e7852a29040f/href</a></iframe><p>Before initialization weights and biases vectors, we must compute length of them and create descriptors for them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3a64037ce77c21dca87a65a65929206/href">https://medium.com/media/b3a64037ce77c21dca87a65a65929206/href</a></iframe><p>And now, when we have descriptors, we can initialize vectors for weights, its velocity and momentum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfc1847987a43129a5d85329e09db270/href">https://medium.com/media/dfc1847987a43129a5d85329e09db270/href</a></iframe><p>Then, we do the same procedure with biases vectors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eafaa074029162f7d5995fa04f058d3/href">https://medium.com/media/1eafaa074029162f7d5995fa04f058d3/href</a></iframe><p>We use glorot initialization of kernel. That means that we generate kernel weights randomly in range from -limit to limit, where limit is sqrt(6/(inputFeatureChannels + outputFeatureChannels))</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2483997abee561cada6f3d43dda7834d/href">https://medium.com/media/2483997abee561cada6f3d43dda7834d/href</a></iframe><p>After kernel generation, we initialize weights &amp; biases state and command buffer, where all the initializations will be performed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11e3a526f652a2081efcabb6cbd5acd6/href">https://medium.com/media/11e3a526f652a2081efcabb6cbd5acd6/href</a></iframe><p>Then, we run command completion and wait until it is completed.</p><h3>Convolution and Dense layers</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db3036d9968ab3e99112a319acfd84d5/href">https://medium.com/media/db3036d9968ab3e99112a319acfd84d5/href</a></iframe><p>Dense layer is quite different, it doesn’t require padding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cc5abde81b9ce94cc3201af9fd61082/href">https://medium.com/media/3cc5abde81b9ce94cc3201af9fd61082/href</a></iframe><h3>Graphs generation</h3><p>To create graphs from layers, we need to implement function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e98e4816808ad6942ea1fa4a6f075323/href">https://medium.com/media/e98e4816808ad6942ea1fa4a6f075323/href</a></iframe><p>Graph is created during patching nodes to other nodes. We need to store result image of the last node as a source for the new one.</p><p>In switch-case statement we’ll create node for layer. Every node requires source at initialization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2ae662338ca4f7b894c85a2b4823b0/href">https://medium.com/media/7d2ae662338ca4f7b894c85a2b4823b0/href</a></iframe><p>Convolution node requires weights’ data source and padding policy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/984453c5c5c6a83f25d85a666c688ebf/href">https://medium.com/media/984453c5c5c6a83f25d85a666c688ebf/href</a></iframe><p>Activation functions don’t require any parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aebd87ae2c32ffb2731ff6d13c4e1ff6/href">https://medium.com/media/aebd87ae2c32ffb2731ff6d13c4e1ff6/href</a></iframe><p>Flatten layer requires flat input size (you can get it by running getOutputSize method without flatten and next layers). This layer transforms input to 1x1 matrix with a number of channels equals to flat input size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac59b3d4817590a3106e9934f30c3bc1/href">https://medium.com/media/ac59b3d4817590a3106e9934f30c3bc1/href</a></iframe><p>Dropout node is included only into training graph. It requires probability of value keeping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b3d37680daf3f65b45a9e3c47e15492/href">https://medium.com/media/0b3d37680daf3f65b45a9e3c47e15492/href</a></iframe><p>Dense layer structure is like Convolution layer, but doesn’t require padding policy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655c4be06798b79458cf5cbfc007b6b7/href">https://medium.com/media/655c4be06798b79458cf5cbfc007b6b7/href</a></iframe><p>And the last case is default, so if the current layer isn’t subclass of Layer class, then we don’t include any nodes into our graphs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed91397d90b76521c2ecb0f73b0b18c9/href">https://medium.com/media/ed91397d90b76521c2ecb0f73b0b18c9/href</a></iframe><p>Our neural network framework will support only softmax activation function at the end of the neural network model. We add loss node of softmax to the training graph and softmax node to the inference graph.</p><h3>Neural Network model initialization</h3><p>After we implemented a method that creates nodes for our model, we can implement initialization of our NN model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08dead9bf565b1998a81587eda2946bf/href">https://medium.com/media/08dead9bf565b1998a81587eda2946bf/href</a></iframe><p>So, what we need to initialize the model? First, we need MTLDevice.</p><blockquote>The MTLDevice protocol defines the interface to a GPU. You can query a MTLDevice for the unique capabilities it offers your Metal app, and use the MTLDevice to issue all of your Metal commands.</blockquote><p>The second thing we need is MTLCommandQueue from our MTLDevice.</p><blockquote>A MTLCommandQueue object queues an ordered list of command buffers for a <a href="https://developer.apple.com/documentation/metal/mtldevice">MTLDevice</a> to execute. Command queues are thread-safe and allow multiple outstanding command buffers to be encoded simultaneously.</blockquote><p>The third is array of layers which we’ll use at the createNodes() function to build our graphs.</p><p>And the last two arguments are basic model parameters: number of epochs and batch size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a40ac402a22726b48cea7e98820f995/href">https://medium.com/media/7a40ac402a22726b48cea7e98820f995/href</a></iframe><p>First, we copy arguments of initialization to the local storage of our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f4ba63687becb0f220f1460ecdb9dc9/href">https://medium.com/media/6f4ba63687becb0f220f1460ecdb9dc9/href</a></iframe><p>To get final node, we run createNodes() method. But after method running, we get nodes without loss nodes (except softmax loss node).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fc78cad8f6ca6addf8ccc72cb0281f3/href">https://medium.com/media/5fc78cad8f6ca6addf8ccc72cb0281f3/href</a></iframe><p>To create training graph, we need to add loss nodes and get loss exits, so we run trainingGraph method. It returns loss exit points of graph. In our case, it must contain only one loss exit point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159937dba887402c9e14372c81dfa0da/href">https://medium.com/media/159937dba887402c9e14372c81dfa0da/href</a></iframe><p>After getting loss exit point, we can use it to create training graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42e123a6ff04323cdf5263f2b0d90615/href">https://medium.com/media/42e123a6ff04323cdf5263f2b0d90615/href</a></iframe><p>Inference graph initialization is like the training one. This initialization is easier because we don’t have to create loss nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec1db05a49e0824bc503f78ed135324/href">https://medium.com/media/5ec1db05a49e0824bc503f78ed135324/href</a></iframe><p>Creating inference graph is quite the same as training graph creating.</p><h3>Dataset implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c88fdbba8e1b32627702abfff7b59863/href">https://medium.com/media/c88fdbba8e1b32627702abfff7b59863/href</a></iframe><p>Our dataset supports 2 types of data: images and bytes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446666da2895f058129f4b3113c487f6/href">https://medium.com/media/446666da2895f058129f4b3113c487f6/href</a></iframe><p>Dataset comprises array of samples, image size parameter (if data type is image), class labels (our neural network model is supposed to be classifier).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2330bb4d0b593ac5d44ce106aadfd801/href">https://medium.com/media/2330bb4d0b593ac5d44ce106aadfd801/href</a></iframe><p>Data sample duplicates data type for convenient use. Also, it stores label index in classLabels array in dataset. Body of the sample depends on data type. If data type is image, then sample stores CGImage and its MTLTexture.</p><p>Before data sample initialization, we need to create convert method from CGImage to MTLTexture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82e24d4f1f80528874716211756d487d/href">https://medium.com/media/82e24d4f1f80528874716211756d487d/href</a></iframe><p>I implemented convert method as a computable variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7929e63b9f981219a79b5bf7ec899af/href">https://medium.com/media/c7929e63b9f981219a79b5bf7ec899af/href</a></iframe><p>Because of that, I have to get default MTLDevice again. So frequent thing in Metal coding is working with descriptors. And we need to create texture descriptor. Pixel format for our texture is r8Unorm. It means there is only red channel here (grayscale) and the value is represented as unsigned 8-bit normalized integer. Also, we copy width and height of CGImage to the descriptor. Our texture region has zero-origin and size equals to CGImage size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d19f8cd9bb047a3fbf4d96e799686e0/href">https://medium.com/media/2d19f8cd9bb047a3fbf4d96e799686e0/href</a></iframe><p>Our color space use 8-bit per component and one component per pixel(red channel). Also, our color space doesn’t use alpha channel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7dd735b2188c390e98a34480da4791e/href">https://medium.com/media/a7dd735b2188c390e98a34480da4791e/href</a></iframe><p>We use Accelerate framework to make image fitting to the format of our texture. After it, we use the image to get data that can be written to the texture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cb958107ec5cb69bb07e78e4e4af61d/href">https://medium.com/media/1cb958107ec5cb69bb07e78e4e4af61d/href</a></iframe><p>And this method helps us to create data sample much easier. Initialization of data sample is defining the type, copying parameters from arguments and getting texture (if the type is image).</p><p>But we can’t use our data samples in feeding the model. So, we have to implement the conversion to the MPSImage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41b21b7222ffc025a2ac8ff7c79ab0b0/href">https://medium.com/media/41b21b7222ffc025a2ac8ff7c79ab0b0/href</a></iframe><p>MPSImage can be initialized easily with a texture. When data type is bytes, we create flat MPSImage with descriptor and write bytes to it.</p><p>OK. We implemented data sample class. Now we have to implement dataset initializing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec271bed34e957e884cf00054d8c5663/href">https://medium.com/media/ec271bed34e957e884cf00054d8c5663/href</a></iframe><p>Initializing dataset with bytes is very simple. All we have to do is to provide initializer with array of bytes and label for every sample.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6869d680adcd30190f9d096c19b5904e/href">https://medium.com/media/6869d680adcd30190f9d096c19b5904e/href</a></iframe><p>Also, we’ll write initializer from folder of sub-folders with images. To work with folders and files we have to get default FileManager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef606a7bb62fc6a1818bb5c78d6bdd69/href">https://medium.com/media/ef606a7bb62fc6a1818bb5c78d6bdd69/href</a></iframe><p>Then, we implement our files structure. First, we seek for sub-folders in the given folder. Every sub-folder represents a unique class. Then, we look for files in every sub-folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723e476c122d0bca9e66eee6524b0052/href">https://medium.com/media/723e476c122d0bca9e66eee6524b0052/href</a></iframe><p>After that, we try to read an image from every file. If we read image successfully, then we can fit the image to the format using CGContext. And the last thing is creating DataSample from the image and adding it to the samples array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cd2f609eb07b9826c1701751a95a22a/href">https://medium.com/media/6cd2f609eb07b9826c1701751a95a22a/href</a></iframe><p>For the case, when we have only one dataset and want to divide it into train and test sets, we must write an appropriate method. It copies all the common parameters like array of class labels, image size and data type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fcf8c2ce77ff6bbd2cc0f1cc0a1137e/href">https://medium.com/media/9fcf8c2ce77ff6bbd2cc0f1cc0a1137e/href</a></iframe><p>After that, it divides samples by classes, using Dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1e5212d859ad21c24e373ec6e9677c6/href">https://medium.com/media/a1e5212d859ad21c24e373ec6e9677c6/href</a></iframe><p>Then, it divides all classes of the sample using a given test set percentage.</p><h3>Training</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9512bfcd1a19a98a15129bf5611d529b/href">https://medium.com/media/9512bfcd1a19a98a15129bf5611d529b/href</a></iframe><p>Our training process is divided into epochs. Before starting new epoch, we have to wait until the previous one completed. We evaluate our model before training and after every epoch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7cc9811ef3168e27de622ec3329d6b/href">https://medium.com/media/2e7cc9811ef3168e27de622ec3329d6b/href</a></iframe><p>At every epoch we sending all the samples in batches to the training.</p><p>But before implementing the trainIteration method we have to implement getting training batches from dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bc93fd127ef5c68a6f29b5037f1af2/href">https://medium.com/media/23bc93fd127ef5c68a6f29b5037f1af2/href</a></iframe><p>Getting training batch isn’t hard, ’cause we implemented getting MPSImage from sample. Batch is array of these MPSImages. Also we have to change loss state batch with labels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9abbab134eb280de39f9ace43c3762e/href">https://medium.com/media/f9abbab134eb280de39f9ace43c3762e/href</a></iframe><p>Loss data us array of type float, where all the variables except the correct one are equal to 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac3109d792bb54ae421242f78f45b613/href">https://medium.com/media/ac3109d792bb54ae421242f78f45b613/href</a></iframe><p>After getting training batch, we have to encode it to MTLCommandBuffer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/635ffdbe5dd13a4b83f818d49568c5e9/href">https://medium.com/media/635ffdbe5dd13a4b83f818d49568c5e9/href</a></iframe><p>In training iteration, we get train batch and expectation for it. Using double buffering semaphore cause permanent 100% GPU load.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c715065a04583164e085c4e4781b6b/href">https://medium.com/media/40c715065a04583164e085c4e4781b6b/href</a></iframe><p>We have to add completed handler to our command buffer. After training iteration over, we count training loss and output it to Terminal. We use fflush to replace previous iteration state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2b24e7be0889d9a876846ff17a076f6/href">https://medium.com/media/c2b24e7be0889d9a876846ff17a076f6/href</a></iframe><p>To get training loss, we sum all the losses in a batch and dividing it by batch size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ed1e025e906985355fc2f8d2b1c3933/href">https://medium.com/media/6ed1e025e906985355fc2f8d2b1c3933/href</a></iframe><p>At the end we synchronize batches with command buffer, start commands in a buffer and return it.</p><h3>Evaluation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97ba8c535732388d58c0eab08c10283/href">https://medium.com/media/c97ba8c535732388d58c0eab08c10283/href</a></iframe><p>While evaluation, we count correct answers and divide it by the number of samples in the test set. Then, we reload inference graph from data sources, because weights were changed only in training graph during training, not in inference graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50c6c9081d0627cf5a9dcc8709cb7dae/href">https://medium.com/media/50c6c9081d0627cf5a9dcc8709cb7dae/href</a></iframe><p>Evaluation also will have double buffering semaphore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/572252d3169cdff5e96110414ec62fd2/href">https://medium.com/media/572252d3169cdff5e96110414ec62fd2/href</a></iframe><p>Batch preparation is even easier than in training. We need an only array of DataSamples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db191a3ac20265f9f4c9868ab72c9e84/href">https://medium.com/media/db191a3ac20265f9f4c9868ab72c9e84/href</a></iframe><p>Then we’ll use predict method, because we need to implement it, anyway. It returns an array of label predictions. We compare expectations with predictions and evaluate model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1a78875de1482a53552f7fbecf06ac/href">https://medium.com/media/3a1a78875de1482a53552f7fbecf06ac/href</a></iframe><p>For prediction we have to prepare our DataSamples. We transform them into MPSImages and encode to command buffer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b0cf05bb6472577a6b2be53c210b97c/href">https://medium.com/media/7b0cf05bb6472577a6b2be53c210b97c/href</a></iframe><p>Encoding inference batch to command buffer is very similar to encoding training batch. The only difference is that we encoding batch to inference graph, not training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bece21a11cd7f60c5e0f6774ff50ed8f/href">https://medium.com/media/bece21a11cd7f60c5e0f6774ff50ed8f/href</a></iframe><p>When operations on GPU are done, we can check output for every item in a batch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8921cded4712762d2f73ad1a40296fd5/href">https://medium.com/media/8921cded4712762d2f73ad1a40296fd5/href</a></iframe><p>Then, we read output for every item in a batch and append array of answers by an index of the maximum value. That is how classifiers work.</p><h3>Examples</h3><p>I tried hiragana classification using ETL dataset and digits classification using MNIST. After 10 minutes of training, hiragana classifier had 75% accuracy and digits classifier had 98% accuracy.</p><h3>Conclusion</h3><p>This neural network framework is much faster than the previous version we made. However, our implementation supports only classifiers. If you are really interested in building other neural network models with Metal Performance Shaders, our framework is flexible and you can modify it as well. Saving model is a very usual thing, that is why I didn’t consider it in this article. You can find the source code with a model saving in <a href="https://github.com/stefjen07/ShadersNeuralNetwork">my GitHub repository</a>.</p><p>Thanks for reading. If you have any tips or you found mistakes in this article, please leave your feedback in the comments. I am ready to improve the experience of my readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1fd75d715b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-neural-network-in-swift-using-metal-shaders-aa1fd75d715b">Building Neural Network in Swift using Metal shaders</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks in Swift]]></title>
            <link>https://medium.com/data-science/neural-networks-on-swift-ba181dcdfde5?source=rss-12391c476fb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba181dcdfde5</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Eugene Stsefankou]]></dc:creator>
            <pubDate>Mon, 10 May 2021 21:02:40 GMT</pubDate>
            <atom:updated>2021-05-13T14:39:14.721Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating Neural Network framework in Swift from scratch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TtBn650FQJGshnLi" /><figcaption>Photo by <a href="https://unsplash.com/@askkell?utm_source=medium&amp;utm_medium=referral">Andy Kelly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>We live around great technologies like self-pilot cars, voice assistants, image analyzers. Most of them use neural networks as the basis for their algorithm. We’re going to build a basic neural network from scratch using Swift.</p><h3>Some theory</h3><p>Before we can develop an application, we must learn the theory of neural networks. Neural networks are made up of <em>input, output and hidden layers</em>. Full-connected simple layers are composed of <em>neurons</em>. <em>Synapses</em> connect neurons to each other. Each synapse has its own <em>weight value</em>. During the generation of the neural network, it fills the weights with random values. They will be changed while training (in the animation below, <strong>red</strong> indicates <em>high weight</em> and <strong>blue</strong> indicates <em>low weight</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*JdVZlulpawGx63uPXySNEg.gif" /><figcaption>Training neurons. Image by Yauheni Stsefankou</figcaption></figure><p><strong>The training process</strong> is divided into several epochs. We process all data samples in the dataset at each epoch. We fill the input layer with data sample’s input. Each layer then processes the input through the activation function and sends it to the next layer through synapses. When a value passes through a synapse, it multiplies the value by the synapse weight. When the neuron’s value is calculated, it <em>sums up all the input values and bias</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*bej53fIfWFJcykfKCbpP0w.gif" /><figcaption>Forward propagation. Image by Yauheni Stsefankou</figcaption></figure><p>Here is an example of a neural network. It gets <em>an unsigned 4-bit number</em> and returns <em>whether the number is even or not</em>. Note that <em>all binary representations of even numbers end with 0</em>. This means that <strong>prediction depends only on the last bit</strong> (the fourth neuron from the input layer). This is why I’ve highlighted the synapses that are connected to the last neuron in the input layer. Other synapses from the input layer make no sense and their weights approach zero during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*NC5KCQlgpyjXGhuT_2ErmA.jpeg" /><figcaption>Neural network example. Image by Yauheni Stsefankou</figcaption></figure><h3><strong>Short review</strong></h3><p>Our neural network framework will not be fast due to the lack of very tight optimizations and GPU compatibility. Its only optimization is <em>multithreading by DispatchQueue’s concurrent performing</em> instead of loops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*4RL6_rC_SyEDmccEzsOOwA.gif" /><figcaption>Concurrent performing vs For loop. Image by Yauheni Stsefankou</figcaption></figure><p>This implementation consists of <em>a Dense layer, sigmoid function, training and prediction methods</em>.</p><p>Let’s start!</p><h3>Dataset structure</h3><p>We have to implement Dataset that contains all the samples we want to train on.</p><p>Here is a Dataset model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*xlos9IAYIQ3o9GPWLlv6MQ.jpeg" /><figcaption>Dataset model. Image by Yauheni Stsefankou</figcaption></figure><p>Note that <em>the dataset consists of data samples</em>. Let’s implement the structure in Swift.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2dbddfa79920e32488fa893dac96a0b/href">https://medium.com/media/d2dbddfa79920e32488fa893dac96a0b/href</a></iframe><p>Our second observation is that <em>data samples include input and output data</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d1768f5ffd3372ca23b094add18fcbd/href">https://medium.com/media/9d1768f5ffd3372ca23b094add18fcbd/href</a></iframe><p>And <em>the data pieces are composed of a body and its size</em> for convenience.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d45cb82e73c60e6557052762749c6acd/href">https://medium.com/media/d45cb82e73c60e6557052762749c6acd/href</a></iframe><p>The size of the data <em>must have a width, optional variables are height and depth</em> (depends on the type of data size). This is why we provide initializers for all data size types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a3731189542d2ec815034ff2d90356a/href">https://medium.com/media/4a3731189542d2ec815034ff2d90356a/href</a></iframe><p>Data piece can be <em>1D, 2D or 3D</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98478913b53f9e8e87fdb3944853f8cc/href">https://medium.com/media/98478913b53f9e8e87fdb3944853f8cc/href</a></iframe><h3>NN model class</h3><p>We have implemented a dataset system in our neural network. Now we need to create <em>a neural network class</em>. It includes <em>layers, learning rate, number of epochs per training, number of samples in each training batch</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d88993c6f5a83945e6ce859a91e69a/href">https://medium.com/media/27d88993c6f5a83945e6ce859a91e69a/href</a></iframe><p>Now we need to implement <em>the Layer class</em>. Each layer includes several neurons (except for convolutional layers) and an activation function for them. In addition, we will keep the output cache for backpropagation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2135c128bcfe408440c95c1ed711243f/href">https://medium.com/media/2135c128bcfe408440c95c1ed711243f/href</a></iframe><p>Each neuron stores weight for each synapse that goes to it and the bias. In addition, we keep a cache to update the weights to support <em>batch</em> gradient descent types. There are 3 gradient descent types: <em>batch, stochastic and mini-batch</em>. With <em>batch</em> and <em>mini-batch</em> gradient descent, the weights are updated after multiple propagations. In addition, we keep the delta for backpropagation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de5982eeeb83ac372b1af4fa3bedab5b/href">https://medium.com/media/de5982eeeb83ac372b1af4fa3bedab5b/href</a></iframe><p>Neural networks use many activation functions such as <em>sigmoid, ReLU</em>. We need to define these activation functions as a protocol. Each activation contain transfer (for forward propagation) and derivative functions (for backward propagation). We also store ID (rawValue) for enumerating functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ac44cd0a25c076021a477ef3c8bc403/href">https://medium.com/media/8ac44cd0a25c076021a477ef3c8bc403/href</a></iframe><p>And now for this protocol it is possible to create structures of activation functions. Let’s make a sigmoid function.</p><h3><strong>Sigmoid function</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*4ZzyNJAz-j_ppzPJFfBYBg.png" /><figcaption>Rendered equation from Wikipedia</figcaption></figure><p>I think you’ve seen <em>the graph of the sigmoid function</em>. Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXCBO-Wx5XhuY_OwMl0Phw.png" /><figcaption>The graph of the sigmoid function. Image from Wikipedia by Qef</figcaption></figure><p><strong>The sigmoid function</strong> is suitable when we need to get the probability at the output. For example, the probability of even numbers.<br><strong>The sigmoid derivative function</strong> is the product of the output and the difference between the output and 1.</p><p>Our sigmoid structure contains its <em>identifier</em> (rawValue), <em>transfer and derivative functions</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cceacc7695760f1398ddbd6707c6e3bd/href">https://medium.com/media/cceacc7695760f1398ddbd6707c6e3bd/href</a></iframe><p>In addition, we need to create an enum for our functions and a method to get them from the identifiers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e27ccf57ed5bc3af3b6e5635b16b6e68/href">https://medium.com/media/e27ccf57ed5bc3af3b6e5635b16b6e68/href</a></iframe><h3>Layer functions</h3><p>Each type of layer should have individual propagations. Here they are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4346f242e0580e96945c792e7f48e2f9/href">https://medium.com/media/4346f242e0580e96945c792e7f48e2f9/href</a></iframe><h3>Training algorithm</h3><p>The first thing we need to do is <em>divide a dataset into batches</em>. We can do this by shuffling data samples and then dividing them into groups with a size equal to the preferred batch size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*ggEl3veUyo_HMYUSjQwmYw.gif" /><figcaption>Dividing into batches. Image by Yauheni Stsefankou</figcaption></figure><p>Then, for each sample in a batch, the algorithm performs forward and backward propagations. After using all samples in batch, the algorithm updates the weights for all the layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede1e6a4387d48ea29e2ee4acb3a6569/href">https://medium.com/media/ede1e6a4387d48ea29e2ee4acb3a6569/href</a></iframe><h3>Propagations executing</h3><p><strong>Forward propagation</strong> sends the output of neurons through synapses to the next layer.</p><p><strong><em>Backpropagation</em></strong> spreads a prediction error by using forward propagation cache and pushing it toward the input layer. For the first propagation, sample’s expected value is used as input.</p><p><strong>The delta weights method</strong> calculates the change in weights and stores them in the cache. It works like a forward propagation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87059d58a1a01f5cd7e8c7dbade6876c/href">https://medium.com/media/87059d58a1a01f5cd7e8c7dbade6876c/href</a></iframe><h3>Dense layer</h3><p>The first Layer subclass in our neural network is <strong>a Dense layer</strong>. We considered a Dense layer in the section <em>Some theory</em>. This is the simplest layer of neural networks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7418d6bd9b60a19861cf52222bc96ea/href">https://medium.com/media/d7418d6bd9b60a19861cf52222bc96ea/href</a></iframe><p>OK. We have initialized a Dense layer, now we need to write propagation functions for it. Instead of loops we use concurrent performing from DispatchQueue. <em>Forward propagation</em> generates an output of each neuron by multiplying the weight of each neuron and the inputs passed to it. It also adds bias to the result. And the last operation with the result is the use of the activation transfer function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4456d53bfefa8b1307af6e99900984c3/href">https://medium.com/media/4456d53bfefa8b1307af6e99900984c3/href</a></iframe><p><em>Backward propagation</em> uses the output of forward propagation to spread the error across all neurons. It spread errors using the activation derivative function. Multithreading is not optimal here, so we don’t use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27e5a14564174bdd134e4477b9a7146b/href">https://medium.com/media/27e5a14564174bdd134e4477b9a7146b/href</a></iframe><p><em>The delta weights method</em> is using concurrent performing. When building neural network model, you should find a sweet sport for the learning rate. Also, bias is updating during this method execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16d292262375dd3dfa0057584f976c01/href">https://medium.com/media/16d292262375dd3dfa0057584f976c01/href</a></iframe><p>After all the items in the batch are used, the neural network updates neurons’ weights with propagation cache. And, of course, it is optimal to use multi-threading concurrent performing here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/564abd21353dfe377739cb9fccd25a57/href">https://medium.com/media/564abd21353dfe377739cb9fccd25a57/href</a></iframe><p>And the second important function of a neural network is <em>predicting</em>. To predict the result, the function <em>receives the forward propagation result</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a9ad1d08a5e95352fc37c193a663816/href">https://medium.com/media/0a9ad1d08a5e95352fc37c193a663816/href</a></iframe><h3><strong>Using written framework to implement neural network model</strong></h3><p>Hooray! We have implemented <em>the foundation of our neural network framework, sigmoid activation and a Dense layer for it</em>. Now we can check this with a simple example.</p><p>The task of this example is <em>to classify a number by parity</em>. This is an unusual task for neural networks, but easy to understand.</p><p>To initialize a new neural network model, we need to put this in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bebe2851ac56144e60b01539e71f905/href">https://medium.com/media/8bebe2851ac56144e60b01539e71f905/href</a></iframe><p>After that, we can change some parameters of our model (batch size, number of epochs and learning rate):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f6e022f585c77b27c7d03c625a8e6f/href">https://medium.com/media/e1f6e022f585c77b27c7d03c625a8e6f/href</a></iframe><p>The most important part when implementing a neural network model is setting up the layer structure. Here is the layer structure example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afd4baeee91c1483f78dfeef7e6ed52f/href">https://medium.com/media/afd4baeee91c1483f78dfeef7e6ed52f/href</a></iframe><p>After that, our model is ready for training. It all starts with feeding a dataset into a model.</p><p>We put <em>the input number as its binary</em> and get <em>the probability that it is even</em>. The first sample from our dataset is <em>[0.0, 0.0, 0.0, 1.0]</em>, and its expectation value is <em>0.0</em>. This means that binary representation of input number is <em>0001</em>. In decimal representation, it will be <em>1</em>. It is an odd number. Therefore, we expect <em>0.0</em> (zero probability that the number is even).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa55400b1d05487a3fc7782eb09fccf/href">https://medium.com/media/7fa55400b1d05487a3fc7782eb09fccf/href</a></iframe><p>After training the neural network, you can start using it for predictions. You can get a prediction by feeding data sample to model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e6d4b7a7b272f540f1d58dea6fda971/href">https://medium.com/media/2e6d4b7a7b272f540f1d58dea6fda971/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*-0dGeKWzNLSZAE6SUdeQIA.png" /><figcaption>The result of training with 30 epochs. Image by Yauheni Stsefankou</figcaption></figure><p>The result is <em>0.45</em>, which means that the answer is <em>0 (odd) with 55% probability</em> or <em>1 (even) with 45% probability</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*iJhqP28s6UiwRH0NWSOhQA.png" /><figcaption>The result of training with 1000 epochs. Image by Yauheni Stsefankou</figcaption></figure><p>When we change the number of epochs to <em>1000</em>, training takes thirty times longer, but the probability of the evenness of <em>1111</em> changes to <em>3.8%</em>. This means that our neural network model has become more accurate.</p><h3>Model saving</h3><p>To save the model, we need to prepare all structures and classes. They must be <em>compatible with the Codable protocol</em> for JSON encoding. Almost all classes and structures only need to add the Codable protocol to the declaration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a6c3755da2c188f9247f3d620af1e1/href">https://medium.com/media/95a6c3755da2c188f9247f3d620af1e1/href</a></iframe><p>We implemented the layer as a class, not a structure. <strong>The class requires encoding and decoding methods</strong> to conform to the Codable protocol. Encoding and decoding methods require keys for all the variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29dedf76a3c9f7c596b211912995177e/href">https://medium.com/media/29dedf76a3c9f7c596b211912995177e/href</a></iframe><p>After adding it, we have to add the initializer from the decoder to our Dense layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a769bde08a7baf1016ff1857f45de092/href">https://medium.com/media/a769bde08a7baf1016ff1857f45de092/href</a></iframe><p>We need to write <em>a wrapper for the layer</em> because Layer class <em>is not final and it can have subclasses</em>. It encodes not only the subclass of the layer, but also the type of the subclass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5d0973871316c5ae752e05aa21d8522/href">https://medium.com/media/a5d0973871316c5ae752e05aa21d8522/href</a></iframe><p>After writing the wrapper, we need to replace the encoding and decoding methods of the neural network model with our own. Rather than encode and decode the layers as such, we encode the wrappers of the layers, because we need to store the type of the Layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3a3b522d4175cdcc612ffda9c459eed/href">https://medium.com/media/e3a3b522d4175cdcc612ffda9c459eed/href</a></iframe><p>Now we can write a method to save the model. First, we have to initialize JSON encoder and use it to encode the model. We then get the URL of the current application directory and write the encoded data there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c2800a6dbf46fd8895840a786004e5/href">https://medium.com/media/64c2800a6dbf46fd8895840a786004e5/href</a></iframe><p>Reading a model from a file is no more difficult than saving it. Now, instead of initializing the JSON encoder, we are initializing the JSON decoder. Then we get the data from the file and decode it with our decoder. And the last thing we need to do is initialize the model from the decoded model variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13c66e20191f7d3f23059953d82fbddd/href">https://medium.com/media/13c66e20191f7d3f23059953d82fbddd/href</a></iframe><h3>Conclusion</h3><p>We have created the basic neural network framework and now we can add any types of functions and layers. Here is a link to a git repository with all the source code and some extra features (Dropout, Flatten and Convolutional 2D layers, ReLU activation): <a href="https://github.com/stefjen07/NeuralNetwork">https://github.com/stefjen07/NeuralNetwork</a>.</p><p>Thanks for reading. If you have any tips or you found mistakes in this article, please leave your feedback in the comments. I am ready to improve the experience of my readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba181dcdfde5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/neural-networks-on-swift-ba181dcdfde5">Neural Networks in Swift</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>