<?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 Peter Skvarenina on Medium]]></title>
        <description><![CDATA[Stories by Peter Skvarenina on Medium]]></description>
        <link>https://medium.com/@peter.skvarenina?source=rss-4a506078a7b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zFs0DE_RrilrJ_nTBgE_IQ.jpeg</url>
            <title>Stories by Peter Skvarenina on Medium</title>
            <link>https://medium.com/@peter.skvarenina?source=rss-4a506078a7b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:22:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peter.skvarenina/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[Detecting facial features using Deep Learning]]></title>
            <link>https://medium.com/data-science/detecting-facial-features-using-deep-learning-2e23c8660a7a?source=rss-4a506078a7b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e23c8660a7a</guid>
            <category><![CDATA[video-chat]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Peter Skvarenina]]></dc:creator>
            <pubDate>Wed, 02 Aug 2017 13:08:46 GMT</pubDate>
            <atom:updated>2017-08-04T08:43:04.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Maybe you were wondering how you can place funny objects on faces in real-time video chats or detect emotions? I’ll show you one possible approach here utilizing deep learning as well as skim over one older approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*y9Z-gMLPPCR_yqhiO_EANw.jpeg" /></figure><p>A challenging task in the past was detection of faces and their features like eyes, nose, mouth and even deriving emotions from their shapes. This task can be now “magically” solved by deep learning and any talented teenager can do it in a few hours. I will show you such an approach in this post.</p><h3><strong>“Classical” method (CLM)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*gXmxeqKo-vNu5F0i8hIh7w.png" /></figure><p>If you were like me and had a need to perform face tracking (in my case to transfer one’s gestures from a web camera to an animated character), you probably found out that one of the best performing algorithms used to be Constrained Local Model (<a href="https://sites.google.com/site/xgyanhome/home/projects/clm-implementation/ConstrainedLocalModel-tutorial%2Cv0.7.pdf?attredirects=0">CLM</a>), as implemented by e.g. <a href="https://github.com/TadasBaltrusaitis/CLM-framework">Cambridge Face Tracker</a> or its newer <a href="https://github.com/TadasBaltrusaitis/OpenFace">OpenFace</a> incarnation. This is based on splitting the detection tasks into detecting shape vector features (<a href="http://slidegur.com/doc/3183242/face-and-facial-feature-tracking-asm--aam--clm">ASM</a>) and patch image templates (<a href="http://slidegur.com/doc/3183242/face-and-facial-feature-tracking-asm--aam--clm">AAM</a>), and refining the detection using pre-trained linear SVM.</p><p>It works by roughly estimating key-point positions first, then applying SVM with pre-trained images containing parts of face and adjusting key-point positions. This is repeated until error is sufficiently low for our purposes. Also, worth mentioning that it assumes the position of face on the image was estimated already, e.g. by using <a href="https://en.wikipedia.org/wiki/Viola%E2%80%93Jones_object_detection_framework">Viola-Jones detector</a> (<a href="https://en.wikipedia.org/wiki/Haar-like_feature">Haar cascades</a>). The CLM process is however pretty involved and non-trivial, and definitely won’t be implemented by a high-school wizard. You can see the overall architecture here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSji4dBB_q23hLyeZ4fgrw.png" /><figcaption>Well, fairly complicated, right?</figcaption></figure><h3><strong>Deep Learning</strong></h3><p>Instead, we can use a very simple convolutional neural network (<a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">CNN</a>) and perform detection of key-points on parts of images we expect to contain faces. For that we need to have a training dataset though; we can use the one provided by <a href="https://www.kaggle.com/">Kaggle </a>for their <a href="https://www.kaggle.com/c/facial-keypoints-detection/data">facial key-points detection challenge</a>, containing 15 key-points, or a more complex <a href="http://www.milbo.org/muct/">MUCT dataset</a> with 76 key-points (Yay!).</p><p>Obviously, having quality training datasets is essential here and we all should commemorate poor undergrad students that had to sacrifice their time and effort to annotate bunch of faces to be allowed to graduate, so that we can perform these magical tricks easily.</p><p>Here is how a sample baroque face and its key-points in the Kaggle dataset would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*1e9NG46qPoybYZeeTCfGBw.png" /><figcaption>James Madison Jr.</figcaption></figure><p>The dataset contains greyscale images with 96x96 resolution and 15 key-points, 5 per each eye and 5 for mouth/nose positions.</p><p>For an arbitrary image, we first need to detect where in the image the faces are; aforementioned Viola-Jones detector based on Haar cascades can be used (and if you look at how it works, it resembles CNNs a bit). Or if you are more adventurous, you can use Fully Convolutional Networks (<a href="https://people.eecs.berkeley.edu/%7Ejonlong/long_shelhamer_fcn.pdf">FCN</a>) as well and perform image segmentation with depth estimation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwF91aP0qoNZ5IenPij5uQ.jpeg" /><figcaption>OpenCV does the trick</figcaption></figure><p>Anyway, this is a piece of cake using OpenCV:</p><pre>Grayscale_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)</pre><pre>face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)</pre><pre>bounding_boxes = face_cascade.detectMultiScale(grayscale_image, 1.25, 6)</pre><p>This chunk of code returns all possible face bounding boxes on an image.</p><p>Next for each bounding box returned by Viola-Jones we extract the corresponding sub-images, convert them to greyscale and resize them to 96x96. And they will become input to our finished CNN for inference.</p><p>The CNN architecture is super trivial; a bunch of 5x5 convolutional layers (3 in fact, with 24, 36 and 48 filters each), then 2 more 3x3 convolutional layers (64 filters each) and 3 fully connected layers (with 500, 90 and 30 nodes) in the end. Some max pooling to prevent overfitting and global average pooling to reduce number of flatten parameters. The output will be 30 floating point numbers denoting a sequence of x, y coordinates for each of 15 key-points.</p><p>Here is the implementation in <a href="https://keras.io/">Keras</a>:</p><pre>model = Sequential()</pre><pre>model.add(BatchNormalization(input_shape=(96, 96, 1)))</pre><pre>model.add(Convolution2D(24, 5, 5, border_mode=”same”, init=’he_normal’, input_shape=(96, 96, 1), dim_ordering=”tf”))<br>model.add(Activation(“relu”))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=”valid”))</pre><pre>model.add(Convolution2D(36, 5, 5))<br>model.add(Activation(“relu”))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=”valid”))</pre><pre>model.add(Convolution2D(48, 5, 5))<br>model.add(Activation(“relu”))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=”valid”))</pre><pre>model.add(Convolution2D(64, 3, 3))<br>model.add(Activation(“relu”))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=”valid”))</pre><pre>model.add(Convolution2D(64, 3, 3))<br>model.add(Activation(“relu”))</pre><pre>model.add(GlobalAveragePooling2D());</pre><pre>model.add(Dense(500, activation=”relu”))<br>model.add(Dense(90, activation=”relu”))<br>model.add(Dense(30))</pre><p>You might want to choose <a href="http://Root Mean Square Propagation">Root Mean Square Propagation</a> (rmsprop) optimizer and <a href="https://en.wikipedia.org/wiki/Mean_squared_error">Mean Squared Error</a> (MSE) as your loss function and accuracy metrics.</p><p>Just by some trivial tricks like <a href="https://arxiv.org/abs/1502.03167">batch normalization</a> on input images, global average pooling as well as <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/keras/initializers/he_normal">HE normal</a> weight initialization you can get 80–90% validation accuracy and loss &lt; 0.001 at around 30 training epochs:</p><pre>model.compile(optimizer=’rmsprop’, loss=’mse’, metrics=[‘accuracy’])</pre><pre>checkpointer = ModelCheckpoint(filepath=’face_model.h5&#39;, verbose=1, save_best_only=True)</pre><pre>epochs = 30</pre><pre>hist = model.fit(X_train, y_train, validation_split=0.2, shuffle=True, epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*wQ6QBOJimsVXhpNUivQLdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*VbKZ8xJrDeX4wgZWRtHVqQ.png" /></figure><p>Then to predict key-points location simply run:</p><pre>features = model.predict(region, batch_size=1)</pre><p>aaand that’s it! You have now mastered the art of detecting facial key-points!</p><p>Mind you, the result of your prediction will be 15 pairs of x, y coordinates for each key-point, in the order as depicted on the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*aKejx96JSAAV6UqMGEAPcg.png" /><figcaption>Saving you some time…</figcaption></figure><p>If you want to do better, you might want to do some additional homework:</p><ul><li>experiment how you can reduce number of convolutional layers and filter sizes while retaining accuracy and improving inference speed</li><li>replace convolutional part with transfer learning (<a href="https://arxiv.org/abs/1610.02357">Xception </a>is my favorite)</li><li>use a more detailed dataset</li><li>do some advanced image augmentation to improve robustness</li></ul><p>You might find all of this way too easy; if you want a challenge, move to 3D and look at how <a href="https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf">Facebook</a> and <a href="http://research.nvidia.com/sites/default/files/publications/laine2017sca_paper_0.pdf">NVidia</a> are tracking faces.</p><p>Obviously, you can use this newly learned magic to perform some non-trivial things you might have always wanted to do but didn’t know how:</p><ul><li>place annoying objects on faces during video chat such as sunglasses, weird caps, mustaches etc.</li><li>swap faces between friends, enemies, animals and objects</li><li>contribute to vanity of human population by allowing testing new hair-styles, jewelry or make-up on selfie real-time videos</li><li>detect if your employee is too drunk (or insufficiently drunk) to perform assigned tasks</li><li>identify prevailing emotion in people in your video feed if you want to automate emotional processing for whatever weird reason</li><li>use real-time face-to-cartoon conversion using <a href="https://en.wikipedia.org/wiki/Generative_adversarial_networks">GANs</a> and bend the cartoon faces according to your own face on a web-cam to mimic your movement, talk and emotions</li></ul><p>So now you know how to make your own awesome video chat filter! How about writing one right now?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kphA-vO990dlXHT7Je0-7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e23c8660a7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/detecting-facial-features-using-deep-learning-2e23c8660a7a">Detecting facial features using Deep Learning</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[Self-driving car using deep learning]]></title>
            <link>https://medium.com/@peter.skvarenina/self-driving-car-using-deep-learning-e796d39edf5c?source=rss-4a506078a7b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e796d39edf5c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[self-driving-cars]]></category>
            <category><![CDATA[future]]></category>
            <dc:creator><![CDATA[Peter Skvarenina]]></dc:creator>
            <pubDate>Sun, 12 Feb 2017 21:33:16 GMT</pubDate>
            <atom:updated>2017-03-04T18:19:39.902Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I would like to share with you something absolutely cool — how to make a car driving on its own using just a simple <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">convolutional neural network</a> (CNN) and a camera! A talented 12-year old should be able to put this all together ;-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*7DplprjmlTV27aEn2LxmGA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Mzfayxn6V69NP9b0AJS2bg.gif" /></figure><p>You can see the preview of the result on the images on the left.</p><p>First, <a href="https://en.wikipedia.org/wiki/Deep_learning">deep learning</a> is nowadays just a PR term for <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">neural networks</a>. Despite having some nice properties, like ability to <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem">approximate</a> any “normal” function pretty well, neural networks were soon considered a <a href="http://www.quotationspage.com/quote/239.html">dead-end</a> in artificial intelligence.</p><p>Only recently with some advances in computing back-propagation efficiently on GPUs and <a href="https://en.wikipedia.org/wiki/Big_data">Big data</a> revolution, they became extremely useful. I would like to show you how easy is it nowadays to use deep learning for a quite nice driving on its own!</p><p>The approach here is based on a fairly recent research from <a href="http://www.nvidia.com/">NVidia</a> and their self-driving car <a href="https://blogs.nvidia.com/blog/2016/05/06/self-driving-cars-3/">Dave-2,</a> described in <a href="https://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf">this paper</a>. They managed to have a car drive on its own by using three cameras, without any radar or <a href="https://en.wikipedia.org/wiki/Lidar">LiDAR</a>! This all needed just 72 hours of pre-recorded footage by human drivers for training neural network. You can watch it here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNJU9ULQUwng%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNJU9ULQUwng&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNJU9ULQUwng%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca1c54e1707be4341f5020c7f93a3600/href">https://medium.com/media/ca1c54e1707be4341f5020c7f93a3600/href</a></iframe><p>I will show you how to do this using a <a href="https://github.com/udacity/self-driving-car-sim">car simulator</a>. The idea is to drive around a track and associate each recorded/rendered image with the actual steering value, then pass it to neural network and let it learn from your driving style.</p><p>Here you can see three images from a simulator, each corresponding to one camera — left, center and right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*mLtJfOw-nvmCuQa8kqgDaQ.jpeg" /><figcaption>Car cameras in simulator</figcaption></figure><p>Using a simulator, you drive around the track, record images and their corresponding steering angle (we assume throttle/speed is always the same for simplicity), then pass this to a convolutional neural network/CNN. The network is described here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*oXwc-G9mGJC2LqD2N_kEug.png" /></figure><p>Now this structure probably looks weird if you’ve never seen a CNN before. You can see there are many layers, hence the name <strong>deep learning</strong>.</p><p>What you can see on the picture is that our network expects images in the format 200x66xRGB and its associated steering angle for training and outputs a steering angle it associates with an input image during self-driving.</p><p><a href="http://computervision.wikia.com/wiki/Convolution">Convolution</a> is a common way to create graphics filters in <a href="https://en.wikipedia.org/wiki/Computer_Vision">computer vision</a> or <a href="https://en.wikipedia.org/wiki/Image_processing">image processing</a> fields for things like edge detection. They usually extract some useful information encoded in a block of image we can process later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*ZCjPUFrB6eHPRi4eyP6aaA.gif" /><figcaption>Convolutional filter example (source: tkengo.github.io)</figcaption></figure><p>In our case, with each convolutional layer we would simply like to obtain some nice <strong>graphics filters we don’t know in advance</strong>, that would help us to process images with the intent to extract expected steering angle. Here you don’t have to know the details at all, we expect CNN to figure out what filters are needed, it’s our little magic box with answers!</p><p>Just quickly glancing over the layers, you can see convolutional layers specify a filter dimension (5x5 or 3x3), resulting output size (i.e. 98x31), how many filters we want to get (i.e. 24 in 98x31x24) and what is our activation function (in our case it’s <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLU</a>). Then we have <a href="http://people.idsia.ch/~juergen/icsipa2011.pdf">max pooling</a> and <a href="http://www.cs.toronto.edu/~hinton/absps/dropout.pdf">dropout</a> layers to reduce <a href="https://en.wikipedia.org/wiki/Overfitting">overfitting</a>, flattening layer and a few <a href="https://en.wikipedia.org/wiki/Multilayer_perceptron">fully connected dense layers</a>. You don’t need to know the details here.</p><p>Here is how this network looks like in <a href="https://keras.io/"><strong>Keras</strong></a>, a deep learning framework (it pretty much corresponds to the image with layers above):</p><pre>model = Sequential()<br><br># batch regularization to reduce internal covariate shift<br>model.add(BatchNormalization(input_shape=(66, 200, 3)))<br><br># 200x66x3 -&gt; 98x31x24, 5x5 convolution<br>model.add(Convolution2D(24, 5, 5, border_mode=&quot;valid&quot;, input_shape=(66, 200, 3), dim_ordering=&quot;tf&quot;))<br>model.add(Activation(&quot;relu&quot;))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=&quot;same&quot;))<br><br># 98x31x24 -&gt; 47x14x36, 5x5 convolution<br>model.add(Convolution2D(36, 5, 5, border_mode=&quot;valid&quot;))<br>model.add(Activation(&quot;relu&quot;))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=&quot;same&quot;))<br><br># 47x14x36 -&gt; 22x5x48, 5x5 convolution<br>model.add(Convolution2D(48, 5, 5, border_mode=&quot;valid&quot;))<br>model.add(Activation(&quot;relu&quot;))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), border_mode=&quot;same&quot;))<br><br># 22x5x48 -&gt; 20x3x64, 3x3 convolution<br>model.add(Convolution2D(64, 3, 3, border_mode=&quot;valid&quot;))<br>model.add(Activation(&quot;relu&quot;))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1), border_mode=&quot;same&quot;))<br><br># 20x3x64 -&gt; 18x1x64, 3x3 convolution<br>model.add(Convolution2D(64, 3, 3, border_mode=&quot;valid&quot;))<br>model.add(Activation(&quot;relu&quot;))<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1), border_mode=&quot;same&quot;))<br><br># flatten<br>model.add(Flatten())<br><br># dense 1164<br>model.add(Dense(1164))<br>model.add(Activation(&quot;relu&quot;))<br>model.add(Dropout(0.5))<br><br># dense 100<br>model.add(Dense(100))<br>model.add(Activation(&quot;relu&quot;))<br><br># dense 50<br>model.add(Dense(50))<br><br># dense 10<br>model.add(Dense(10))<br><br># dense 1<br>model.add(Dense(1))<br><br>model.compile(loss=&quot;mse&quot;, optimizer=Adam(LEARNING_RATE))</pre><p>The code above is in <a href="https://www.python.org/">Python,</a> I used <a href="https://www.jetbrains.com/">JetBrains</a> <a href="https://www.jetbrains.com/pycharm/?fromMenu">PyCharm </a>with <a href="https://www.continuum.io/downloads">Anaconda</a> to code and run/debug it.</p><p>Into this model you feed input images and steering angles, let it train for a while and the resulting weights and parameters on your layers can be then used to assign a steering angle to your input images.</p><p>Now, neural networks have unfortunately some strong disadvantages. One is that they learn very very slowly (unlike humans that can mimic things from a single observation), so you need a lot of driving data. This should be fairly simple if you program your car simulator to output driving data and render proper driving images for you though. Next, CNNs can be easily fooled by noise, where classification can fail on images where humans won’t notice any difference. For this we try to apply some significant transforms to training images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LsHPEcRWglqbuspYXfTCbQ.png" /><figcaption>Image processing pipeline</figcaption></figure><p>On the picture above we can see input image in the first row. Underneath are some transforms applied — first, some artificial “shadows” are generated, making CNN’s life a bit more difficult. This however is extremely useful if there are unexpected lighting variations during driving, like driving in a forest with trees casting shadows etc. Of course we would like our car to drive properly even in such case!</p><p>Next two transforms simulate driving on a bumpy road or fast driving with overloaded suspension — we just rotate and translate image a bit to simulate momentum changes.</p><p>Then there is random gamma adjustment — this can be used to simulate different lighting conditions throughout the day.</p><p>Last, we have resize and crop operations; crop making sure mainly road is visible and that image had expected dimensions for neural network.</p><p>You can think of many possible image adjustments to simulate weather, season, or even adding random noise etc. These few transforms are however sufficient for making car driving in our simulator all by itself.</p><p>Also, the training used images taken from all three cameras; the left and right cameras in addition adjusted steering a bit to side. They were basically used for situations such as “what if” car is driving to one side under dangerous angle. Here more eccentric camera placement could be used instead of driving to a side manually and then steering to opposite side with a full lock.</p><p>If you would like to know more details and play with the code yourself, you can see the whole project in <a href="https://github.com/squared9/Self-driving-Car/tree/master/Behavioral_Cloning">this repository</a>.</p><h3>Performance</h3><p>You need a beefy GPU to train network in acceptable time. In my case, I used around 25,000 input images, 0.0005 learning rate, 128 image batch and <a href="http://www.geforce.com/hardware/desktop-gpus/geforce-gtx-970">GTX970</a>, there were around 1,600,000 parameters to optimize and a single training epoch took around 10 minutes to run. You’d need between 5–40 epochs, so expect a few hours of training time. Obviously, you can invest in <a href="http://www.guru3d.com/articles-pages/geforce-gtx-1080-2-way-sli-review,1.html">dual GPUs</a> or even <a href="https://developer.nvidia.com/devbox">GPU clusters</a> to accelerate your training.</p><h3>Conclusion</h3><p>As you could see, deep learning has become a very powerful tool for many “intelligent” tasks. In our case, just having some images with steering angles allowed us to drive a car around, which is amazing when you think about it!</p><p>If you are interested in learning more about practical <a href="https://en.wikipedia.org/wiki/Machine_learning">ML</a>, there are many interesting things going on right now. <a href="http://www.udacity.com/">Udacity </a>is building an <a href="https://www.udacity.com/self-driving-car">open source self-driving car</a> and providing <a href="https://www.udacity.com/course/self-driving-car-engineer-nanodegree--nd013">self-driving car nanodegree</a> (where this project originated), <a href="http://selfdrivingcars.mit.edu/">MIT has an excellent intro to self-driving car</a> with a similar project from <a href="https://www.tesla.com/videos/full-self-driving-hardware-all-tesla-cars">Tesla</a> footage, <a href="http://www.stanford.edu/">Stanford </a>has a great <a href="http://cs231n.stanford.edu/">computer vision CNN course</a>, <a href="http://www.ox.ac.uk/">Oxford</a> provides a <a href="https://github.com/oxford-cs-deepnlp-2017">deep learning natural language course</a> with open challenges and there is a phenomenal <a href="https://www.coursera.org/learn/machine-learning">intro to ML by Andrew Ng</a> from Stanford on <a href="http://www.coursera.org/">Coursera</a>. For more rigorous education you might want to spend around $7,000 to get <a href="http://omscs.gatech.edu/specialization-machine-learning">online M.S. in ML</a> from <a href="http://www.gatech.edu/">Georgia Tech</a> (I myself am thinking about it) or take a more expensive <a href="http://scpd.stanford.edu/public/category/courseCategoryCertificateProfile.do?method=load&amp;certificateId=1226717">AI graduate certificate course</a> at <a href="http://www.stanford.edu/">Stanford</a>.</p><p>If you’d like to make your own self-driving car, there is <a href="http://f1tenth.org/">F1/10</a> racing league and you could consider assembling <a href="http://www.jetsonhacks.com/2016/01/18/jetson-racecar-build-part-1-traxxas-rally-unboxing/">MIT’s Jetson Car</a> including LiDAR and add some <a href="http://www.intel.com/content/www/us/en/nuc/overview.html">NUC</a>-style computer to run it fast.</p><p>And if you are crazy enough, why not make your own self-driving racecar? You can assemble your own <a href="http://www.b-racing.cz/en/gallery/">K1-Attack sports car</a> and enjoy utmost flexibility in programming the car to suit your own needs and ideas! And then there is always <a href="http://www.fiaformulae.com/en">Formula E</a> with its <a href="http://www.roborace.com/">Roborace</a> ;-) E-Lewis chasing E-Fernando before E-Max crashes into him!</p><h3>Future</h3><p>It really seems like either you are going to learn Machine Learning (ML) within the next few years, or <a href="https://bothsidesofthetable.com/mark-cuban-on-why-you-need-to-study-artificial-intelligence-or-youll-be-a-dinosaur-in-3-years-db3447bea1b4#.s6j14mjpa">you will become a dinosaur</a>. I can imagine there are already many people working on employing ML in simple code generation, like generating rudimentary web apps, mobile apps, CRUD etc. Now with <a href="https://www.andrew-lucas.com/connected-lifestyle/audrey-alexa-voice-recognitions-time-finally-come/">recent advancements in speech recognition</a>, imagine building a system listening to your commands, learning from your own code or code provided by other people associated with wishes how the app should behave expressed by voice and accompanied by code. With some meta-programming rules baked in we might soon see magic app builders where we just say what we want and then refine app by specifying what we don’t like. I wouldn’t be surprised if the main driver behind <a href="https://www.bloomberg.com/news/articles/2016-07-11/google-to-train-2-million-indian-developers-on-android-platform">teaching 2 million developers code Android</a> was a way to collect the type of reasoning the all skill-level developers use for given problems, and train a self-developing system to learn how to develop meaningful programs from that.</p><p>As somebody who spent a lot of time developing algorithms for <a href="https://www.animatron.com/">Animatron,</a> I can imagine creating animations not just by <a href="https://helpx.adobe.com/adobe-character-animator/how-to/adobe-character-animator.html">body</a> and <a href="http://squared9.com/animatrax/">facial gestures,</a> but also by telling a story, using voice commands to “actors” like a real movie director, and letting ML figure it out, by providing some annotated examples and annotated characters.</p><p>All this brings me to conclusion — it seems likely that many tasks currently done by software developers that are simple in nature will be automated away, like what we saw with associates at big law companies in the past 5 years. So it’s unlikely there will be well paid positions in SW engineering for most normal tasks in the next 10 years, only bleeding edge ones, and the sooner you jump onto ML/robotics/automation train, the better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e796d39edf5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Implemented the Puppet Tool in Animatron: a Step By Step Guide]]></title>
            <link>https://medium.com/@peter.skvarenina/puppet-implementation-e4be982747b6?source=rss-4a506078a7b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4be982747b6</guid>
            <category><![CDATA[gwt]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[webgl]]></category>
            <dc:creator><![CDATA[Peter Skvarenina]]></dc:creator>
            <pubDate>Wed, 05 Oct 2016 13:46:44 GMT</pubDate>
            <atom:updated>2017-12-16T23:17:59.412Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the upcoming tools in <a href="http://www.animatron.com/">Animatron</a> (our awesome online animation maker) is what we call <strong>puppet</strong>. It allows to go from this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*5qy4ywl7FBPoa-HR_NojyA.png" /></figure><p>into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mPC_PPgfZPLmBJXKqpEkdw.gif" /></figure><p>which is very cool! <br><em>(Note: medium.com reduced the quality of this animation causing color artifacts not present in the </em><a href="http://imgur.com/GKSDnzu"><em>original</em></a><em>)</em></p><p>In this article I’ll try to explain how this has been done in a fairly detailed fashion.</p><p>So, at first you have an image you’d like to animate in some funny way, like the sesame puppet we use throughout the article.</p><p>We take your image and use some basic image processing to remove the background. This processing is very simple at the moment, it just tries to estimate background color from the image corners and then erase the same color within some tolerance. In addition, it tries to apply some feather to smoothen the edges. Both tolerance and feather are set to some sensible default values that seem to work well with cartoon images we tried. Here is how it looks like for our image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*yKLnPG7JBoeZ4cuHFsejkQ.png" /></figure><p>Next, we apply some simple computer vision to the image — we first try to find out what is the component with the largest area in the image (which we assume is the character you want to animate) and then extract its contour. We end up with the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*ML2S1PpUOCJq8iFKzinjkQ.png" /></figure><p>The blue line here is the contour of the image. We use this contour to prepare a <strong>triangulation of the character</strong>. There are many possible choices for the type of triangulation, such as regular triangulation, triangulation using equilaterals etc. We decided to use regular triangulation due to the type of “morphing” we ended up using. Internally, we first generate a regular mesh of points covering the bounding box of the character, then test which points are “inside” the contour using the usual even-odd rule. This might not work 100% for border triangles, so in addition we test if triangles created from each 3 neighboring points cover at least one point on a contour. This gets us perfect results.</p><p>So, the picture with regular triangulation now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*wVZBFFcn621Xkgcm6kw-Zw.png" /></figure><p>Now for those of you experienced with computer graphics you probably understand why this is needed. We basically render individual triangles covering the character using WebGL and change shape of these triangles according to some method making character bending look realistic. This way we provide an illusion that the character is changing its shape naturally, while we just render triangles that adjust their shape and the texture mapping does the trick for us.</p><p>In the editor itself, we allow you to place pins at portions of your character corresponding to vertices of triangulation grid. Then you can navigate to some time and move these pins as you like. The shape will update as you do that. Here you can see 5 pins, three moving hands and top of head, two keeping nose and bottom edge at the same place; blue dots show origin of movement and green dots destination while the yellow pins show the current position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*kCqUse2YNZ8598PFHY37fg.png" /></figure><p>One of the methods you can use for moving triangles (and which we actually use here) is physics simulation with <a href="http://www.cs.rpi.edu/~cutler/classes/advancedgraphics/S09/lectures/06_mass_spring_systems.pdf">mass-spring networks</a>. This simulation method is extremely popular among game developers to simulate cloth, hair, particle systems, collision deformation etc. and even some structural engineers use it, though its origins are in biological systems in simulation of proteins. It’s a very fast and stable method these days.</p><p>To explain how it works, we first talk real physics! Let’s look at a spring and its properties. Each spring has what we call rest state, which is the state the spring is naturally in and in which no internal forces exist. Each spring also has a stiffness property, let’s call it <em>k</em>, which is some ratio how much force do we need to actuate spring movement. This can be summarized by <a href="https://en.wikipedia.org/wiki/Hooke%27s_law">Hooke’s Law</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*Y0xCWrAwrNtx0iRkI2edEg.png" /></figure><p>This says that the force needed to expand/shrink a spring is proportional to the expanding/shrinking distance <em>x</em> from its resting state length. As any simple physics formula, this one also has a catch — it works only for very small values of <em>x</em>. But like most high-school physicists, we will use it anyway!</p><p>Spring forces act outwards if we try to squeeze the spring and inwards if we try to stretch it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpMWRSkOYw0Iv1cLatEceQ.png" /></figure><p>What we do is that we link all neighboring points in our triangulation grid with these springs. We actually link them in this fashion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*dbfmXgQfMtAAHm0qQICEKw.png" /></figure><p>Each side of a rectangle is a spring, and there are two additional springs, one for each diagonal, to keep it stable. Now you probably understand why we chose to use regular triangulation.</p><p>Our picture then has an undergoing physical layer that responds to the movement of actuating pins in the same way a set of springs would. The actuating pins, which you inserted in the editor, are causing the movement and all the other points to adjust according to spring network behavior. All grid points also have the same mass. This is what makes the image deformation seem somewhat realistic. Of course, this model is simplistic, it only has one 2D spring layer whereas with normal objects you’d expect to have some 3D structure, however for many cases this is good enough for the purpose of animation.</p><p>Alongside stiffness we also use damping acting against the spring movements proportional to spring’s internal velocity. This allows us to control the amount of oscillations — low damping creates large oscillations, high damping removes them.</p><p>Material-wise, if we set both stiffness and damping to low values, we get a behavior similar to liquids. If we set both to medium values, we get fabrics-like behavior. If we set both stiffness and damping to high values, we get a rigid material behavior (however here the stability of computations might decrease along areas where material might break). By default, we set it to above average stiffness and below average damping to behave more like a rubber layer.</p><p><em>The algorithm and math to compute physics is as follows:</em></p><p>First, the spring force exerted on end points <em>pi</em> and <em>pj</em> could be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*ve3QLQmJzkj4OkjE_bWGNw.png" /></figure><p>where <em>k</em> is the spring stiffness, <em>lij</em> is the current distance between <em>pi</em> and <em>pj</em>, <em>rij</em> is the rest length of spring, or the original distance between <em>pi</em> and <em>pj</em> and <em>dij</em> is the unit direction of the vector between <em>pi</em> and <em>pj</em>. You need to make sure the direction <em>dij</em> corresponds to the expected behavior at each endpoint, i.e. the force needs to go inward the spring if the current length is larger than rest length and outwards if it’s the other way round.</p><p>As for damping, with the need to slow down the current movement, the force exerted on a point <em>pi</em> is simply proportional to point’s velocity <em>vi</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*NLTLwlGJlgnBoHiNHKQglA.png" /></figure><p>The overall force on a point will be then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*bGIG_klv4q4Ii6efn86bbA.png" /></figure><p>where <em>N(i)</em> are all neighbors of <em>pi</em> connected to it via springs. We can afford to ignore mass as we assume all points have the same mass, so we can just pretend it could be also unit mass. We can then assume our computed forces correspond to individual point accelerations.</p><p>For each time step, the algorithm starts with first moving actuating pins to their respective places at a given time, then computing all forces in all springs and at last adding damping force; each point in the end will have a single vector which will be the sum of all forces exerted on it from all the springs it is connected to.</p><p>Subsequently, in the second phase we need to compute the new positions for each point. Here we use <a href="https://en.wikipedia.org/wiki/Verlet_integration">Verlet integration</a> with constant step <em>dt</em>, a very simple yet very stable method for solving dynamics equations. This method doesn’t need to keep velocities, it rather computes them from the previous positions. The final positions will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*IAe4Q5GhV6r9SsoajIaLdA.png" /></figure><p>where <em>pi^n</em> is the position of <em>pi</em> in the simulation step <em>n</em> and <em>dt</em> is the integration step that should be small enough to provide stable solutions and large enough to make computation fast. This is the trick that makes cloth, hair and deformations fast and real-time in many current games while allowing you to adjust it to what your computing device is capable of.</p><p>If you want to learn more about physics beyond Hooke’s law and mass-spring systems, with real use in structural engineering or even rocket science, I recommend this <a href="https://www.edx.org/course/mechanical-behavior-materials-part-1-mitx-3-032-1x-0">MIT course</a>.</p><p>As described, we compute coordinates of points using this method in the editor. It seems however like something that could be slow when running in a browser, right? Mind you, browsers have a very simple <a href="https://www.opengl.org/">OpenGL</a> functionality in a form of <a href="https://www.khronos.org/registry/webgl/specs/1.0/">WebGL 1.0</a>, no <a href="https://www.opengl.org/wiki/Compute_Shader">compute shaders</a>, no <a href="https://www.opengl.org/wiki/Transform_Feedback">transform feedback</a> that could be used and JavaScript, despite recent advancements, is a far cry performance-wise from what you can get by using C++ in games or even on mobile devices.</p><p><em>How to make this fast then?</em></p><p>Well, we use a WebGL 1.0 shader trick. Instead of computing physics for every single frame during playback, we compute physics simulation in the editor only and store coordinates at certain key frames in the editor (such as whenever a new movement is initiated/ends and in some frames in between if the time between movements is too long) and player uses only these stored positions instead of computing anything. We then use a special vertex shader in WebGL that blends the coordinates to present an approximation of a shape at a given time. Our shader looks like this:</p><pre>#ifdef GL_ES<br>	precision highp float;<br>	#endif<br>	attribute vec2 initialShape;<br>	attribute vec2 finalShape;<br>	attribute vec2 textureCoordinates;<br>	varying vec2 finalTextureCoordinates;<br>	uniform float alpha;<br>	uniform mat4 projectionMatrix;</pre><pre>	void main()\n&quot; +</pre><pre>	    vec4 initialPosition = vec4(initialShape.x, initialShape.y, 0, 1);<br>	    vec4 finalPosition = vec4(finalShape.x, finalShape.y, 0, 1);<br>	    vec4 position = initialPosition * (1.0 - alpha) + alpha * <br>				  finalPosition;<br>	    finalTextureCoordinates = textureCoordinates;<br>	    gl_Position = projectionMatrix * position;<br>	}</pre><p>Here the initial shape is given by initialShape VBO, final shape in finalShape VBO and the blending amount in uniform alpha. Projection matrix is just for proper scaling/positioning of a 2D image within WebGL viewbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2FC8lFbgqmkIrlj8ew_yng.png" /></figure><p>An example — imagine you have character coordinates recorded at times 0s, 1s, 3s, 4s. Now you want to view shape corresponding to the state at 2.5s. You look at coordinate times and pick the pre-computed coordinates at time 1s as your initial shape, the coordinates at time 3s as your final shape. Next you compute alpha for time 2.5s, which is (2.5s — 1s) / (3s — 1s) = 0.75. Then you pass these into the shader and shader renders an approximated shape at time 2.5s. On the picture above, there is a depiction of this scenario — imagine the blue polygon is the state of the object at the time 1s, the black is the state at 3s. The red one is the interpolated one at 2.5s, having all vertices ¾ on the line between the blue and black ones.</p><p>So that’s it about puppet implementation I wanted to share with you!</p><p><strong>Alternative implementations</strong></p><p>You might want to consider using as-rigid-as-possible shape manipulation algorithm for moving triangles based on quadratic error metrics to minimize distortions of triangles both in rotation and scale. Benefits are that you can explicitly compute positions at any time without any kind of physics simulation and that the deformations seem to be more predictable, disadvantage is the need to handle large sparse matrices and their inverses in a browser, as well as sometimes looking less realistic. You can learn more about it in this <a href="https://www.coursera.org/learn/interactive-computer-graphics">interesting course from University of Tokyo</a>.</p><p><strong>Challenges</strong></p><p>- <a href="http://www.animatron.com/">Animatron</a> is written in Java using <a href="http://www.gwtproject.org/">GWT</a>; getting WebGL renderer working nicely was a major challenge fusing together WebGL, GWT’s native methods and JavaScript with very limited debugging possibility</p><p>- server-side rendering in our case is running on cloud machines without a GPU, hence we can’t use our WebGL renderer. Instead, we figured out a math trick allowing us to render the same quality with <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/2d/">Java2D</a> using <a href="https://docs.oracle.com/javase/7/docs/api/java/awt/TexturePaint.html">TexturePaint</a>. Yes, it’s possible, the animation shown at the beginning of this article is rendered this way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4be982747b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>