<?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 Davi Sousa on Medium]]></title>
        <description><![CDATA[Stories by Davi Sousa on Medium]]></description>
        <link>https://medium.com/@davifelipemsousa?source=rss-339edfd7b62d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*v1TGUJlpymV2txwt.</url>
            <title>Stories by Davi Sousa on Medium</title>
            <link>https://medium.com/@davifelipemsousa?source=rss-339edfd7b62d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:27:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davifelipemsousa/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[Fiz um robô e deixei um mês fazendo day trade]]></title>
            <link>https://medium.com/@davifelipemsousa/fiz-um-rob%C3%B4-e-deixei-um-m%C3%AAs-fazendo-day-trade-d53c54b4d293?source=rss-339edfd7b62d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53c54b4d293</guid>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[robots]]></category>
            <dc:creator><![CDATA[Davi Sousa]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 17:39:45 GMT</pubDate>
            <atom:updated>2021-12-30T17:31:25.172Z</atom:updated>
            <content:encoded><![CDATA[<p>A alguns anos atrás, quando o termo day trade ainda não era tão conhecido como hoje, resolvi pesquisar mais sobre o assunto e entender como esse mundo funciona. Quando mais estudava mas percebia que não sabia quase nada. Descobri que o mercado financeiro é uma ciência! Uma ciência que envolve análise gráfica, estatística, programação e até psicologia.</p><p>Pra quem tá de fora e tem curiosidade sobre esse mundo, vou tentar compartilhar da forma mais imparcial possível sobre o conhecimento que daiquiri durante esses anos. Assim como a linguagem de programação que usei para desenvolver o robô e os resultados obtidos pelo robô durante 1 mês de operações.</p><p>No meio dessa ciência chamada mercado financeiro, existe uma subdivisão chamada análise gráfica ou análise técnica. Que por definição é uma ferramenta para análise de movimento do preço.</p><p>É fato que não temos como saber se o preço de um determinado ativo vai subir ou cai nos próximos dias, horas ou nos próximos minutos. A premissa da análise gráfica é encontrar padrões gráficos que se repetiram várias vezes no passado e através de estatística, escolher os padrões que tem a maior probabilidade de se repetir no futuro. Esses padrões são como se fossem desenhos no gráfico que se repetiram várias vezes e no momento em que um novo desenho começa a se formar, podemos abrir uma operação “apostando” que o preço vai completar o desenho indo para o lado que apostei.</p><p>Se fizer um estudo e constatar que em uma base histórica de 1 ano por exemplo, e que em 70% das vezes em que o desenho se formou, completou fechando o padrão, a tendência é que esse percentual se mantenha o mesmo ao longo do tempo.</p><p>Tomando como base o exemplo anterior, muita gente pode pensar então que de 10 operações, vou acertar obrigatoriamente 7. Mas não é bem assim. Se o estudo foi feito com base em um ano, a tendência é que essa estatística se mantenha parecida na projeção futura durante o mesmo período. Nesse caso, é bem provável que das 10 primeiras operações, acerte somente 5 ou 4 e erre o restante.</p><p>É aí que entra a parte mais difícil: A psicologia. A maioria das pessoas perdem dinheiro no mercado financeiro por não conseguir manter o controle emocional e psicológico em se manter seguindo a mesma estratégia, mesmo durante de uma sequência de operações perdedoras. É natural do ser humano não saber lidar com perdas.</p><p>Vamos aos resultados do robô:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*MF_VtrqC7_x_vJ4DMDRvhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*qlbL59yrOxWbqH2tssSyqg.png" /></figure><p>Do dia 27 ao dia 30 de julho, desceu do saldo de R$760 para R$505. Passou 3 dias seguidos sem ganhar nada. Só perdendo. Olhando pro gráfico, essa perca pode ser até aceitável, pois essa sequência de perdas só veio depois depois de uma sequência de ganhos. Mas se as operações tivessem começado no dia 28, o robô teria passado os 3 primeiros dias sem ganhar nada. E nesse caso, a maioria das pessoas não ia ter coragem de deixar o robô operando por mais tempo por que certamente ia pensar que essa sequência de perdas não ia ter fim. A perda financeira causa dor. E quando qualquer pessoa sente muita dor por muito tempo, a primeira reação é fazer alguma coisa para a dor parar.</p><p>Por isso que a maioria das pessoas perdem dinheiro no mercado financeiro. Seja no day trade ou em operações mais longas. O mercado é pura emoção, por que as pessoas agem pela emoção e esses sentimentos são refletidos no gráfico. A maioria não suporta a dor da perda e desiste no momento que mais está perdendo. Por isso os gráficos registram movimentos de baixa irracionais em momentos de desespero em que as pessoas correm para zerar a operação e se livrar da dor da perda o mais rápido possível.</p><p>Para fazer negociações na bolsa de valores, é necessário acessar o home broker da corretora pelo navegador e passar por várias autenticações. Para day trade esse processo é impraticável por que as operações tem que ser feitas de forma muito rápida. Por isso existem várias plataformas de negociação. Que no final das contas, são programas instalados com computador local, conectados com servidor da corretora em que é possível enviar ordens de compra ou de venda de forma muito mais rápida. Apertando apenas um botão.</p><p>O robô que desenvolvemos foi feito em uma plataforma chamada Metatrader. Atualmente considero a melhor plataforma para desenvolvimento de robôs de investimento. Tem uma linguagem própria chamada Mql5 (muito parecida com C). Tudo é feito por lá. Desde a escrita do código até a compilação do robô. Tem uma comunidade bem ativa e um marketing place para venda e aluguel de robôs.</p><p>Espero que tenha ajudado a entender melhor sobre mercado financeiro, day trade e robôs de investimento. Não me aprofundei muito em análise gráfica e programação para não deixar o leitura cansativa. Mas se preferir pode conferir esse curso em que abordamos esse tema por mais de 6 horas mostrando detalhadamente como o robô foi feito.</p><p><a href="https://www.udemy.com/course/metatrader-mql5-aprenda-trade-com-robos/">Metatrader Mql5 - Aprenda trade com robôs</a></p><p>Finalmente vamos aos resultados das operações. Todas as operações feitas foram gravadas e podem ser conferidas nesse canal. Assim como os resultados compilados na planilha. As operações foram feitas no mini contrato de dólar futuro do dia 14/07/2021 até o dia 13/08/20201. Segue o vídeo com a análise dos resultados:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fhk454ovrcn4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dhk454ovrcn4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fhk454ovrcn4%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/336221ec3b3dc35bbe024c3e37cda4e2/href">https://medium.com/media/336221ec3b3dc35bbe024c3e37cda4e2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53c54b4d293" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native get started]]></title>
            <link>https://medium.com/@davifelipemsousa/react-native-get-started-20fff18b6685?source=rss-339edfd7b62d------2</link>
            <guid isPermaLink="false">https://medium.com/p/20fff18b6685</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-example]]></category>
            <category><![CDATA[react-native-get-started]]></category>
            <dc:creator><![CDATA[Davi Sousa]]></dc:creator>
            <pubDate>Thu, 28 Jun 2018 19:38:33 GMT</pubDate>
            <atom:updated>2018-07-13T00:34:03.541Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9WQnrzal06w%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9WQnrzal06w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9WQnrzal06w%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/6fa5599973244b05ae801d84556d1eac/href">https://medium.com/media/6fa5599973244b05ae801d84556d1eac/href</a></iframe><p>For those who don’t know React is an open source library developed by Facebook based on components.</p><p>React Native is the same React only with several native components for mobile multplatform.</p><p>Although it is possible to work on a project with only Ract, it is also possible to add React in a legacy project with Angular.</p><p>In the same way Cordova. It is possible to add React in a Cordova project. React don’t replace Cordova.</p><p>React Native Replaces Cordova. React Native is neither webview like Cordova nor can it be tested in the browser like Ionic and other Cordova based frameworks.</p><p>The main difference between React native and other cross-platform mobile-based cross-platform frameworks is that the visual components are native. That’s it. Although the syntax is a bit like html and css.</p><p>The main difference between React and React Native is that React Native is exclusive for mobile and dispenses use of the Cordova. React js can be used for web along with another js or mobile library or with Cordova.</p><p>Which to use and how to use, will depend on the requirements and each project. Beyond the knowledge of the team in each of the two.</p><p>Before you begin you need to make the following installations:</p><ul><li>Java (JDK)</li><li>Pyton</li><li>Android Studio for Android or Xcode for IOS</li><li>Node JS</li></ul><p>Now let’s rum this command to check if node JS are installed</p><pre>node -v</pre><p>And this another command to install React Native CLI (Command line interface)</p><pre>npm install -g react-native-cli</pre><p>If you prefer, run this another command to check if React Native CLI were installed correct</p><pre>react-native -v</pre><p>And finally run this command to create an new project</p><pre>react-native init poc1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6bVI3zcB2mu2aJAoOQxJdg.jpeg" /></figure><p>To run this project in mobile device, we should run this command</p><pre>react-native run-android</pre><p>There is another alternative: Enter the project android folder at the prompt and execute this command to generate the APK file</p><pre>gradlew assembleDebug</pre><p>Navigate to the <strong>app/build/outputs/apk</strong> folder where the apk was generated and run this other command to install the apk on the mobile</p><pre>adb install app-debug.apk</pre><p>Now just go back to the root project and run</p><pre>react-native start</pre><p>This command starts the process on port 8081. Then just open the app that was installed on the device or emulator and run that other command in a new window of the prompt, leaving the first window open.</p><pre>adb reverse tcp:8081 tcp:8081</pre><p>This command makes the link between the 8081 ports of the phone and computer. Once this is done, you can now execute this other command to refresh the APP on the device.</p><pre>adb shell input keyevent 46 46</pre><p>If you are in the emulator, just click on his screen and press “R” twice. Note that 46 is the “R” code on the keyboard.</p><p>If everything is ok, the app opens on the device or emulator like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*x1NKhFQ5QmmhQM0QcX4ChA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Zf-OD0wum0kM0lsgkgl8xQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20fff18b6685" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous image classifier in Cordova]]></title>
            <link>https://medium.com/@davifelipemsousa/continuous-image-classifier-in-cordova-d4442735ba79?source=rss-339edfd7b62d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4442735ba79</guid>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[cordova-tensorflow]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cordova-camera-preview]]></category>
            <dc:creator><![CDATA[Davi Sousa]]></dc:creator>
            <pubDate>Sat, 23 Jun 2018 02:39:12 GMT</pubDate>
            <atom:updated>2018-06-27T03:32:13.678Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRH9EAlKYa_E%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRH9EAlKYa_E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRH9EAlKYa_E%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/7722d7a6349971714f97361d09e4895b/href">https://medium.com/media/7722d7a6349971714f97361d09e4895b/href</a></iframe><p>had already <a href="https://medium.com/@davifelipemsousa/cordova-tensorflow-f8b9ee5e6abe">created a post</a> showing how to do image recognition using the Tensorflow cordova plugin.<br>Now let’s show you how to do continuous image recognition using the camera preview plugin from Cordova.<br>First we need to create the project by executing this command</p><pre>cordova create previewcamera com.yourname.previewcamera previewcamera</pre><p>now let’s run this command to install the plugin Cordova camera preview</p><pre>cordova plugin add <a href="https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git">https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git</a></pre><p>and this other command to install the Cordova plugin Tensorflow</p><pre>cordova plugin add <a href="https://github.com/heigeo/cordova-plugin-tensorflow">https://github.com/heigeo/cordova-plugin-tensorflow</a></pre><p>Let’s add this code in the index.js file</p><pre>var app = {<br>    // Application Constructor<br>    initialize: function() {<br>        document.addEventListener(&#39;deviceready&#39;, this.onDeviceReady.bind(this), false);<br>    },</pre><pre>// deviceready Event Handler<br>    //<br>    // Bind any cordova events here. Common events are:<br>    // &#39;pause&#39;, &#39;resume&#39;, etc.<br>    onDeviceReady: function() {<br>        //this.receivedEvent(&#39;deviceready&#39;);<br>  <br>  let options = {<br>    x: 0,<br>    y: 0,<br>    width: window.screen.width,<br>    height: window.screen.height,<br>    camera: CameraPreview.CAMERA_DIRECTION.BACK,<br>    toBack: true,<br>    tapPhoto: true,<br>    tapFocus: false,<br>    previewDrag: false<br>  };</pre><pre>CameraPreview.startCamera(options);<br>  <br>  <br>  $(&#39;#my-img&#39;).click(function(){<br>   <br>   <br>  });<br>  <br>  var self = this;<br>  setTimeout(function(){<br>   self.capturePhoto();<br>  },2000);<br>  <br>  <br>    },<br> <br> capturePhoto:function(){<br>  var self = this;<br>  var optionsTake = {<br>       width:640, <br>       height:640, <br>       quality: 85<br>       };<br>      CameraPreview.takePicture(optionsTake, function(base64PictureData){<br>     /*<br>    base64PictureData is base64 encoded jpeg image. Use this data to store to a file or upload.<br>    Its up to the you to figure out the best way to save it to disk or whatever for your application.<br>     */</pre><pre>// One simple example is if you are going to use it inside an HTML img src attribute then you would do the following:<br>     imageSrcData = &#39;data:image/jpeg;base64,&#39; +base64PictureData;<br>    <br>    $(&quot;#deviceready&quot;).removeClass(&quot;blink&quot;);<br>    <br>    <br>    var tf = new TensorFlow(&#39;custom-model&#39;, {<br>       &#39;label&#39;: &#39;My Custom Model&#39;,<br>       &#39;label_path&#39;: &quot;<a href="http://www.davifelipe.com.br/arquivos/star_wars_graph.zip#retrained_labels.txt">http://www.davifelipe.com.br/arquivos/star_wars_graph.zip#retrained_labels.txt</a>&quot;,<br>       &#39;model_path&#39;: &quot;<a href="http://www.davifelipe.com.br/arquivos/star_wars_graph.zip#rounded_graph.pb">http://www.davifelipe.com.br/arquivos/star_wars_graph.zip#rounded_graph.pb</a>&quot;,<br>       &#39;input_size&#39;: 299,<br>       &#39;image_mean&#39;: 128,<br>       &#39;image_std&#39;: 128,<br>       &#39;input_name&#39;: &#39;Mul&#39;,<br>       &#39;output_name&#39;: &#39;final_result&#39;<br>      });<br>    //var tf = new TensorFlow(&#39;inception-v1&#39;);<br>    $(&quot;#message&quot;).html(&quot;loading...&quot;);<br>    <br>    tf.onprogress = function(evt) {<br>     if (evt[&#39;status&#39;] == &#39;downloading&#39;){<br>      $(&quot;#message&quot;).html(&quot;Downloading model files...&quot;);<br>      $(&quot;#message&quot;).html(evt.label);<br>      if (evt.detail) {<br>       // evt.detail is from the FileTransfer API<br>       <br>       var carregados = evt.detail.loaded/1024/1024;<br>       var total = evt.detail.total/1024/1024;<br>       <br>       carregados = carregados.toFixed(2);<br>       total = total.toFixed(2);<br>       <br>       var perc = (carregados * 100 / total).toFixed(2);<br>       <br>       $(&quot;#message&quot;).html(`${perc}% ${carregados}MB de ${total}MB`);<br>      }<br>     } else if (evt[&#39;status&#39;] == &#39;unzipping&#39;) {<br>      $(&quot;#message&quot;).html(&quot;Extracting contents...&quot;);<br>     } else if (evt[&#39;status&#39;] == &#39;initializing&#39;) {<br>      $(&quot;#message&quot;).html(&quot;Initializing TensorFlow&quot;);<br>     }<br>    };<br>    <br>    $(&#39;#my-img&#39;).attr(&#39;src&#39;, imageSrcData);<br>    <br>    tf.classify(base64PictureData).then(function(results) {<br>     $(&quot;#message&quot;).html(&quot;&quot;);<br>     results.forEach(function(result) {<br>      $(&quot;#message&quot;).append(result.title + &quot; &quot; + result.confidence+&quot; &lt;br/&gt;&quot;);<br>     });<br>     self.capturePhoto();<br>    },<br>    function(error){<br>     $(&quot;#message&quot;).html(error);<br>    });<br>    <br>   },<br>   function(error){<br>    alert(&quot;error: &quot;+error);<br>   });<br> },<br> <br> <br> <br>    // Update DOM on a Received Event<br>    receivedEvent: function(id) {<br>        var parentElement = document.getElementById(id);<br>        var listeningElement = parentElement.querySelector(&#39;.listening&#39;);<br>        var receivedElement = parentElement.querySelector(&#39;.received&#39;);</pre><pre>listeningElement.setAttribute(&#39;style&#39;, &#39;display:none;&#39;);<br>        receivedElement.setAttribute(&#39;style&#39;, &#39;display:block;&#39;);</pre><pre>console.log(&#39;Received Event: &#39; + id);<br>    }<br>};</pre><pre>app.initialize();</pre><p>And put this another code in the index.html file</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src &#39;self&#39; data: gap: <a href="https://ssl.gstatic.com/">https://ssl.gstatic.com</a> &#39;unsafe-eval&#39;; style-src &#39;self&#39; &#39;unsafe-inline&#39;; media-src *; img-src &#39;self&#39; data: content:;&quot;&gt;<br>        &lt;meta name=&quot;format-detection&quot; content=&quot;telephone=no&quot;&gt;<br>        &lt;meta name=&quot;msapplication-tap-highlight&quot; content=&quot;no&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width&quot;&gt;<br>        &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/index.css&quot;&gt;<br>        &lt;title&gt;Hello World&lt;/title&gt;<br>    &lt;/head&gt;<br> &lt;style&gt;<br>  html, body, .ion-app, .ion-content {<br>    background-color: transparent;<br>     }<br>  .app{<br>   background:none;<br>  }<br> &lt;/style&gt;<br>    &lt;body&gt;<br>        &lt;div class=&quot;app&quot;&gt;<br>            &lt;h1&gt;Apache Cordova&lt;/h1&gt;<br>            &lt;div id=&quot;deviceready&quot; &gt;<br>                &lt;img width=&quot;100&quot; src=&quot;img/logo.png&quot; id=&quot;my-img&quot;/&gt;<br>    &lt;br/&gt;<br>    &lt;span id=&quot;message&quot; style=&quot;background-color:white;color:black;margin:3px;padding:3px&quot;&gt;Loading...&lt;/span&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>  &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.8.2.min.js&quot;&gt;&lt;/script&gt;<br>        &lt;script type=&quot;text/javascript&quot; src=&quot;cordova.js&quot;&gt;&lt;/script&gt;<br>        &lt;script type=&quot;text/javascript&quot; src=&quot;js/index.js&quot;&gt;&lt;/script&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Don’t forget do download jquery-1.8.2.min.js and put it in the www/js folder!</p><p>Run this command to add android platform</p><pre>cordova platform add android@6.3.0</pre><p>And finally, run this command to run our project on mobile device</p><pre>cordova run android</pre><p>If it’s all right, we’ll see the result on the mobile screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*CyfWQjMkl-4TPz4uPNZe1g.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4442735ba79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cordova Tensorflow example]]></title>
            <link>https://medium.com/@davifelipemsousa/cordova-tensorflow-f8b9ee5e6abe?source=rss-339edfd7b62d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8b9ee5e6abe</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cordova]]></category>
            <category><![CDATA[apache-cordova]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Davi Sousa]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 12:02:35 GMT</pubDate>
            <atom:updated>2018-05-26T23:03:20.146Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlnnPiFVIYmQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlnnPiFVIYmQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlnnPiFVIYmQ%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/74a7509044be4f9812a09dadf131133d/href">https://medium.com/media/74a7509044be4f9812a09dadf131133d/href</a></iframe><p>Let’s show you how to do image recognition with Cordova and Tensorflow. In the documentation says that works for Android and IOS. Let’s show the operation on Android.</p><p>We gonna use the model inception-v3 file generated in <a href="https://medium.com/@davifelipemsousa/tensorflow-for-mobile-2cf9675707b9">this post</a></p><p>Assuming that you already have cordova installed, run this command to create a new cordova project:</p><pre>cordova create workshop com.yourname.workshop Workshop</pre><p>Then, navigate to the root directory project and execute this command to install Tensorflow dependencies:</p><pre>cordova plugin add https://github.com/heigeo/cordova-plugin-tensorflow</pre><p>The index.js file should be like this:</p><pre>var app = {<br>     mostraMensagem: function(valor){<br>         document.getElementById(&quot;progress&quot;).innerHTML = valor;<br>     },<br>     // Application Constructor<br>     initialize: function() {<br>         var self = this;<br>         <br>         document.addEventListener(&#39;deviceready&#39;, this.onDeviceReady.bind(this), false);<br>     },<br> <br>     // deviceready Event Handler<br>     //<br>     // Bind any cordova events here. Common events are:<br>     // &#39;pause&#39;, &#39;resume&#39;, etc.<br>     onDeviceReady: function() {<br>         this.receivedEvent(&#39;deviceready&#39;);<br>         var self = this;<br>         self.mostraMensagem(&quot;iniciou!&quot;);<br>         $(&quot;#deviceready&quot;).removeClass(&quot;blink&quot;);//para não ficar piscando.<br>         var self = this;<br>         <br>         var tf = new TensorFlow(&#39;custom-model&#39;, {<br>                     &#39;label&#39;: &#39;My Custom Model&#39;,<br>                     &#39;label_path&#39;: &quot;http://www.davifelipe.com.br/arquivos/star_wars_graph.zip#retrained_labels.txt&quot;,<br>                     &#39;model_path&#39;: &quot;http://www.davifelipe.com.br/arquivos/star_wars_graph.zip#rounded_graph.pb&quot;,<br>                     &#39;input_size&#39;: 299,<br>                     &#39;image_mean&#39;: 128,<br>                     &#39;image_std&#39;: 128,<br>                     &#39;input_name&#39;: &#39;Mul&#39;,<br>                     &#39;output_name&#39;: &#39;final_result&#39;<br>                 });<br>         //var tf = new TensorFlow(&#39;inception-v1&#39;);<br>         self.mostraMensagem(&quot;Carregando...&quot;);<br>         tf.onprogress = function(evt) {<br>             if (evt[&#39;status&#39;] == &#39;downloading&#39;){<br>                 self.mostraMensagem(&quot;Downloading model files...&quot;);<br>                 self.mostraMensagem(evt.label);<br>                 if (evt.detail) {<br>                     // evt.detail is from the FileTransfer API<br>                     <br>                     var carregados = evt.detail.loaded/1024/1024;<br>                     var total = evt.detail.total/1024/1024;<br>                     <br>                     carregados = carregados.toFixed(2);<br>                     total = total.toFixed(2);<br>                     <br>                     var perc = (carregados * 100 / total).toFixed(2);<br>                     <br>                     self.mostraMensagem(`${perc}% ${carregados}MB de ${total}MB`);<br>                 }<br>             } else if (evt[&#39;status&#39;] == &#39;unzipping&#39;) {<br>                 self.mostraMensagem(&quot;Extracting contents...&quot;);<br>             } else if (evt[&#39;status&#39;] == &#39;initializing&#39;) {<br>                 self.mostraMensagem(&quot;Initializing TensorFlow&quot;);<br>             }<br>         };<br>         <br>         var imgData224 = &#39;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASsAAAErCAYAAA...&#39;;<br>         <br>         var aData = imgData224.split(&#39;,&#39;);<br>         document.getElementById(&quot;preview&quot;).src = imgData224;<br>         <br>         tf.classify(aData[1]).then(function(results) {<br>             results.forEach(function(result) {<br>                 self.mostraMensagem(result.title + &quot; &quot; + result.confidence);<br>             });<br>         },<br>         function(error){<br>             self.mostraMensagem(error);<br>         });<br>         <br>     },<br>     <br>     // Update DOM on a Received Event<br>     receivedEvent: function(id) {<br>         var parentElement = document.getElementById(id);<br>         var listeningElement = parentElement.querySelector(&#39;.listening&#39;);<br>         var receivedElement = parentElement.querySelector(&#39;.received&#39;);<br> <br>         listeningElement.setAttribute(&#39;style&#39;, &#39;display:none;&#39;);<br>         receivedElement.setAttribute(&#39;style&#39;, &#39;display:block;&#39;);<br> <br>         console.log(&#39;Received Event: &#39; + id);<br>     }<br> };<br> <br> app.initialize();</pre><p>the variable var imgData224 is the base64 of an image of Master Yoda. You can pick up any of them on the internet, in the star_wars folder that we created or even use the cordova camera plugin to take a snapshot at the time.</p><p>And the index.html file should look like this:</p><pre>&lt;html&gt;<br>     &lt;head&gt;<br>         &lt;meta name=&quot;format-detection&quot; content=&quot;telephone=no&quot;&gt;<br>         &lt;meta name=&quot;msapplication-tap-highlight&quot; content=&quot;no&quot;&gt;<br>         &lt;meta name=&quot;viewport&quot; content=&quot;user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width&quot;&gt;<br>         &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/index.css&quot;&gt;<br>         &lt;title&gt;Hello World&lt;/title&gt;<br>     &lt;/head&gt;<br>     &lt;body&gt;<br>         &lt;div class=&quot;app&quot;&gt;<br>             &lt;h1&gt;Apache Cordova&lt;/h1&gt;<br>             &lt;div id=&quot;deviceready&quot; class=&quot;blink&quot;&gt;<br>                 &lt;p class=&quot;event listening&quot;&gt;Connecting to Device&lt;/p&gt;<br>                 &lt;p class=&quot;event received&quot;&gt;Device is Ready&lt;/p&gt;<br>                 &lt;p&gt;<br>                 &lt;p id=&quot;progress&quot; style=&quot;text-transform: none;&quot;&gt;status!!!&lt;/p&gt;<br>                 &lt;img id=&quot;preview&quot; width=&quot;150&quot; alt=&quot;preview&quot;/&gt;<br>             &lt;/div&gt;<br>         &lt;/div&gt;<br>         &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.8.2.min.js&quot;&gt;&lt;/script&gt;<br>         &lt;script type=&quot;text/javascript&quot; src=&quot;cordova.js&quot;&gt;&lt;/script&gt;<br>         &lt;script type=&quot;text/javascript&quot; src=&quot;js/index.js&quot;&gt;&lt;/script&gt;<br>         <br>     &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Do not forget to download jquery-1.8.2.min.js into the js folder. I used 1.8 but may be the most current version.</p><p>When you start the app the model and label file will be downloaded and the result should be this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Y84sPD3V1V4UePMdRghZPw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8b9ee5e6abe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow for mobile]]></title>
            <link>https://medium.com/@davifelipemsousa/tensorflow-for-mobile-2cf9675707b9?source=rss-339edfd7b62d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf9675707b9</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Davi Sousa]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 10:39:33 GMT</pubDate>
            <atom:updated>2018-05-25T12:32:24.747Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH1783ooICUY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH1783ooICUY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH1783ooICUY%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/681abbcf140dc17ba26f1a499fd5461c/href">https://medium.com/media/681abbcf140dc17ba26f1a499fd5461c/href</a></iframe><p>If you don’t know Tensorflow, I highly recommend you read <a href="https://medium.com/@davifelipemsousa/how-to-classify-images-using-tensorflow-51e1fcf1866">this post</a> first. In this post we generate a personal model that recognizes patterns in images. But for this image recognition to work on the mobile device, we must make some changes to the model.</p><p>We can use a Tensorflow model or a custom model. The Tensorflow models that already exist are: inception-v1 and inception-v3. When we create our custom model as shown in <a href="https://medium.com/@davifelipemsousa/how-to-classify-images-using-tensorflow-51e1fcf1866">this post</a>, the model is not trained from scratch. It is trained from a preexisting Tensorflow model.</p><p>By default Tensorfow uses inception-v3 for this. If you want to change the base model, just pass the parameter</p><pre>--architecture</pre><p>at the time of generating the model. But you can no longer use the inception-v1 model to create custom models.</p><p>In the end this is used to make shortcuts in the training process of our model. So the name of the script we use to generate the model is retrain.py. This is why we are retraining a model that has been trained previously. We are adding a new layer in the training model. Before we begin, we have to regenerate the model. But this time we need to use another image of the docker. This is because the model we generate with the official image will not work on the mobile device.</p><p>This image was created by danjarvis. In <a href="https://hub.docker.com/r/danjarvis/tensorflow-android/">the docker hub page</a> he says that this container is based on the official container that we use in <a href="https://medium.com/@davifelipemsousa/how-to-classify-images-using-tensorflow-51e1fcf1866">this post</a> but with other installations turned to android</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*_2tY8RIYfxOtk6DvrosiZQ.jpeg" /></figure><p>To upload the container with the new image we will run this command in the docker terminal:</p><pre>docker run -it -v ~/projects/dump/tf_files/:/tf_files/ danjarvis/tensorflow-android:1.0.0</pre><p>I am using the star_wars folder created in <a href="https://medium.com/@davifelipemsousa/how-to-classify-images-using-tensorflow-51e1fcf1866">this post</a>.</p><p>IMPORTANT: If you try to use the model star_wars_graph.pb at mobile generated from official Tensorflow container docker, it throws this error:</p><pre>TF initialization failed</pre><p>After you finish downloading the danjarvis / tensorflow-android image and entering the container, we will run this command inside the container to generate the custom model:</p><pre>python /tensorflow/tensorflow/examples/image_retraining/retrain.py \<br>--bottleneck_dir=/tf_files/bottlenecks \<br>--how_many_training_steps 500 \<br>--model_dir=/tf_files_inception  \<br>--output_graph=/tf_files/star_wars_graph.pb \<br>--output_labels=/tf_files/star_wars_labels.txt \<br>--image_dir /tf_files/star_wars</pre><p>When the process finishes, a new star_wars_graph.pb file will be generated. It is this file that must be uploaded to the mobile device.</p><p>The big question here is that in mobile device only works inception-v1 models.</p><p>And if you try to use the model star_wars_graph.pb that we just generated in the danjarvis / tensorflow-android container based on the inception-v3 of Tensorflow it throws this another error:</p><pre>Op BatchNormWithGlobalNormalization is not avaliable on GraphDef version 21. it has been removed in version 9. Use tf.nn.batch_normalization().</pre><p>It is no longer possible to generate custom templates with the inception-v1 architecture. Even though the official example Android app uses inception-v1. In this example project file Android says what we have to do to work with inception-v3</p><p>From line 52:</p><pre>// These are the settings for the original v1 Inception model. If you want to<br>// use a model that&#39;s been produced from the TensorFlow for Poets codelab,<br>// you&#39;ll need to set IMAGE_SIZE = 299, IMAGE_MEAN = 128, IMAGE_STD = 128,<br>// INPUT_NAME = &quot;Mul&quot;, and OUTPUT_NAME = &quot;final_result&quot;.<br>// You&#39;ll also need to update the MODEL_FILE and LABEL_FILE paths to point to<br>// the ones you produced.<br>//<br>// To use v3 Inception model, strip the DecodeJpeg Op from your retrained<br>// model first:<br>//<br>// python strip_unused.py \<br>// --input_graph=&lt;retrained-pb-file&gt; \<br>// --output_graph=&lt;your-stripped-pb-file&gt; \<br>// --input_node_names=&quot;Mul&quot; \<br>// --output_node_names=&quot;final_result&quot; \<br>// --input_binary=true</pre><p>In this comment says that we have to use this strip_unused.py script that is in that same repository in the tensorflow / tensorflow / python / tools folder.</p><p>This script serves to revomer DecodeJpeg Op of the retrained model.</p><p>Beauty! It makes perfect sense. I saw several posts on the internet saying the same thing … But it doesn’t works for me! I tested it several times and the error continues:</p><pre>Op BatchNormWithGlobalNormalization is not avaliable on GraphDef version 21. it has been removed in version 9. Use tf.nn.batch_normalization().</pre><p>After many tests, what worked was to follow steps 4 and 5 of <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2/index.html#4">this code lab</a>:</p><pre>python /tensorflow/tensorflow/python/tools/optimize_for_inference.py \<br>--input=/tf_files/star_wars_graph.pb \<br>--output=/tf_files/star_wars_graph_optimized.pb \<br>--frozen_graph=True \<br>--input_names=Mul \<br>--output_names=final_result</pre><p>And then, this:</p><pre>python /tensorflow/tensorflow/tools/quantization/quantize_graph.py \<br>--input=/tf_files/star_wars_graph_optimized.pb \<br>--output=/tf_files/star_wars_rounded_graph.pb \<br>--output_node_names=final_result \<br>--mode=weights_rounded</pre><p>IMPORTANT: These two steps should be done to optimize the model generated in the docker container from the danjarvis / tensorflow-android image. If the model is generated in the image gcr.io/tensorflow/tensorflow will continue throwing error when executed in the mobile device even following these two steps.</p><p>After to do this, the file to use on the mobile device is star_wars_rounded_graph.pb</p><p>After this process, the file star_wars_rounded_graph.pb continues with the same size but after compacting the size is greatly reduced. Around 25MB. This is because quantize_graph.py has optimized the model to have reduced size when it is compacted.</p><p>This reduced size makes it much easier when the file is downloaded by the app.</p><p>I compressed this file along with retrained_labels.txt in a zip file and sent it to that <a href="https://www.dropbox.com/s/j1yex1z32yw4j3t/star_wars_graph.zip?dl=0">url</a></p><p>Search indexes:</p><pre>[Solved] TF initialization failed</pre><pre>[Solved] Op BatchNormWithGlobalNormalization is not avaliable...</pre><p>Tensorflow generating model for IOS<br>Tensorflow generating model for Android</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf9675707b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to classify images using Tensorflow]]></title>
            <link>https://medium.com/@davifelipemsousa/how-to-classify-images-using-tensorflow-51e1fcf1866?source=rss-339edfd7b62d------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e1fcf1866</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Davi Sousa]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 19:27:52 GMT</pubDate>
            <atom:updated>2019-06-26T10:36:48.601Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXTMK-BlEmHk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXTMK-BlEmHk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXTMK-BlEmHk%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/c517a4e96b0c2e113683b3205a92bf8f/href">https://medium.com/media/c517a4e96b0c2e113683b3205a92bf8f/href</a></iframe><p>Tensorflow is a opensource library maintained by google that which makes possible the creation and training of neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zcbwfs2n1yYjiGNEBx6-Tg.jpeg" /><figcaption>The image above shows some of companies that use Tensorflow</figcaption></figure><p>Let’s gonna show how to recognize images patterns using Tensorflow. The concept is very simple: We gonna download many images and split it in two folders. In one of this folders, we’ll save Darth Vader images and in the another folder, Yoda images. For this test, approximately 35 photos for each folder is sufficient. The more the better.</p><p>Then we will run a command for the algorithm to read the two folders and learn the patterns of each.</p><p>When the process finishes, a file with this “learning” will be generated. To be more didactic I will call it the learning file but in the official documentation, this file is called a pre-trained model. That makes all sense. It is a model that has been previously trained and will be used later to identify the images it has been trained to recognize. Then we will run another script that will load the learning file and identify if any photo is of darth vader or Yoda. This result comes in numerical form from 0 to 1.</p><p>Example: When reading a photo, our algorithm returns something like this:</p><p>dart 0.99887</p><p>yoda 0.0034</p><p>The concept is quite cool and can be applied in several possible situations.</p><h3>Enough talk! let’s make it come true!</h3><p>Before we get started, we’ll need Docker installed. With the Docker terminal open, run this command <strong>IMPORTANT!!: Use danjarvis/tensorflow-android:1.0.0 docker image!!!:</strong></p><pre>docker run -it -v ~/projects/dump/tf_files/:/tf_files/ gcr.io/tensorflow/tensorflow:latest-devel</pre><pre>#The docker image above has a problem. To solve his, use this another docker image:<br>docker run -it -v ~/projects/dump/tf_files/:/tf_files/ danjarvis/tensorflow-android:1.0.0</pre><p>For those who don’t know, the -v parameter indicates the volume in the container. In practice it is a shared folder between the container and the physical machine.</p><p>The directory on the left is the local machine and the directory on the right is the directory inside the container. No need to worry about creating the folder on the physical machine. When you finish downloading the image, the folder is created automatically. ~ / means that the folder will be created inside the user’s folder which in my case looks like this:</p><pre>C:/Users/davi/projects/dump/tf_files</pre><p>This folder corresponds to the tf_files folder inside the container. When you finish downloading docker image, you should be already inside the container as root:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*juLGNOsGJ9aGJnbjtF0JAg.jpeg" /></figure><p>Now let’s download the images of Darth Vader and Master Yoda. Chrome plugin called Fatkun batch download:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vn3HKpwnq79dRjHacFLmqw.jpeg" /></figure><p>Let’s search some images of Darth Vader and Yoda on Google:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LAr1N9cn4A34GxsmjWoujA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*DRVKqpJJrewRN5FTpqUHVw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SEvGf7JcbgcQOxB48O4dYA.jpeg" /></figure><p>Repeat the same for Master Yoda without forgetting to unmark the images that we do not want. Leaving only the images of Master Yoda and Darth Vader.</p><p>That done, let’s create a folder called star_wars and put the folder vader and yoda inside star_wars. The star_wars folder should be inside C: / Users / davi / projects / dump / tf_files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*18sMS9AeD43ayDuZk-AMWQ.jpeg" /></figure><p>Let’s see if we can see the folders inside the container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*IHqNgEvDl70tu24B3DOrrw.jpeg" /></figure><p>IMPORTANT: Don’t add underline in the vader and yoda folders. If it’s darth_vader instead of vader it can throws any error.</p><p>Now we can run the script to read the photo folders and generate the “learning” file. Scrap this cd .. until you go back to the root directory of the container, enter the folder tensorflow:</p><pre>cd tensorflow</pre><p>An then:</p><pre>git pull</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*dIsujvCB1qNo-BTlTArCCA.jpeg" /></figure><p>In my case Already appears up-to-date why I had previously run it. But if you run for the first time, it will download the files we need to run the script that will generate the learning file:</p><pre>python tensorflow/examples/image_retraining/retrain.py \<br>--bottleneck_dir=/tf_files/bottlenecks \<br>--how_many_training_steps 500 \<br>--model_dir=/tf_files_inception  \<br>--output_graph=/tf_files/retrained_graph.pb \<br>--output_labels=/tf_files/retrained_labels.txt \<br>--image_dir /tf_files/star_wars</pre><p>For those who did not understand, I put a backslash to escape the line break. I did this not to write the command on a single line because that way it is easier to read. The backslash is used to ignore the line breaks in the command.</p><p>retrained_graph.pb is the “learning” file you had spoken about before. It will be generated at the end of the process. The file retrained_labels.txt will also be generated.</p><p>/ tf_files / star_wars is the folder we created. And inside it, all the folders of the images we want to teach for the algorithm. Inside the folder star_wars you must have in the middle two folders.</p><p>Let’s run the script and see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*sc_eKghdgWfP36X3OQgB-Q.jpeg" /></figure><p>When the process starts, the script will start reading the photos and generating several txt files in the / tf_files / bottlenecks folder. The process delay is proportional to the number of images in the folders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*m2lkgdl3Ay4Yn2vrVeQfLQ.jpeg" /></figure><p>While the process is running we can already create the script that will load the file of “learning” and identify if the image is of Darth vader or the master yoda. Let’s create a file named label_image.py inside the / projects / dump / tf_files folder with the following code:</p><pre>import tensorflow as tf, sys<br>        <br>image_path = sys.argv[1]<br># Read in the image_data<br>image<em>_data = tf.gfile.FastGFile(image_</em>path, &#39;rb&#39;).read()<br># Loads label file, strips off carriage return<br>label_lines = [line.rstrip() for line <br>                  in tf.gfile.GFile(&quot;/tf<em>_files/retrained_</em>labels.txt&quot;)]<br># Unpersists graph from file<br>with tf.gfile.FastGFile(&quot;/tf<em>_files/retrained_</em>graph.pb&quot;, &#39;rb&#39;) as f:<br>   graph_def = tf.GraphDef()<br>   graph_def.ParseFromString(f.read())<br>   <em>_ = tf.import_</em>graph<em>_def(graph_</em>def, name=&#39;&#39;)<br>with tf.Session() as sess:<br>   # Feed the image_data as input to the graph and get first prediction<br>   softmax<em>_tensor = sess.graph.get_</em>tensor<em>_by_</em>name(&#39;final_result:0&#39;)<br>   <br>   predictions = sess.run(softmax_tensor, <br>           {&#39;DecodeJpeg/contents:0&#39;: image_data})<br>   <br>   # Sort to show labels of first prediction in order of confidence<br>   top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]<br>   <br>   for node<em>_id in top_</em>k:<br>       human<em>_string = label_</em>lines[node_id]<br>       score = predictions[0][node_id]<br>       print(&#39;%s (score = %.5f)&#39; % (human_string, score))</pre><p>When the process finishes, the tf_files folder should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*jvFug4c2nITGRoA0k5cQUw.jpeg" /></figure><p>The bottenecks folder, the retrained_graph.pb file, and retrained_labels.txt were generated by the script. label_image.py is the script we just created and star_wars is the images folder.</p><p>Let’s copy an image of darth vader and another one from yoda to tf_files and test with the newly created script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wi5y86jePer0TPO0KgsEsA.jpeg" /></figure><p>Inside the container, let’s go back to the tf _files folder and test the vader.jpg file</p><pre>python label_image.py vader.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sFdZb-hzxDXySYq8dThWmw.jpeg" /></figure><p>Let’s test the file yoda.jpg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rcEu8q1piBO-7sepoCRmzw.jpeg" /></figure><p>References:</p><p><a href="https://www.tensorflow.org/">https://www.tensorflow.org/</a></p><p><a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/?utm_campaign=chrome_series_machinelearning_063016&amp;utm_source=gdev&amp;utm_medium=yt-desc#0">https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/?utm_campaign=chrome_series_machinelearning_063016&amp;utm_source=gdev&amp;utm_medium=yt-desc#0</a></p><p><a href="https://github.com/llSourcell/tensorflow_image_classifier">https://github.com/llSourcell/tensorflow_image_classifier</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e1fcf1866" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>