<?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 Ugurkan Ates on Medium]]></title>
        <description><![CDATA[Stories by Ugurkan Ates on Medium]]></description>
        <link>https://medium.com/@ugurkanates?source=rss-49f8ecb2420a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ZScMk-BXgsLYDDbLWjzJ2g.png</url>
            <title>Stories by Ugurkan Ates on Medium</title>
            <link>https://medium.com/@ugurkanates?source=rss-49f8ecb2420a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ugurkanates/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[Understanding the virtual cameras]]></title>
            <link>https://ugurkanates.medium.com/understanding-the-virtual-cameras-6cda2bea5c41?source=rss-49f8ecb2420a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cda2bea5c41</guid>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Ugurkan Ates]]></dc:creator>
            <pubDate>Tue, 24 Nov 2020 22:06:57 GMT</pubDate>
            <atom:updated>2020-11-24T22:06:57.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Episode 1 : The Pinhole Menace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*d0G4hqLREbOWOrP_VxrV7w.png" /><figcaption><a href="https://www.imdb.com/title/tt0120623/">A Bug’s Life (1998)</a> by PIXAR</figcaption></figure><p><em>This series is mainly aimed for people who had trouble understanding basic principles of 3D Graphics,rendering(openGL-Vulkan beginners) and anyone who wants to learn more about Virtual Cameras. Most information presented is adapted from various sources. Please check from first episode if you just started !</em></p><h3>Pinhole Camera Model</h3><p>Did you the word camera comes from latin word “room” ? It camera obscura (“dark chamber”). Why you might ask , don’t worry you are about to find out. The desire to record and preserve images is old as civilization itself. The term stands for a practical device that could harness the image-transferring property of light.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4bFLQBtlEfBHlK7R3NE6w.png" /><figcaption>Illustration for pinhole camera model from the history.</figcaption></figure><p>The principle of the camera obscura can be demonstrated with a rudimentary type, just a box(which may be room-sized , or even hangar sized) with a hole in one side. Light from only one part of a scene will pass through the hole and strike a specific part of the back wall. The projection is made on paper on which an artist can then copy the image. Folks at Pixar actually demonstrated this concept on real world.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe1NSlwChJJ0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De1NSlwChJJ0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe1NSlwChJJ0%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/48d075666e41a569b9d4298f17797738/href">https://medium.com/media/48d075666e41a569b9d4298f17797738/href</a></iframe><p>Concepts you should be aware of regarding to this model :</p><p><strong>Image Plane </strong>, represent image sensor of the film. In example video above opposite/back wall , the area gets the lights.</p><p><strong>Amount of light</strong>, how much rays we fire in virtual environment or in this video the all mighty sun (praise it ! ).</p><p><strong>Aperture</strong>, Just to nit-pick: Apertura means “opening” or “hole”. “To open” (infinitive) in Latin is aperī́re. In example it’s tiny hole that let’s lights go through image plane. In order to actually see things (not just bright white wall) we have to make it small as pinhole so only certain ray lights will go through. Aperture filters out any rays that doesn’t come from correct direction.</p><p><em>Question &amp; Answer = Why the images look reverse in this model ?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN6oRqzG3V4pZs40gNI05Q.png" /><figcaption>Answer = It’s obvious isn’t it ?</figcaption></figure><p><em>Question &amp; Answer = How does changing aperture value (while keeping same amount of rays) affects the image ?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*V43tbtmnQQ_pQJbs0hrv2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*XyhBiZZ5vYQUH1aul84ayw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*fibWNAMeXP5WdKTM42pfuA.png" /><figcaption>Low — Medium — High Aperture values.</figcaption></figure><p>As we increase value image gets brighter and kinda looks bigger because of this situation. Decreasing the size of the aperture makes the image <strong>dimmer </strong>because light reaches the image plane <strong>less.</strong></p><p>Decreasing the size of the aperture makes the image<strong> less blurry</strong>. Why you might ask ?</p><p>The light hitting each point in the image plane comes from a narrower range of points in the scene.</p><p><strong>Focal Distance</strong></p><p>Stands for distance between “<strong>pinhole</strong>” and “<strong>image plane</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*Hex82ef47_DJnzhUPJeI_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*ek2CpZSfSYcNiJIZIFAOaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*0QJZr4_k90HUnpjGbJlrpA.png" /><figcaption>Changing focal distance effects field of view.</figcaption></figure><p>As you can see from images increasing focal distance value makes image “more zoomed” but. you capture less things. Which means your FOV(field of view is narrowed and objects appear bigger.</p><p>If we decrease then we see smaller objects and more of the scene at same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQawcwODB6JHx-LyTsjmDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Gj8bfPCK7KEWTxwL585Bxw.png" /><figcaption>Wide FOV ( smaller FD) — Narrow FOV ( larger FD)</figcaption></figure><p>Increasing the focal length also causes images to appear <strong>dimmer</strong>.This is because the rays of light are <strong>more</strong> spread out by the time they hit the image plane.</p><p>Next episode we will talk about lenses,depth of field and more !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cda2bea5c41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpaceX Falcon 9 Roketini RL kullanarak indirmek !]]></title>
            <link>https://medium.com/reinforcementlearningturkiye/spacex-falcon-9-roketini-rl-kullanarak-indirmek-d4e6276a4b9d?source=rss-49f8ecb2420a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e6276a4b9d</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[yapay-zeka]]></category>
            <category><![CDATA[derin-ogrenme]]></category>
            <category><![CDATA[spacex]]></category>
            <category><![CDATA[roket]]></category>
            <dc:creator><![CDATA[Ugurkan Ates]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 11:18:52 GMT</pubDate>
            <atom:updated>2020-06-28T19:14:56.686Z</atom:updated>
            <content:encoded><![CDATA[<h3>SpaceX Falcon 9 Roketini RL kullanarak indirmek !</h3><h3>Tekrar Kullanılabilir Roketler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*jwBL9VvAK385aQJV.jpeg" /><figcaption><a href="https://cosmosmagazine.com/space/launch-land-repeat-reusable-rockets-explained/#:~:text=The%20Falcon%209%20first%2Dstage,Fuel%20tanks%3A&amp;text=These%20engines%20fire%20again%20as%20the%20rocket%20nears%20the%20landing%20platform.">cosmosmagazine.com </a>Roketlerle ilgili daha detaylı bilgi almanız için</figcaption></figure><p>Falcon 9, havacılık ve uzay şirketi SpaceX tarafından geliştirilip üretilen bir roket modeli. Bu roketi özel kılan şey ise kalkışta bundan önce her kalkışta kalkış sonrası çöpe atılan ve milyonlar kaybedilen ilk aşama kapsülünü hasarsız biçimde yere indirebilmesi.</p><p>Bir zamanlar inanılmaz derece uçuk gelen bu başarı “düz dünya toplulukları” gibi inanmayanları bir araya toplamıştı fakat 30&#39;dan fazla atıştan sonra bu arkadaşlar ortalıktan kaybolup gittiler.</p><p>Bugün size roket mühendisliği verecek kapasite de değilim fakat bunun inanılmaz bir mühendislik başarısı olduğunu görmek içinde buna gerek yok. Aşağıda ki diagramda roketin aşamalarını inceleyebilirsiniz. Daha detaylı anlatım içinde bir video bıraktım.</p><figure><img alt="Detaylı video anlatım https://www.youtube.com/watch?v=Wn5HxXKQOjw" src="https://cdn-images-1.medium.com/max/1024/0*Msp5WmafP11Enanx.jpeg" /><figcaption>Detaylı video anlatım <a href="https://www.youtube.com/watch?v=Wn5HxXKQOjw">https://www.youtube.com/watch?v=Wn5HxXKQOjw</a></figcaption></figure><p>Bilinen hiçbir <strong>SpaceX</strong> roketinde<strong> AI</strong> teknolojileri henüz kullanılmıyor. Bunun sebebi <strong>AI </strong>teknolojilerinin henüz doğrulanmasının düzenli ve sistematik şekilde yapılamaması ve kanıtlanma konusunda eksiklerinin olması. Bu tarz milyar dolarlık projelerde ne yapacağı belli olmayan teknolojiler yerine inanılmaz derece net ve kanıtlabilir &amp; tekrarlanabilir teknolojiler <strong><em>(klasik robotik ve kontrol teorisi yöntemleri)</em></strong> tercih ediliyor. Bu sebepten dolayı eğer bu alanlara ilgiliniz varsa klasik yöntemleri AI ile birlikte öğrenmenizi tavsiye ederim.</p><p>Genede biraz eğlence biraz da RL algoritmalarıyla elimizi ısındırmak amaçlı üretilen bu simülasyonda roket indirmeye kalkarsak ne olur ?</p><h3>Simülasyon Ortamı</h3><p><em>Pekiştirmeli Öğrenmeye yeniyseniz internette ve sayfamızda bulunan kaynaklara göz atmanızı öneririm. Bu yazıda belli başlı </em><strong><em>derin öğrenme , RL ve matematik </em></strong><em>kavramlarına hakim olduğunuz varsayılacaktır.</em></p><p>Sevgili <strong><em>Sven Niederberger(@EmbersArc GitHub)</em></strong><em> </em>isimli arkadaşımız kısa bir süre önce bugün işleyeceğimiz zorlu Reinforcement Learning simülasyon ortamını hazırladı , kendisine teşekkür ediyorum buradan . Bunu yaratmasında ki amaç eğlenceli/gaza getirici bir ortam oluşturmakken zamanla ortamın zorluğundan dolayı benchmark/algoritmalarınızı denemetaşı haline geldi. <strong>LunarLander</strong> ortamından esinlenerek yapılmasına rağmen rastgele başlama noktaları sebebiyle çok daha zor olduğu fark edildi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*KFcjtsIwcqyWhhY1.png" /><figcaption><a href="https://mc.ai/solving-lunar-lander-openaigym-reinforcement-learning/">Lunar Lander ortamını açıklayan bir görsel</a></figcaption></figure><p>LunarLander simülasyon ortamının 2 versiyonu bulunmakta.</p><p>Bunlardan biri <strong>diskrit aksiyon ortamı</strong> için diğeri ise<strong> sürekli devam eden</strong></p><p><strong>aksiyon ortamları</strong> için özelleştirilmiş.</p><p>Aksiyon değeri 2 reel sayı tutan vektör ve değer aralıkları -1 ile +1 arasında değişmekte.</p><ul><li>Ana kontrol motoru , -1..0 kalkış, 0..+1 güç alma 50% ‘den 100% güce kadar.Motor 50% altında güçlerde çalışmamakta.</li><li>İkinci değer -(1.0..-0.5) sol motoru ateşlemek için gerekli değer , (+0.5..+1.0 )sağ motoru ateşlemek için alınması gereken değer (-0.5..0.5)</li></ul><p>Ortamın diskrit aksiyon versiyonu sürekli kontrol versiyonuna göre daha kolay çözülebilmekte. Değer tabanlı methodlar ( DQN,Rainbow DQN, Duel DQN, Gorilla DQN, C51 gibi) bir yapay sinir ağıyla birleşip linear olmayan fonksiyon tahmini yapabiliyor. ( Diskrit aksiyon listesi aşağıda bulunuyor)</p><ul><li>0– Hiçbir şey yapma</li><li>1– Sol Motoru Ateşle</li><li>2– Aşağı Motoru Ateşle</li><li>3– Sağ Motoru Ateşle</li></ul><p>Fakat sürekli aksiyon değerleri kullanarak çözmek içinse çok daha komplex methodlara ihtiyacımız var. Bunun sebebi çok az seviyede yararlı ödül sinyali almak , ajanların etrafı gezmesinin zorlaşması ve DQN tarzı methodların stabil olmamasından kaynaklanıyor.</p><p><strong>PPO+LSTM + Paralel Train</strong>(on policy method,cluster tarzında eğitim), <strong>Soft Actor Critic</strong>(SAC,off policy), <strong>DDPG</strong> ve <strong>D4PG</strong>(off policy- hibrit actor critic methodlar) bu algoritmalar problemin çözümünde kullanabilir. Politika tabanlı methodlara girecekseniz LSTM ve Attention mekanizmaları gibi yeni yeni pekiştirmeli öğrenmeyle birleştirilen konulara bakmanızı tavsiye ederim.Bu tarz çalışmalarınızı makale haline getirip SOTA ( state of the art, son teknoloji gibi düşünebilirsiniz) bile olabilirsiniz.</p><p>Bizim kullanacağımız Roket simülasyonu Box2D fizik motorunu kullanıyor ve genel olarak yapısı LunarLander ortamına benzemekte . Ortamı görüntülendirmek için openGL render motoru kullanılıyor fakat resimlerle eğitim yapılmıyor sadece görsel olarak size yardımcı olmak için eklenmiş</p><h3>ORTAM DEĞİŞKENLERİ</h3><p>Ortamda ajanımıza bilgi verecek bilgiler aşağıda ki gibi:</p><ul><li>X pozisyonu</li><li>Y pozisyonu</li><li>Açı</li><li>Birinci ayak yere değme noktası belirteci</li><li>İkinci ayak yere değme noktası belirteci</li><li>Ateşleme değeri</li><li>Motor Gimbal Değeri</li></ul><p>Eğer <strong>VEL_STATE</strong>(kod içerisinde) doğruya çekilmişse bunlara ek olarak aşağıda bulunan hız değerleri de ekleniyor:</p><ul><li>X yönünde ki hız</li><li>Y yönünde ki hız</li><li>Açısal hız</li></ul><p><strong>Gözlemler</strong> bizim direk ajanı eğitmemiz için<strong> kullanışlı şekilde</strong> tasarlanmış.Fizik simülasyonundan alınan yukarda ki bilgiler ile ajanı rahatlıkla eğitip <strong>CNN</strong> gibi görsel veri üzerinden bilgi çıkarmamıza gerek kalmayacak. Ortam zaten yeterince zorlu , görsel veriyle uğraşsak bilgisayar gücü anlamında bayğaı zorlanacaktık. Amacımız <strong>kontrol mühendisliği / robotik </strong>açısından bunun gerçekliğini göstermek ve roketi indirmek olduğu için full bir sistem yapmak yerine görsel veri olmaması bizim işimize yarıyor.</p><p>Hız değerleri ile ilgili iki opsiyonuda denedim ve büyük bir fark olmamasına rağmen hız değerlerini aktif etmenizi öneririm. Ajanın öğrenmesi için <strong>gerekli ne kadar fazla bilgi olursa o kadar iyi</strong>.</p><p>Tüm değerler sistemin eğitiminde hızlı olması için normalize (sayılar) edildi.</p><p><strong>Ödül hesaplaması </strong>aşağıda anlatıldığı üzere yapılıyor.Kod üzerinden de inceleyebilirsiniz. Roketin benzin bilgisi, göreceli pozisyon , ağırlık gibi bilgiler <strong>roket mühendisliği ve fizik kanunlarınca</strong> düşünülüp hangi durumlarda başladığına göre size göreceli bir ödül sinyali veriliyor. Simülasyon her başladığında sizi rastgele yerlerde başlatacağı için bu sistem zorunlu hale geliyor. Çünkü rastgele zorlu pozisyonlardan havadan atılldığınızda bile kurtulmanız için ödül sinyallerini alabilmeniz gerekiyor</p><pre># state variables for rewardif outside or brokenleg:if self.game_over:if landed:if done:<br> distance = np.linalg.norm((3 * x_distance, y_distance)) # weight x position more<br> speed = np.linalg.norm(vel_l)<br> self.game_over = True <br> done = True<br> self.landed_ticks += 1<br> reward += max(-1, 0-2 * (speed + distance + abs(angle) + abs(vel_a)))<br> elif not groundcontact:<br> reward -= 0.25 / FPS <br> else:<br> self.landed_ticks = 0<br> if self.landed_ticks == FPS:<br> reward = 1.0<br> done = True <br> else:<br> # reward shaping<br> shaping = -0.5 * (distance + speed + abs(angle) ** 2)<br> shaping += 0.1 * (self.legs[0].ground_contact + self.legs[1].ground_contact)<br> if self.prev_shaping is not None:<br> reward += shaping - self.prev_shaping<br> self.prev_shaping = shaping <br> groundcontact = self.legs[0].ground_contact or self.legs[1].ground_contact<br> brokenleg = (self.legs[0].joint.angle &lt; 0 or self.legs[1].joint.angle &gt; -0) and groundcontact<br> outside = abs(pos.x - W / 2) &gt; W / 2 or pos.y &gt; H<br> fuelcost = 0.1 * (0 * self.power + abs(self.force_dir)) / FPS<br> landed = self.legs[0].ground_contact and self.legs[1].ground_contact and speed &lt; 0.1<br> done = False reward = -fuelcost reward = np.clip(reward, -1, 1)</pre><h3>Kontrol Girdileri</h3><p><em>Diskrit kontrol girdileri </em>:</p><ul><li>Gimbal’i sola yatırma değeri</li><li>Gimbal’i sağa yatırma değeri</li><li>Yukarı Ateşleme Değeri</li><li>Aşağı Ateşleme Değeri</li><li>İlk ateşleyicilerin kullanılma değeri</li><li>İkinci ateşleyicilerin kullanılma değeri</li><li>Hiçbir şey yapma</li></ul><p><em>Sürekli hareket için kontrol girdileri </em>:</p><ul><li>Gimbal’i açısal olarak <strong>SOL/SAĞ</strong> yatırma değeri</li><li>Ateşleyicileri <strong>YUKARI/AŞAĞI</strong> kaldırma değeri</li><li>Kontrol ateşleyicilerinin<strong> SOL/SAĞ</strong> değeri</li></ul><p>Problem için 3 algoritma denedim. <strong>D4PG,SAC ve PPO </strong>. Her birinde yaşadığım deneyimlerini anlatacağım , tüm kodları repository üzerinden erişebilirsiniz , kod anlatımı yapmayacağım tek tek , daha çok ne tarz şeylere dikkat etmeniz gerekiyor bu kodları kullanırken buna değinmeye çalışacağım. <strong>Sürekli kontrol üzerinde </strong>çalıştım , <strong>diskrit aksiyon </strong>üzerine modifiye ederek kullanabilirsiniz</p><p>Tüm ajan kodları için PTan isimli PyTorch kütüphanesini kullanıyorum , sizede önerebilirim. Çoğu loglama,ajanların networklerini ayağa kaldırma , trajectory düzenlemesi ve birçok konuda yazılan sıkıcı kodlarla uğraşmamanızı sağlıyor. Bunun yerine önceden test edilmiş kodları kullanmanız zaten zor olan işi kolaylaştırmaya bir nebze yarıyor.</p><p>PyTorch AgentNet = <a href="https://github.com/Shmuma/ptan">https://github.com/Shmuma/ptan</a></p><h3>D4PG ( Distributed Distributional Deep Deterministic Policy Gradient)</h3><p>DDPG ve D4PG algoritmaları arasında ki küçük bir fark ortamı nasıl keşfettiklerine dayanıyor. <strong>DDPG</strong> algoritması <strong>Ornstein-Uhlenbeck Process </strong>adını verdiğimiz sistemi kullanıyor bu hesaplaması kompütasyon olarak daha zorlayıcı ve kodu karışıklaştıran bir yapı <strong>D4PG </strong>daha basit olan <strong>simple random normal(Gaussian) distribüsyonunu kullanıyor<em>.</em></strong></p><pre>GAMMA = 0.99<br>BATCH_SIZE = 64<br>LEARNING_RATE = 1e-4<br>REPLAY_SIZE = 100000<br>REPLAY_INITIAL = 10000<br>REWARD_STEPS = 5<br>TEST_ITERS = 1000<br>Vmax = 10<br>Vmin = -10<br>N_ATOMS = 51<br>Hyper Parameters for D4PG</pre><p>D4PG algoritmasıyla çalışan ajanı 1 milyon adım eğittimde sonuçların yeterince iyi olmadığını ve lokal optimaya takıldığını gördüm. Burda bir ilerleme olmayınca ajanı kaydedip diğer algoritmalara geçtim, aşağıda son hallerinden bir video bulunmakta. Bu algoritmanın (veya herhangi bir RL algoritmasının) eğitiminde hyper parametrelerle iyi oynamanız gerekebiliyor . Kodu ekledim ilgilenen ve benden iyi sonuç alacak arkadaşlar çıkabilir aramızdan .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsPZiYrf04_8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsPZiYrf04_8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsPZiYrf04_8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/361d2f03fd2a77239f96eaa4cc4ed997/href">https://medium.com/media/361d2f03fd2a77239f96eaa4cc4ed997/href</a></iframe><p><strong>Soft Actor Critic (SAC)</strong></p><p>SAC şuan çıkmış model bağımsız algoritmalar arasında en iyilerinden biri. Özellikle sürekli hareket problemlerinde üstünden zaman geçmesine rağmen en iyilere kafa tutabilmekte. Özellikle getirdiği yenilikler şöyle:</p><p><strong><em>Entropy Regülasyonu </em></strong>= Ajanın bir yere takılıp kalmaması için ne kadar kararsız olursa belirli bir bonus ödül alıyor. Buda lokal optimalara takılmamayı sağlıyor</p><p><strong><em>Double Q Hilesi</em></strong>= Normalde eğitilen tek Q network(target gene aynı network amaçlı kullanılıyor) yerine tamamen ayrı 2 network ve bunların target networkları olan 2 network daha kullanılıyor. Bu değerlerden en küçük 2 tanesini seçip Bellman tahmin hesaplamasında bu değeri kullanıyorsunuz. Buda daha stabil bir eğitim süreci sağlıyor.</p><p>Bu algoritma daha muhafazakar politika değişimi(daha az değişiyor yani ani şeyler yapmıyor , kısıtlı) üzerine kurulmuş olan ( TRPO,PPO gibi) algoritmalar ile aynı yapıyı kullanıyor. Sadece fark olarak “toplam maksimum ödül” optimize etmekle kalmayıp <strong>kararsızlığıda maksimum hale optimize etmeye </strong>çalışıyor</p><p>Bu sadece hem <strong>politika tabanlı methodlar gibi stabil eğitiliyor </strong>, hemde <strong>değer tabanlı algoritmalar gibi eski deneyimleri </strong>kullanabiliyor ve daha kısa sürede eğitilebiliyor.İki tarafın en iyi yönleri yani</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*nOKT8w0l5X2_aAvi.png" /><figcaption>Rastgele noktalardan kurtulmak zor olduğu için bazen düşük ödül alınıyor</figcaption></figure><p><strong>Roket Ortamı- Simülasyonu </strong>oldukça kompleks bir yapı, gerçek dünyaya göre özellikle daha karışık çünkü bir roketin rastgele hızlar ve konumlardan bırakılması felaket olabilirdi.</p><p>Ajanınızı eğitirken bunu göz önünde bulundurmanız gerekir yani bazı noktalardan kendini toparlayamaması normal. İsterseniz parametrelerle oynayıp daha<strong> gerçekçi</strong> , sadece belirli noktalardan bırakılan roket tasarlayabilirsiniz, kod üzerine oynama yapmanız gerekir.</p><p>Benim eğittiğim ajan 1 milyon adım aldı ve başarılı iniş yapabiliyordu.TESLA P100 (16GB VRAM and 21 TFlops of 16bit sistemi ile eğittim).</p><pre>GAMMA = 0.99<br>BATCH_SIZE = 64<br>LR_ACTS = 1e-4<br>LR_VALS = 1e-4<br>REPLAY_SIZE = 100000<br>REPLAY_INITIAL = 10000<br>SAC_ENTROPY_ALPHA = 0.1<br>TEST_ITERS = 10000<br>Hyper parameters for Soft Actor Critic</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwxDb52vyS_Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwxDb52vyS_Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwxDb52vyS_Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c7ea9c37bc8f17e28068fc64984a6e2/href">https://medium.com/media/3c7ea9c37bc8f17e28068fc64984a6e2/href</a></iframe><h3>PPO — Policy Proximal Optimization</h3><p>PPO artık 3 yaşını almış eski bir algoritma ama hala bu tarz problemlerde ilk denenen algoritmalardan. Oldukça az değişkeni olduğu için optimal noktayı bulması kolay olabiliyor eğer yeterince eğitirseniz. Her zaman aklınızda olması gereken bir algoritma bu tarz problemlerde.</p><pre>GAMMA = 0.99<br>GAE_LAMBDA = 0.95<br>TRAJECTORY_SIZE = 4097<br>LEARNING_RATE_ACTOR = 1e-5<br>LEARNING_RATE_CRITIC = 1e-4<br>PPO_EPS = 0.2<br>PPO_EPOCHES = 10<br>PPO_BATCH_SIZE = 256<br>TEST_ITERS = 100000<br>Hyper Parameters for PPO</pre><p>Bu sefer diğer problemlere göre sınırları zorlamak istedim ve daha büyük bir trajeksiyon sayısı seçtim yani herhangi bir hesaplama yapmadan önce daha çok adım alacaktı. Bu bilgisayar gücü olarak yorucu bir iş ama ne tarz sonuç alacağımı görmek istedim ve sistemi 6 milyon adım eğittim</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*r712mFtCmXalliDw.png" /><figcaption>Fena olmayan inişler yapabiliyor eğitim sonu</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz-j82WmZojY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz-j82WmZojY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz-j82WmZojY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5acad846e4bb8e4ad106c411da6f1604/href">https://medium.com/media/5acad846e4bb8e4ad106c411da6f1604/href</a></iframe><h3>Sonuç ve Düşünceler</h3><p>Öncellikle herkese <strong>PTAN </strong>kütüphanesi ile haşır neşir olmasını öneriyorum. Çoğu sıkıcı ama gerekli olan sistemi (terminal durumlarda kontrol edilmesi,çoklu paralel eğitme, loglama vs) her şeyi içinde bulunduruyor. Sizin yapmanız gereken ajanınızı implement etmeniz.</p><p>Kendi ajanlarınızı oluşturabilirsiniz veya benimkilerin parametrelerini değiştirebilirsiniz.</p><p>Eğlenceli bir deneyim oldu benim için ,gerçekten zorlayıcı ve dinamik bir problem.Roketlerin rastgele noktalardan başlaması zorlayıcı ve eğitimde lokal optimalara sebep olabilyior. En stabil PPO ‘yu buldum sonra SAC ve en kötü olarak D4PG büyük olasılıkla benim beceriksizliğimden dolayı bu sonuçlar oldu :) , bu blog postunun ingilizce versiyonuda profilimde bulunmaktadır</p><p>GitHub repomdan kodlara erişebilirsiniz , ayrıca Google Colab üzerinde notebooklar oluşturdum bunlarla başlayabilirsiniz. Video kayıt ve loglama opsiyonları açık rahatça eğitimi izleyebilirsiniz.Anlamadığınız bir konu olursa bana ulaşabilirsiniz , README üzerinde kod kullanımı detaylı anlatılmaktadır. (repoya star atmayı unutmayın :)</p><p><a href="https://github.com/ugurkanates/SpaceXReinforcementLearning">https://github.com/ugurkanates/SpaceXReinforcementLearning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e6276a4b9d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/reinforcementlearningturkiye/spacex-falcon-9-roketini-rl-kullanarak-indirmek-d4e6276a4b9d">SpaceX Falcon 9 Roketini RL kullanarak indirmek !</a> was originally published in <a href="https://medium.com/reinforcementlearningturkiye">Reinforcement Learning Turkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpaceX Falcon 9 Landing with RL]]></title>
            <link>https://medium.com/data-science/spacex-falcon-9-landing-with-rl-7dde2374eb71?source=rss-49f8ecb2420a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dde2374eb71</guid>
            <category><![CDATA[control]]></category>
            <category><![CDATA[rockets]]></category>
            <category><![CDATA[spacex]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ugurkan Ates]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 10:26:40 GMT</pubDate>
            <atom:updated>2020-06-30T13:41:28.775Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reusable rockets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*gnVtfUTP_QMrlN4hnky68g.jpeg" /><figcaption><a href="https://cosmosmagazine.com/space/launch-land-repeat-reusable-rockets-explained/#:~:text=The%20Falcon%209%20first%2Dstage,Fuel%20tanks%3A&amp;text=These%20engines%20fire%20again%20as%20the%20rocket%20nears%20the%20landing%20platform.">cosmosmagazine.com </a>for more information about Rockets in general</figcaption></figure><p>The Falcon 9, developed by aerospace company SpaceX, means it is now possible to reuse the first-stage of the rocket, by flying it safely back to Earth.</p><p>An achievement once seemed so impossible that it lead creation of multiple “fake SpaceX landing videos-explanations” now is widely agreed upon about how amazing behind the tech related to it.</p><p>While today I’m not here nor capable of you giving rocket engineering course just wanted to show this quick little diagram from SpaceX to understand a little bit more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-yIJQth30F3sL2QhTz3YA.jpeg" /><figcaption><a href="https://www.inverse.com/article/33904-how-spacex-lands-a-falcon-9-rocket-in-6-steps">You can check more about in video form here</a> <a href="https://www.youtube.com/watch?v=Wn5HxXKQOjw">https://www.youtube.com/watch?v=Wn5HxXKQOjw</a></figcaption></figure><p>While none of AI techniques have been deployed to any of <strong>SpaceX</strong> tech pipeline (they are using classic-robotics/control theory way of <a href="https://en.wikipedia.org/wiki/Motion_planning">path planning </a>algorithms) it would be nice to see what would happen if we tried to solve the problem with<em> state of the art</em> <a href="https://en.wikipedia.org/wiki/Reinforcement_learning"><strong><em>Reinforcement Learning</em></strong></a><strong><em> </em></strong>algorithms.</p><h3>The Environment</h3><p><em>If you are new to RL I urge you to checkout other tutorials,books and resources for beginners relating to learning more about fundamentals of RL and the math about it.</em></p><p>Dear Sven Niederberger(<em>@EmbersArc on GitHub</em>) created this tough Reinforcement Learning environment some time ago. While in creation it’s main purpose was to create a nice attractive/hype GYM like environment using ideas from LunarLander envs , it quickly has been realized it’s way harder to solve in terms of RL than what was inspired for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*01PHi8ZCva2CKiErdThQ8g.png" /><figcaption>How does LunarLander works,<a href="https://mc.ai/solving-lunar-lander-openaigym-reinforcement-learning/">ref mc.ai</a></figcaption></figure><p>LunarLander has 2 versions. One designed for <strong>discrete action space</strong></p><ul><li>0– Do nothing</li><li>1– Fire left engine</li><li>2– Fire down engine</li><li>3– Fire right engine</li></ul><p>other for <strong>continuous action space</strong></p><p>Action is two real values vector from -1 to +1.</p><ul><li>First controls main engine, -1..0 off, 0..+1 throttle from 50% to 100% power. Engine can’t work with less than 50% power.</li><li>Second value -1.0..-0.5 fire left engine, +0.5..+1.0 fire right engine, -0.5..0.5 off.</li></ul><p>While discrete action one easily can be solved with Value based methods plus non linear functional approximation such as DQN,Rainbow DQN or Gorilla DQN , continuous action problem requires somekind of actor-critic based algorithm to work due sparse rewards, hard exploration and unstable nature of vanilla DQN methods.</p><p><strong>PPO+LSTM + paralel train</strong>(on policy,cluster style training), <strong>Soft Actor Critic</strong>(SAC,off policy), <strong>DDPG</strong> and <strong>D4PG</strong>(off policy- hybrid actor critic methods) can be used for solving this problem. Especially if you are going for a on policy methods I would urge to you take a look on parallelization and LSTMs(or Attention mechanisms for being SOTA?) with RL in general but that’s a topic for another day.</p><p>Our Rocket gym also uses most of things from LunarLander setup and it’s highly customizable structure.It uses Box2D as physics backend and openGL for light rendering of environment(images aren’t used in observations just there for checking your progress)</p><h4>STATE VARIABLES</h4><p>The state consists of the following variables:</p><ul><li>X position</li><li>Y position</li><li>Angle</li><li>First Leg Ground Contact Indicator</li><li>Second Leg Ground Contact Indicator</li><li>Throttle</li><li>Engine Gimbal</li></ul><p>If <strong>VEL_STATE</strong>(in code) is set to true, the velocities are included:</p><ul><li>X velocity</li><li>Y velocity</li><li>Angular velocity</li></ul><p><strong>Observations</strong> are very useful <strong><em>extracted features </em></strong>from physics simulation as such you wouldn’t waste most of your computing power on <em>CNN’s</em> to extract them hence our purpose to create a meaningful <strong><em>robotics/control algorithm replacement</em></strong> rather than full blown system.</p><p>I have tried both options while there’s is no big difference I would suggest you to turn on Velocity States for more information , it helps with agent learning , hence <strong><em>more relevant info better mentality</em></strong>. Be note all values has been normalized for smooth training process.</p><p><strong>Reward calculation</strong> is explained in this little snippet code. Basically takes fuel cost and your relative position to ground and rocket of weight to understand how correct your landing was done in terms of control mechanics and physics. Because you might not get a easy situation due random spawning but if you still recovered from that state you should get a decent reward signal</p><pre># state variables for reward<br> distance = np.linalg.norm((3 * x_distance, y_distance)) # weight x position more<br> speed = np.linalg.norm(vel_l)<br> groundcontact = self.legs[0].ground_contact or self.legs[1].ground_contact<br> brokenleg = (self.legs[0].joint.angle &lt; 0 or self.legs[1].joint.angle &gt; -0) and groundcontact<br> outside = abs(pos.x — W / 2) &gt; W / 2 or pos.y &gt; H<br> fuelcost = 0.1 * (0 * self.power + abs(self.force_dir)) / FPS<br> landed = self.legs[0].ground_contact and self.legs[1].ground_contact and speed &lt; 0.1<br> done = False</pre><pre>reward = -fuelcost</pre><pre>if outside or brokenleg:<br> self.game_over = True</pre><pre>if self.game_over:<br> done = True<br> else:<br> # reward shaping<br> shaping = -0.5 * (distance + speed + abs(angle) ** 2)<br> shaping += 0.1 * (self.legs[0].ground_contact + self.legs[1].ground_contact)<br> if self.prev_shaping is not None:<br> reward += shaping — self.prev_shaping<br> self.prev_shaping = shaping</pre><pre>if landed:<br> self.landed_ticks += 1<br> else:<br> self.landed_ticks = 0<br> if self.landed_ticks == FPS:<br> reward = 1.0<br> done = True</pre><pre>if done:<br> reward += max(-1, 0–2 * (speed + distance + abs(angle) + abs(vel_a)))<br> elif not groundcontact:<br> reward -= 0.25 / FPS</pre><pre>reward = np.clip(reward, -1, 1)</pre><h4>CONTROL INPUTS</h4><p><em>Discrete control inputs</em> are:</p><ul><li>Gimbal Left</li><li>Gimbal Right</li><li>Throttle Up</li><li>Throttle Down</li><li>Use First Control Thruster</li><li>Use Second Control Thruster</li><li>No Action</li></ul><p><em>Continuous control inputs</em> are:</p><ul><li>Gimbal (Left/Right)</li><li>Throttle (Up/Down)</li><li>Control Thruster (Left/Right)</li></ul><h3>Creation of the Agent</h3><p>I have tried 3 algorithms for this problem. <strong>D4PG,SAC and PPO </strong>with some modifications. I will talk briefly about each experience and results from them , you will able to find full codes for all 3 in repository. All of my agents done with continuous control inputs , feel free to check discrete case as well</p><p>For all agents I have used PTAN a pyTorch based RL library that eases setting up agents handling process such as logging,network creation,setting &amp; collecting up trajectories and more. I encourage to you to check out because most of time wasting time with boilerplate code is waste of time and prone to buggy code.While PTan isn’t plug&amp;train helps for what it’s set out to do.</p><p>PyTorch AgentNet = <a href="https://github.com/Shmuma/ptan">https://github.com/Shmuma/ptan</a></p><h4>D4PG ( Distributed Distributional Deep Deterministic Policy Gradient)</h4><p>One minor difference between DDPG and D4PG comes from action exploration. Instead of <strong>Ornstein-Uhlenbeck Process </strong>noise we just use a more <strong>simple random noise from normal(Gaussian) distribution<em> .</em></strong><em> </em>Calculating OU noise doesn’t seems to provide much yet it complefiy the code so I mostly prefer D4PG.</p><pre>GAMMA = 0.99<br>BATCH_SIZE = 64<br>LEARNING_RATE = 1e-4<br>REPLAY_SIZE = 100000<br>REPLAY_INITIAL = 10000<br>REWARD_STEPS = 5<br>TEST_ITERS = 1000<br>Vmax = 10<br>Vmin = -10<br>N_ATOMS = 51<br>Hyper Parameters for D4PG</pre><p>While I accidentally deleted TensorBoard logs of this run , I practically trained D4PG for 1 million steps and it seemed wasn’t converging from losses and stuck on some local optima. Still I have some video from it. I still included code for it maybe with different batch sizes and random seeds you can train more efficiently.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsPZiYrf04_8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsPZiYrf04_8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsPZiYrf04_8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/64464b0584a7ab98eb4b88affdd8eca5/href">https://medium.com/media/64464b0584a7ab98eb4b88affdd8eca5/href</a></iframe><p><strong>Soft Actor Critic (SAC)</strong></p><p>SAC is still one of SOTA algorithms in model free RL.In a nutshell it’s differences can be stated as</p><p><strong><em>Entropy Regularization </em></strong>= Getting more bonus reward at each time stamp proportional to entropy of policy at current step</p><p><strong><em>Double Q Trick</em></strong> = You have 2 networks predicting Q values , choosing minimum of them for Bellman approximation results you with more smooth training process.</p><p>This algorithm still builds up on conservative policy iteration ( TRPO,PPO etc). Instead of just maximizing lifetime awards it also tries to maximize entropy ( uncertainty in layman terms). So you can get best of both worlds , ability to <strong>learn efficiently from past experiences (experience replays</strong>) and <strong>more stable policy learning </strong>setup from on-policy methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*YdfWJdCI9l6YeMHNIFaWGw.png" /><figcaption>Randomization plays big part part on low rewards at start of training.</figcaption></figure><p><strong>Rocket Environment</strong> is very complex compared to real world situation due randomized nature , at each time step rocket can spawn in a state that’s very hard to recover even in real life. So you should always keep that in mind when evaluating this environment.You can modify environment to be more “<strong><em>realistic”</em></strong> aka a similar landing process to real life where it wouldn’t do a rush emergency landing but I used default ones.After a while rewards started to pick up and agent stuck itself mostly fine on most cases. This training took 1 million steps with TESLA P100 (16GB VRAM and 21 TFlops of 16bit performance).</p><pre>GAMMA = 0.99<br>BATCH_SIZE = 64<br>LR_ACTS = 1e-4<br>LR_VALS = 1e-4<br>REPLAY_SIZE = 100000<br>REPLAY_INITIAL = 10000<br>SAC_ENTROPY_ALPHA = 0.1<br>TEST_ITERS = 10000<br>Hyper parameters for Soft Actor Critic </pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwxDb52vyS_Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwxDb52vyS_Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwxDb52vyS_Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0092a941073e3af3d9e775e4ff01360a/href">https://medium.com/media/0092a941073e3af3d9e775e4ff01360a/href</a></iframe><h4>PPO — Policy Proximal Optimization</h4><p>PPO while outdone by some SOTA(state of the art) is still very useful algorithm to try on continuous control problems due easy to implement nature and very few hyperparams to change compared to other algorithms.</p><pre>GAMMA = 0.99<br>GAE_LAMBDA = 0.95<br>TRAJECTORY_SIZE = 4097<br>LEARNING_RATE_ACTOR = 1e-5<br>LEARNING_RATE_CRITIC = 1e-4<br>PPO_EPS = 0.2<br>PPO_EPOCHES = 10<br>PPO_BATCH_SIZE = 256<br>TEST_ITERS = 100000<br>Hyper Parameters for PPO</pre><p>I have went for a bigger trajectory this time and wanted to push my compute capabilities as much as possible in relative terms. I trained this network for 6 million steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*mGJ9VDp7p9b2ILGdoK3vjw.png" /><figcaption>It can do great landings depending on spawn trajectory.</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz-j82WmZojY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz-j82WmZojY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz-j82WmZojY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5acad846e4bb8e4ad106c411da6f1604/href">https://medium.com/media/5acad846e4bb8e4ad106c411da6f1604/href</a></iframe><h3>Conclusion and Thoughts</h3><p>I suggest you get familiar with<strong> PTan</strong> for very easy experiments on different algorithms, it allows you to keep track of rewards(handles terminal states etc fairly easy even on multiple env setups) since code heavily uses them. Of course you can use your own code with my hyper params as well.</p><p>This was a fun experience , it’s really hard and dynamic problem with randomization factor added in you can modify it to be less random and easier to solve obviously you also can make it harder. I found PPO most stable during training but SAC got good results way before PPO while D4PG failed on me, it might be due my parameter choices feel free to try your own version and write results.</p><p>You can access my repository which contains ready to train Google Colab notebooks , local train codes and saved models/logs. I also urge you to check Colab Pro which lets you train 24h on fast machines. In repository README you can find more about how to run code.</p><p><a href="https://github.com/ugurkanates/SpaceXReinforcementLearning">ugurkanates/SpaceXReinforcementLearning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dde2374eb71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/spacex-falcon-9-landing-with-rl-7dde2374eb71">SpaceX Falcon 9 Landing with RL</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[How to use your Android Device as OpenCV camera/video input device]]></title>
            <link>https://ugurkanates.medium.com/how-to-use-your-android-device-as-opencv-camera-video-input-device-4bb26f6006ef?source=rss-49f8ecb2420a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb26f6006ef</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ugurkan Ates]]></dc:creator>
            <pubDate>Tue, 29 Oct 2019 16:48:27 GMT</pubDate>
            <atom:updated>2019-10-29T16:48:27.388Z</atom:updated>
            <content:encoded><![CDATA[<p>with Python 3.6</p><p>Most of Computer Vision,Object Detection and Image processing related algorithms and projects requires HD or near HD pictures to be compute as intended. Since we have bunch of great picture taking devices in our hand why not combine both and be free of our bad laptop webcams.</p><p>This tutorial is aimed at Python3.5+ (Tested version currently works with Python3.6 , Ubuntu 18.04 LTS) . I saw a various tutorials about these both most of them didn’t work or was dependent on Python2 related libraries. Also it’s always better to use webcam if your hardware is capable of taking 5MP+ pics. <strong>Lets get started !</strong></p><p>Required packages for this tutorial <strong>numpy &amp; openCV</strong></p><blockquote>pip install opencv-python<br>pip install numpy</blockquote><p>We need IP WebCam or equivalent to install on our Android Device</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*vBZxiz-lZ5yrVSIs0bHGMg.png" /><figcaption>IP Webcam on Google Play Store (29 October 2019)</figcaption></figure><p><a href="https://play.google.com/store/apps/details?id=com.pas.webcam&amp;hl=en">IP Webcam - Apps on Google Play</a></p><p>You can download either from here or your favorite choice of store for .apk</p><p>Your <strong>PC and Mobile device</strong> needs to be connected to <strong>same network </strong>to work.</p><p>After installing app just scroll over to end of page and press <strong>Start server</strong></p><p>This will provide you with IP which you will use either for pictures or as video stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*wL1_pH3VGkMohHcMLNWnnw.png" /><figcaption>Your IP listed here , I use HTTP but you can use secure connection as well.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb572fa648448f1ed7cc83d59661ab07/href">https://medium.com/media/cb572fa648448f1ed7cc83d59661ab07/href</a></iframe><p>If you want to use only images rather than stream just disable <strong>ANDROID_AS_VIDEO.</strong></p><p>Be aware , your device may output revert picture or wrong camera preference , which all can be configured from android app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*JgCB1EKHvJn7Z9GiM-rcow.png" /><figcaption>Me testing my Python code with Samsung Android tablet.</figcaption></figure><p>Hope it was helpful &amp; good coding !</p><p><a href="https://github.com/ugurkanates">ugurkanates - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb26f6006ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A safe and secure update strategy for MCU’s]]></title>
            <link>https://ugurkanates.medium.com/a-safe-and-secure-update-strategy-for-mcus-adcf4d4cb461?source=rss-49f8ecb2420a------2</link>
            <guid isPermaLink="false">https://medium.com/p/adcf4d4cb461</guid>
            <category><![CDATA[mcu]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Ugurkan Ates]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 15:03:12 GMT</pubDate>
            <atom:updated>2019-09-22T15:03:12.950Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Linux on MCU’s ? No Way !</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*4qPvklh1HoXWwXq6LsQZSg.jpeg" /><figcaption>Soon MCU’s will be powerful and still cheap enough to run them :)</figcaption></figure><p>Many embedded systems are deployed in places that are difficult or impractical for a human operator to access. This is especially true for Internet of Things (IoT) applications, which are typically deployed in larger quantities and with limited battery life.</p><p>Some examples would be embedded systems that monitor the health of a person or a machine. These challenges, coupled with the rapid software life cycle, cause many systems to require support for over-the-air (OTA) updates.Microprocessors found a solution to this problem by running entire OS (such as Linux variant) and creating necessary service structure for healthy tracking and OTA updates of IoT devices on the field . But for MCU’s its not that simple hence limited memory and processing power it’s not feasible or possible to load entire OS to MCU’s for most of time.OTA updates are still crucial part of product product life so how they do it ? Updating devices without breaking any critical feature of device that seems a hard task to solve , well not anymore !</p><h3>What are the challenges</h3><ul><li>Application image could get corrupted due to communication errors while downloading.</li><li>Not enough size to back up main application due size of new update.</li><li>While writing new firmware to the flash power could go off. (Unless your card is specially designed to take care of that)</li><li>Partial Erase during replacing backup application.</li><li>Programming Error during installing new firmware.</li><li>Downloaded firmware file could be wrong ( older version , same version , not correct data type, not passing checksum etc.)</li><li>Downloaded firmware could be bugged.</li></ul><p>I am gonna show a solution to all these problems using dual firmware which acts like a backup up our image.</p><h3>General overview of Fail Proof OTA / IAP with MCU’s</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*m84yMvKTk4fQGaLMynG_8A.png" /><figcaption>General overview of update system ( OTA / IAP)</figcaption></figure><p>Using a dual firmware method , we always save our current working application when trying to install firmware update. Using a bootloader ( which just another thread or process) at lowest part of memory stack and our communication layer stacked with applications. This way we emulate the ROM. This method obviously has memory duplication problem but that seems to be negligible considering how advantageous and abstracted from specific device sets.Here’s a little C code snippet for backupping your application(or image).</p><pre>#define BACKUP_ADDRESS (uint32_t)0x0800B000 <br>#define APPLICATION_ADDRESS (uint32_t)0x08007000 <br>#define APPLICATION_SIZE 0x4000 <br>int copy_image(void) {  <br> __IO uint32_t dst = BACKUP_ADDRESS;<br> __IO uint32_t src = APPLICATION_ADDRESS;<br> __IO int i;  <br>/* Unlock the Flash Program Erase controller */<br> FLASH_Unlock ();  <br>/* page-wide erase of backup area */  <br> if (FLASH_If_Erase(dst))·  <br>{  <br>FLASH_Lock(); <br> return ERROR;  <br>}  <br>/* word-wise program */ <br>/* start copying */  <br>for (i = 0; i &lt; (APPLICATION_SIZE/4); ++i) <br> {  <br>while (FLASH_ProgramWord(dst, *(uint32_t *)src) != FLASH_COMPLETE) {} <br> if ((*(uint32_t *)dst) != (*(uint32_t *)src)) <br> {  <br> /* Lock flash */ <br> FLASH_Lock();  <br> return ERROR; <br> } <br> src += 4; <br> dst += 4;<br>  } <br> /* Lock flash */  <br>FLASH_Lock();  <br>return SUCCESS; <br>}</pre><blockquote>If you want to know more about the topic , please look for thesis on this subject ( Kumar Amit Mehta , <em>FAIL-PROOF OVER THE AIR FIRMWARE UPGRADE FOR EMBEDDED SYSTEMS</em>) and Amazon FreeRTOS (which provides this feature)</blockquote><p><a href="https://github.com/ugurkanates">https://github.com/ugurkanates</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adcf4d4cb461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threading vs Multiprocessing in Python]]></title>
            <link>https://ugurkanates.medium.com/threading-vs-multiprocessing-in-python-c6bb9922a14e?source=rss-49f8ecb2420a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6bb9922a14e</guid>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ugurkan Ates]]></dc:creator>
            <pubDate>Sat, 14 Sep 2019 21:05:36 GMT</pubDate>
            <atom:updated>2019-09-14T21:05:36.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Sj5yOCRkcxM89jwYMvS8Xw.jpeg" /></figure><p>This is bit confusing topic if you know thread &amp; mprocessing in C/C++/Java so I hope it will clear for you after reading this.</p><p><strong><em>Multiple Python Implementations ?</em></strong></p><p>Python have different implementations over the years. Most commonly used one is CPython which is implemented by Python core developers and the Python community, supported by the <a href="https://www.wikizeroo.org/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvUHl0aG9uX1NvZnR3YXJlX0ZvdW5kYXRpb24">Python Software Foundation</a>. Which is effectively version you would download from <a href="http://www.python.org/">www.python.org</a>. CPython is implemented with C obviously.</p><blockquote><strong>So what is CPython?</strong></blockquote><blockquote><a href="https://stackoverflow.com/questions/17130975/python-vs-cpython">https://stackoverflow.com/questions/17130975/python-vs-cpython</a></blockquote><p>@<a href="https://stackoverflow.com/users/6381389/chiel">Chiel</a> from Stackoverflow</p><blockquote>CPython is the <em>original</em> Python implementation. It is the implementation you download from Python.org. People call it CPython to distinguish it from other, later, Python implementations, and to distinguish the implementation of the language engine from the Python <em>programming language</em> itself.</blockquote><blockquote>The latter part is where your confusion comes from; you need to keep Python-the-language separate from whatever <em>runs</em> the Python code.</blockquote><blockquote>CPython <em>happens</em> to be implemented in C. That is just an implementation detail, really. CPython compiles your Python code into bytecode (transparently) and interprets that bytecode in a evaluation loop.</blockquote><blockquote>CPython is also the first to implement new features; Python-the-language development uses CPython as the base; other implementations follow.</blockquote><p>And there are other Python implementations like Jython (Java) , C# Python and R Python implementations are also used in some areas in Python development community.Notice that So CPython does <strong>not</strong> translate your Python code to C by itself. Instead, it runs an interpreter loop. If you are interested in that please look for Cython which is entirely different beast.</p><p>In <em>CPython</em> there is a special mechanism implemented and its called <strong><em>GIL.</em></strong></p><p><strong><em>What is GIL aka Global Interpreter Lock ?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYpbss7LLJH0IdbiGPyMtw.jpeg" /></figure><p><em>In CPython, the </em><strong><em>global interpreter lock</em></strong><em>, or </em><strong><em>GIL</em></strong><em>, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.).</em></p><p>It’s a developer/implementation decision which is not to mess and deal memory management. Since this is a really big part of all legacy Python code it’s utterly impossible to change it any moment (hence idea of other implementations). What GIL in nutshell means your so called multihthread operations in Python are actually not multithreadded ? Outside of some blocking and long running applications like (I/O,Image Processing,Numpy these happen outside of GIL) most of your code interpreted will become bottleneck with GIL. Eliminating GIL is one of the most wanted features for Python mail groups but developers has yet to find a solution about it. More on that <a href="https://wiki.python.org/moin/GlobalInterpreterLock">https://wiki.python.org/moin/GlobalInterpreterLock</a></p><p><strong><em>So what’s point of threads in Python then?</em></strong></p><p>Threading albeit not effectively like it’s actual purpose and implementation in other languages are still useful tool for developers if one has right case to use it. Network scripts, I/O, data related tasks still depends on waiting for data and you can still do other computations in CPU while they are doing their job without creating new process for them(which saves memory and time = performance for you). For CPU intensive processes, there is little benefit to using the threading module.</p><p><strong><em>When to use Multi Processing and when to use Threads</em></strong></p><p>A new thread is spawned from existing process , a process is independent from the process it created. So it makes faster to create <strong>threads c</strong>compared to multiprocessing. You will get all memory is shared with threads which might be useful and efficient thing if your tasks demand it. You will need mutex with threads for control of shared memory stack , not needed for multiprocesses they have their own memory spaces. One GIL for all threads (threading library) , One GIL for each process (multiprocessing)</p><p><em>These code bit from engineer-man , will link them in end of page.</em></p><pre># threading example<br>from threading import Thread<br>import os<br>import math<br><br>def calc():<br>	for i in range(0, 4000000):<br>		math.sqrt(i)<br><br>threads = []<br><br>for i in range(os.cpu_count()):<br>	print(&#39;registering thread %d&#39; % i)<br>	threads.append(Thread(target=calc))<br><br>for thread in threads:<br>	thread.start()<br><br>for thread in threads:<br>	thread.join()</pre><p>What it looks like when executed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*FWV4EcnXjtRedswfEkBhQQ.png" /><figcaption>One thread even though we created multiple ones</figcaption></figure><pre># multi processing example<br>from multiprocessing import Process<br>import os<br>import math<br><br>def calc():<br>	for i in range(0, 70000000):<br>		math.sqrt(i)<br><br>processes = []<br><br>for i in range(os.cpu_count()):<br>	print(&#39;registering process %d&#39; % i)<br>	processes.append(Process(target=calc))<br><br>for process in processes:<br>	process.start()<br><br>for process in processes:<br>	process.join()</pre><p>What it looks like when executed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*oUz4vy1E-Lr740OGDmOzYQ.png" /><figcaption>Each with their own process</figcaption></figure><p>So a if you are going to use I/O , data pulling and network scripts definitely use threads with python if you are gonna do all your processing within CPU then i suggest to use multiprocessing for your program.</p><p>I hope it cleared out some smoke and will change your view on how to use them with Python compared to other languages.</p><blockquote><a href="https://github.com/engineer-man/youtube/tree/master/036">https://github.com/engineer-man/youtube/tree/master/036</a> python code for example.</blockquote><p><a href="https://github.com/ugurkanates">ugurkanates - Overview</a></p><p>Thanks for reading and happy coding all !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6bb9922a14e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>