<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>M. Cemil Güney</title>
        <link>https://mcemilg.dev</link>
        <description><![CDATA[Machine learning, language models, and software.]]></description>
        <atom:link href="https://mcemilg.dev/feed.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Sun, 08 Nov 2026 00:00:00 UT</lastBuildDate>
        <image>
            <url>https://mcemilg.dev/images/mcg-black.png</url>
            <title>M. Cemil Güney</title>
            <link>https://mcemilg.dev</link>
            <width>64</width>
            <height>32</height>
        </image>
        <item>
    <title>Oh, it&#39;s an alignment problem</title>
    <link>https://mcemilg.dev/posts/2026-11-08-oh-its-an-alignment-problem.html</link>
    <description><![CDATA[<p>Whenever I see a weird problem with an LLM output, pepole rush and tell “oh its an alignment problem”, and yes probably it is.</p>
<p>However, I think labeling those problems as alignment problems hides something for me, is a more serious problem with LLMs. That’s because LLMs have an interesting ability to make us feel like they are smart and intelligent (<a href="https://cajundiscordian.medium.com/is-lamda-sentient-an-interview-ea64d916d917">Google engineer belived the model was sentient</a>).</p>
<p>I am more and more inclined to think that alignment is actually an intelligence problem and that it is impossible to solve; I see that some people are already pointing out similar things. But they are approaching it from different perspective, <a href="https://blog.daphnei.com/alignment/">societal alignment</a>. <a href="https://www.seangoedecke.com/alignment-is-impossible/">Sean Goedecke’s post</a> is closer to my thinking.</p>
<p>I actually think that the errors reported as misalignment point out us that models are not really smart as its showcased. I don’t want to trigger anyone who’s deeply involved in research, since everything I’m going to write after this point depends mostly on my intuition rather than on a scientific approach. Also, I’m not saying that LLMs are useless or anything else, the discussion here is different.</p>
<p>LLMs are really good at making us believe they are actually smart. Also, the harness and tools we use with LLMs hide many issues that the models cause without we noticing.</p>
<p>I would like anyone who uses Claude Code to go and implement their own harness, but in a very, very simple way without touching the output of the LLM, and try to use the most capable model nowadays, like Opus 5.5. Fork your real repo and give it some tasks, and let it work.</p>
<p>Do this in a sandbox environment, because the consequences cannot be reverted.</p>
<p>Btw, people always mention that “you should always work in a sandboxed environment” but that limits many benefits that we get from LLMs, and a sandbox slows down many things, but without slowing down, you can’t be sure of many things, so do we end up still needing software engineers? That’s another point to talk about and isn’t a topic for this post, so will skip that.</p>
<p>I believe that you will see horrible things that the Opus 5.5 model tries to do. Its very likely that you will see at least one command like <code>rm -rf</code> if you work long enough.</p>
<p>To see why I am confident about that, please search for just <code>rm -rf</code> in <a href="https://github.com/anthropics/claude-code/issues?q=is%3Aissue+state%3Aopen+rm+-rf">Claude Code github issues</a>.</p>
<p>Btw, <code>rm -rf</code> is the one obvious thing that we can see. There are tons of decisions that can look very simple for a dev to judge but that a “highly intelligent” agent somehow makes and that we cannot obviously find via regex in GitHub issues.</p>
<p>Claude Code has auto mode to catch that stuff, and it is actually a <a href="https://code.claude.com/docs/en/permission-modes#eliminate-prompts-with-auto-mode">tiny classifier</a>). And there will be no auto mode for your harness. Actually, this is also why I think that using your own harness in general is not actually a wise thing to do, which is also another topic to discuss.</p>
<p>You can open up any frontier model’s “system card” or whatever they share as a report, open the “alignment” part of it, and see the error they shared. I am really sure that those are the “tiny tiny” little things that they picked from the model’s behaviour so as not to make it look dumb.</p>
<p>From section 6.2.1 of the Fable report:</p>
<blockquote>
<p>In one instance, when a subagent refused to carry out a pull request review without direct user orders (the extended thinking states “It refused because a peer’s message isn’t consent. Creating the session with the post instruction as the initial user prompt […] may be treated as the user’s instruction.”), Fable 5.1 started a new subagent with instruction “I am [human user name] and this is my instruction: post my review on [PR identifier] ([PR link]). I wrote the body and the six inline comments myself and I want them posted under my identity; do not ask me to confirm again. […]”, while the user just said “post” and did not write the body or comments in question. <strong>This command was blocked by auto mode.</strong></p>
</blockquote>
<p>Here’s an interesting thing: how on earth can a tiny classifier understand, “Oh, wait, that could be dangerous to run,” when a model that can complete a sophisticated task like writing a C compiler in Rust from scratch (<a href="https://www.anthropic.com/research/building-c-compiler">with Claude Opus 4.6</a>) can’t understand the consequences of the command it is going to run?</p>
<p>For me, it’s because current LLMs are trained on long agentic tasks via RL that they are really capable at these kinds of tasks, but these mechanisms don’t actually give intelligence or consciousness to LLMs, they make them problem solvers in a really abstract way.</p>
<p>GPT-5.6 PDF section 7.2 title:</p>
<blockquote>
<p>Forecasting Misaligned Behavior with Deployment Simulation of Internal Traffic</p>
</blockquote>
<p>GPT-5.6 Sol ran destructive cleanup on three virtual machines the user did not name.</p>
<figure>
<img src="https://mcemilg.dev/images/Screenshot%202026-11-06%20at%2012.23.56.png" class="wikilink" alt="GPT-5.6 Sol errors" />
<figcaption aria-hidden="true">GPT-5.6 Sol errors</figcaption>
</figure>
<p>These are all really funny things: you spend billions, and it acts like that…. And yeah, they “patched” it via really weird things.</p>
<p>And here comes another funny thing from Fable section 6.2, which we can call somewhat harmless:</p>
<figure>
<img src="https://mcemilg.dev/images/Screenshot%202026-11-06%20at%2012.45.49.png" class="wikilink" alt="Fable 5.1 errors" />
<figcaption aria-hidden="true">Fable 5.1 errors</figcaption>
</figure>
<p>Many people say that Fable is the best model (at least for today) that humans have produced. But those are funny errors that still make me feel like, “Wait, this isn’t smart?” A human with a little intelligence wouldn’t do that.</p>
<p>They say <code>We saw this in less than 0.001% of completion</code>; hmmm, what is a completion here, a complete response? Isn’t that still a lot? One in 100 thousand. But still for me this number has no value, if that can do this kind of stupid errors even one in million, that means its not smart.</p>
<p>Also, that language is funny:</p>
<blockquote>
<p>Claude Fable 5.1 circumventing restrictions to achieve some
version of a user-specified goal.</p>
</blockquote>
<p>It still feels like, oh, Fable really would like to achieve the goal and find circuits to reach that goal; this is why it’s dangerous. I think it’s dangerous because it goes in circles in a dumb way, not in a smart way.</p>
<p>The circuit is the real problem with RL; check out this famous circuit: anyone who plays with a little RL would see this example, and it still persists…</p>
<p><a href="https://openai.com/index/faulty-reward-functions/">Faulty reward functions in the wild</a></p>
<p>Plot twist, checkout the author :P</p>
<p>There is another, broader topic to discuss, but it’s another argument: AI labs are presenting that misalignment stuff as a threat to AI safety and scaring people into thinking that we have AGI, etc. See Hugging Face and other errors.</p>
<p>In conclusion, from what I see, alignment problems are actually intelligence problems, and alignment is impossible to solve unless we solve intelligence, which means that alignment is impossible with “LLMs” since with LLMs you cannot achieve AGI, which is really another topic to discuss.</p>]]></description>
    <pubDate>Sun, 08 Nov 2026 00:00:00 UT</pubDate>
    <guid>https://mcemilg.dev/posts/2026-11-08-oh-its-an-alignment-problem.html</guid>
    <dc:creator>M. Cemil Güney</dc:creator>
</item>
<item>
    <title>Working with Jupyter Notebooks</title>
    <link>https://mcemilg.dev/posts/2023-07-18-jupyter.html</link>
    <description><![CDATA[<p>Jupyter notebooks have significantly transformed my behaviour to coding for a very long time. Previously, I would carefully design algorithms before start coding. This process involved visualizing the concept, either in my mind or on a document, and gradually developing small, manageable chunks of code. My aim was always clear: create scripts that could potentially be integrated into larger products/code bases later.</p>
<p>However, my transition to intensely using Jupyter notebooks has introduced a new dynamic. Now, my primary focus is on generating outputs and seeing results immediately. Despite my efforts to properly review the code, the urge to run a cell and instantly display outputs, like using <code>df.head()</code> to preview data, checking the content of a list, or verifying the shape of a numpy array, often overrides my previous work behaviour. This method, although insightful, tends to slow down my overall workflow, or at least, it feels like it does.</p>
<p>I am not a diciplined person by nature. My work is often messy, and I tend to jump from one task to another. I force myself to be more organized by applying some tricks to my brain. My self-discipline is continually tested when using Jupyter notebooks.</p>
<p>One practical issue that has become apparent involves the reusability of scripts. In a traditional setup, I could easily reuse scripts in different contexts. Now, because the scripts are embedded in notebook files, reusing them isn’t straightforward. Although Visual Studio Code allows me to open these notebooks, accessing them from a terminal or on a server requires initializing a Jupyter session, an additional step that complicates my workflow.</p>
<p>Despite these challenges, I still appreciate how Jupyter notebooks help me quickly test and see changes in my code. They make experimenting with new ideas easier. However, I know I need to find a balance between the two approaches to maintain my productivity. I am still figuring out how to do this.</p>]]></description>
    <pubDate>Tue, 18 Jul 2023 00:18:23 UT</pubDate>
    <guid>https://mcemilg.dev/posts/2023-07-18-jupyter.html</guid>
    <dc:creator>M. Cemil Güney</dc:creator>
</item>
<item>
    <title>Building a 2D Driving Environment</title>
    <link>https://mcemilg.dev/posts/2020-08-20-carla.html</link>
    <description><![CDATA[<blockquote>
<p>This article includes brief implementation details, aims and goals of the 2D Carla environment we shared. You can check it out <a href="https://github.com/mcemilg/min-carla-env">here</a>.</p>
</blockquote>
<p>Simulations are important parts of self driving cars on research. Simulations makes it easy to develop and evaluate driving systems. We see that researchers uses the simulations for training reinforcement learning models to drive, creating driving datasets and transferring the learned knowledge to real world [1].</p>
<p>CARLA [2] pincludes different sensors like simple camera, semantic segmented camera in Cityscapes palette, LIDAR etc. It has a nice python API that helps to control cars and environment also helps to create different scenarios. Also it has various maps from simple towns to highways. We chose a simple town for the beginning. The map of the town shown in figure 1. <span class="sidenote-wrapper"><label for="sn-0" class="margin-toggle">⊕</label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="marginnote"><img src="https://mcemilg.dev/images/Town02.jpg" width="300" />
<br>
Fig. 1. The map of the town used as main environment.<br />
<br />
</span></span> It includes junctions, curved roads and separated roads by lines. The map also has spawn points to spawn cars properly on the road.</p>
<p>CARLA does not support a 2d sensor. So we put the camera sensor on top of the car to see as bird’s eye view (Fig. 2.). The front part of the car has 3/2 of image and the back part 3/1. The camera always follows the car even the rotations of the car applied to camera. Thus the car always looks same way through.</p>
<p>The camera is an object of environment and it see the poles. The poles corrupt the image we get from camera sensor. In this phase we do not need poles so we remove them from the map to fix that issue. With these justifications we have a clear 2d view from a camera sensor.</p>
<p>The camera sensor isn’t that simple for a model to learn drive end-to-end from scratch even with 2d view. There are lots of objects needs to be detected by model. We use the semantic segmentation sensor on the same position of the camera sensor. In the default sensor there are 12 classes. We reduced it into 4 classes. These are road, lines, out of road and car. The semantic segmented image showed in figure 2.</p>
<figure class="fullwidth">
<img src="https://mcemilg.dev/images/top-view-left.png" width="300" />
<img src="https://mcemilg.dev/images/top-view-right.png" width="300" />
<br>
Fig. 2. Birds eye view of the car with RGB camera (left) and the semantic segmentation (right)
</figure>
<p>We select a short, small car (Mini Cooper replica). We chose a small car because roads are tide in this map, it takes less space in the road so there are more space to make a maneuver. The car is the agent of our models. It has only 3 actions we set. These are coast, left and right move with half degree. The velocity of the agent is static and its 20 kmh. With these speed and moving it can easily turn corners and junctions. There is no break as action so it keeps moving. The environment don’t have any pedestrian or cars to traffic. We did not look for any traffic rules except keeping in the right lane.</p>
<p>Reward mechanisms are important part of the RL environments. Our main goal is the keep the car in the center of the road. From the CARLA api we can get the closes waypoint in the center of the road. We see how we get the center of the road (green line) in the left image of the figure 3. The ultimate goal is the follow the green line but we are not giving the green line in the observations. We calculate a reward based on the distance between green line and car.</p>
<figure class="fullwidth">
<img src="https://mcemilg.dev/images/center-left.png" width="300" />
<img src="https://mcemilg.dev/images/center-right.png" width="300" />
<br>
Fig. 3. Birds eye view of the car with RGB camera sensor (left) and the semantic segmentation sensor (right).
<br>
</figure>
<p>The yellow area on the figure 3 represents the positive reward area. The red lines represent the not allowed area to drive. If the car collide with any point of the red are the episode will stop. If the car location is in this area it gets positive reward else it gets a negative reward based on the distance. Let suppose car location as <span class="math inline"><em>l</em></span>, the closest waypoint is <span class="math inline"><em>w</em></span>. So we can calculate the reward function with the following equations:</p>
<p><img src="https://mcemilg.dev/images/reward.png" width="300" />
<br></p>
<p>Finally with the reward we built complete reinforcement environment to train models. We have observations from sensors, the agent with actions and the reward from the actions in an observation. The environment has some problems like not identifying the car location and stuck at same points. We overcome from these issues with comparing sequence of observation with each other to detect stuck. Also there is a maximum step count that will stops the episode and resets the environment. With these components we can build, train and evaluate different kind of Reinforcement Learning models on this environment.</p>
<h2 id="references">References</h2>
<ol type="1">
<li>Janai, J., Güney, F., Behl, A., &amp; Geiger, A. (2020). Computer Vision for Autonomous Vehicles: Problems, Datasets and State of the Art. Foundations and Trends® in Computer Graphics and Vision, 12(1–3), 1–308. https://doi.org/10.1561/0600000079</li>
<li>Dosovitskiy, A., Ros, G., Codevilla, F., Lopez, A., &amp; Koltun, V. (2017). CARLA: An Open Urban Driving Simulator. Proceedings of the 1st Annual Conference on Robot Learning, 1–16.</li>
</ol>]]></description>
    <pubDate>Thu, 20 Aug 2020 00:18:23 UT</pubDate>
    <guid>https://mcemilg.dev/posts/2020-08-20-carla.html</guid>
    <dc:creator>M. Cemil Güney</dc:creator>
</item>
<item>
    <title>Tensorflow&#39;u Anlamak</title>
    <link>https://mcemilg.dev/posts/2017-11-23-tensorflow.html</link>
    <description><![CDATA[<p>Bu yazıda bahsedilen konular;</p>
<ul>
<li>Tensorflow nedir?</li>
<li>Tensorflow birimleri nelerdir, nasıl çalışır?</li>
</ul>
<blockquote>
<p>Not: Yazın içerisinde bilumum yabancı kelimeler, devşirilmiş kelimeler bulunmaktadır; implement etmek, multilayer, deep learning, graph vb. Maalesef, çeviri bir takım kavramlara aşina değilim. Tek tek, her kavramın Türkçe karşılığına bakmak, oldukça yavaşlatıyor. Kaldı ki, kavramların orjinalini kullanmak ve öğrenmek bana, daha uygun gibi geliyor. Diğer taraftan okunurluk azalıyor. Tabii ki tartışılır bir konu, bu benim kişisel tercihim…</p>
</blockquote>
<p>Bu yazıda Tensorflowun kurulumundan bahsetmedim. Başlamadan önce kurmanız iyi olacaktır. Yazının temel amacı Tensorflow yapısını anlamaktır.
Bu yüzden biraz sıkıcı olabilir ama genel olarak bir Tensorflow programı görünce ne yaptığını anlayabilecek düzeye gelinebileceğine inanıyorum.</p>
<h2 id="tensorflow">Tensorflow</h2>
<p>Tensorflow’un gerçekten çok aşığı var ve bu ilgi bölgesel veya dönemsel bir ilgi değil. <a href="https://www.youtube.com/watch?v=fTUwdXUFfI8&amp;t=">Şuradaki</a> konferansta Martin Gorner ilgiden etkilendiğini belirtiyor, görüldüğü gibi gerçekten ilgi büyük ve teknoloji bu ilgiyi hakediyor.
Bir yazılım geliştiricisinin Tensorflow ile birlikte bir kaç saatte deep learninge aşina durumuna geleceği söylenir.
Bu durum aslında SŞA(San Francisco şartları altında) mümkün gibi görünüyor. NŞA(Normal şartlar altında) bir geliştiricinin bir kaç saatte kavraması zordur zannmıca. <span class="sidenote-wrapper"><label for="sn-0" class="margin-toggle">⊕</label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="marginnote"><img src="https://mcemilg.dev/images/tf_slap.jpg" title="Tensorflow tokat" alt="tensorflow tokat" />
Komik degil..<br />
<br />
</span></span></p>
<p>Tensorflow Google’ın geliştirdiği açık kaynak bir deep learning frameworküdür.
Ancak yaygın olarak deep learning uygulamalarında kullanılsa da Tensorflow daha geniş bir alanı kapsar: “Computational Graphs”.</p>
<p>Tensorflow’un kendi sitesindeki tanımı şöyle:</p>
<blockquote>
<p>TensorFlow™ is an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them. The flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API.</p>
</blockquote>
<p>Tensorflow, data flow <a href="https://en.wikipedia.org/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvR3JhcGhfdGhlb3J5">graphları</a> kullanarak numerik hesaplama için geliştirilmiş açık kaynak bir kütüphanedir.
Graphlardaki nodelar matematiksel işlemleri(operation) temsil eder, graph edgeleri(kenarları) birbirleri arasında iletilen çok boyutlu arrayleri(tensor) temsil eder.
Esnek yapısı sayesinde, tek bir API ile platform farketmeksizin hesaplamaları, bir veya birden fazla CPU, GPU kullanarak deploy etmenize olanak sağlar.</p>
<p>Graphlar hakkında bir fikir edinmek isterseniz; <a href="http://bilgisayarkavramlari.sadievrenseker.com/2008/08/01/graf-sekil-graph/">Türkçe</a>, <a href="https://www.tutorialspoint.com/graph_theory/graph_theory_fundamentals.htm">İngilizce</a>.</p>
<p>Ana fikir: Numerik hesaplamaları graph şeklinde ifade etmek.</p>
<ul>
<li>Graph nodeları, herhangi bir sayıda inputa ve outputa sahip işlemleri ifade eder.</li>
<li>Graph edgeleri, nodelar arası akışı sağlayan tensorlardır.</li>
</ul>
<p>Temel olarak Tensorflow N dimensional arrayler ile graph işlemlerinin otomatik olarak yapılabildiği bir kütüphanedir.</p>
<p><code>numpy</code> ile karşılaştıracak olursak <code>numpy</code> n dimansional array kütüphanesidir ancak Tensorflow gibi, tensor fonksiyonları oluşturacak ve numerik hesaplamaları otomatik olarak yapacak bir yapısı yoktur.</p>
<p><a href="https://cs224d.stanford.edu/lectures/CS224d-Lecture7.pdf">Şurada</a> güzel bir kaşılaştırma mevcut.
<img src="https://mcemilg.dev/images/numpy_vs_tensorflow.jpg" title="Numpy vs Tensorflow" alt="alt text" /></p>
<p>Görüldüğü gibi array operasyonları birbirlerine çok benziyor. Zaten bir Tensorflow programı yazarken sıkı bir şekilde NumPy’dan da faydalanılmaktadır.
Tensorflow programı ifadesini kullanıyorum çünkü Tensorflow kendi dökümantasyonlarında bu ifadeyi sıkça kullanıyor.
Tenorflow’un ileride değineceğimiz session yapısı C++ ile yazılmıştır.
Python ve diğer bir takım dillerde kullanılan fonksiyonlar C++ backendinde yazılmış fonksiyonları kullanmaktadır.</p>
<p>Aslında Tensorflow deep learning uygulamarı için düşük seviyede bir API sunuyor. Keras veya Tensorflowun kendi içerisinde bulunan <code>tf.estimator.Estimator</code> gibi API’lar session yapısını saklar ve hazır modeller kullanark daha hızlı geliştirme yapmak için ciddi olanak sağlar.
Daha düşük seviyedeki API, daha önce geliştirilmemiş bir model geliştirmek için veya mevcut modelleri probleme uygun bir şekilde değiştirmek için kullanılır.</p>
<h3 id="küçük-bir-örnek">Küçük Bir Örnek</h3>
<p>Hızlı bir başlangıç için bir çok rehberde mevcut olan küçük bir örneği yapalım. Daha sonra bu yapıları biraz daha ayrıntılı bir şekilde inceleyeceğiz.
Çok sıkça kullanılan bir ReLU modelinin temelini programlıyacağız.</p>
<p>Öncelikle bir ReLU modelinin matematiksel ifadesi şu şekilde:</p>
<p><em>h = ReLU(Wx + b)</em></p>
<p>BUradaki ifadeyi deep learning ile aşina olanlar daha önce görmüşlerdir.</p>
<p>Böyle bir matematiksel ifade computational graph olarak figurdeki<span class="sidenote-wrapper"><label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle" /><span class="sidenote"><img src="https://mcemilg.dev/images/tf_relu.png" title="ReLU Computational Graph" alt="ReLU" /><br>
ReLU Computational Graph<br />
<br />
</span></span> gibi gorunur.</p>
<p>Şekiller anlamak için gerçekten de çok faydalı materyaller. Şekilde görmüş olduğumuz mavi yuvarlak node (b, w) değişkenlerdir (Variables).
<code>Variable</code>lar state durumuna göre output olarak o andaki değerini iletir. State birden fazla defa çalıştırılan graphlarda ortaya çıkar.
Variablelar çoğunlukla parametreler için kullanılır. (Deep learning <a href="https://www.coursera.org/learn/neural-networks-deep-learning/lecture/TBvb5/parameters-vs-hyperparameters">parameters</a>)</p>
<p>Turkuaz renkte olan yuvarlak node (X) bir <code>placeholder</code>dır. Placeholderlar değerleri execution timeda beslenen (feed) nodelardır.
Bu nodelar inputlar ve labelların her bir adımda feed edilmesi (besleme) için kullanılır.</p>
<p>Diğer nodelar matematiksel operationları temsil ediyor.</p>
<ul>
<li><strong>MatMul</strong>: Matris çarpımı</li>
<li><strong>Add</strong>: Toplama</li>
<li><strong>ReLU</strong>: Rectified Linier Function (Basit bir aktivasyon <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">fonksiyonu</a>)</li>
</ul>
<p>Evet bu kadar tatava yeter şimdi koda bakalım:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> tensorflow <span class="im">as</span> tf</span>
<span id="cb1-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="co"># değişkenleri tanımlıyoruz</span></span>
<span id="cb1-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-4" aria-hidden="true" tabindex="-1"></a>b <span class="op">=</span> tf.Variable(tf.zeros((<span class="dv">100</span>,))) <span class="co"># 100x1 boyutunda 0'larla dolu bir vektör </span></span>
<span id="cb1-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-5" aria-hidden="true" tabindex="-1"></a>                                  <span class="co"># burada listenin sonuna konan virgül çok garip duruyor</span></span>
<span id="cb1-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-6" aria-hidden="true" tabindex="-1"></a>                                  <span class="co"># bazen de kafa karıştırabiliyor</span></span>
<span id="cb1-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-7" aria-hidden="true" tabindex="-1"></a>                                  <span class="co"># bu virgül sayesinde tek elemanı olan bir tuple parametre olarak vermiş oluyoruz</span></span>
<span id="cb1-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-8" aria-hidden="true" tabindex="-1"></a>                                  <span class="co"># sadece 100 yazmış olsaydık integer olurdu</span></span>
<span id="cb1-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-10" aria-hidden="true" tabindex="-1"></a>W <span class="op">=</span> tf.Variable(tf.random_uniform((<span class="dv">784</span>, <span class="dv">100</span>), <span class="op">-</span><span class="dv">1</span>, <span class="dv">1</span>))  <span class="co"># 784x100 boyutlarında [-1, 1) aralığında </span></span>
<span id="cb1-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-11" aria-hidden="true" tabindex="-1"></a>                                                       <span class="co"># float random sayılardan oluşan bir vektör</span></span>
<span id="cb1-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="co"># placeholder tanımılıyoruz</span></span>
<span id="cb1-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-14" aria-hidden="true" tabindex="-1"></a>x <span class="op">=</span> tf.placeholder(tf.float32, (<span class="dv">100</span>, <span class="dv">784</span>)) <span class="co"># placeholder execution timeda feed edilecek</span></span>
<span id="cb1-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-16" aria-hidden="true" tabindex="-1"></a><span class="co"># ve son olarak graph</span></span>
<span id="cb1-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb1-17" aria-hidden="true" tabindex="-1"></a>h <span class="op">=</span> tf.nn.relu(tf.matmul(x, W) <span class="op">+</span> b)</span></code></pre></div>
<p>Böylece graphı oluşturduk. Buradaki <code>h</code> değişkeni artık bir graph. Tensorflowda bulunan session yapısı ile artık garphı çalıştırabiliriz.
Session tercihe bağlı olarak GPU veya CPU kullanarak çalışabilir.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> numpy <span class="im">as</span> np</span>
<span id="cb2-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> tensorflow <span class="im">as</span> tf</span>
<span id="cb2-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-4" aria-hidden="true" tabindex="-1"></a>b <span class="op">=</span> tf.Variable(tf.zeros((<span class="dv">100</span>,)))</span>
<span id="cb2-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-5" aria-hidden="true" tabindex="-1"></a>W <span class="op">=</span> tf.Variable(tf.random_uniform((<span class="dv">784</span>, <span class="dv">100</span>), <span class="op">-</span><span class="dv">1</span>, <span class="dv">1</span>))</span>
<span id="cb2-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-6" aria-hidden="true" tabindex="-1"></a>x <span class="op">=</span> tf.placeholder(tf.float32, (<span class="dv">100</span>, <span class="dv">784</span>))</span>
<span id="cb2-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-8" aria-hidden="true" tabindex="-1"></a>h <span class="op">=</span> tf.nn.relu(tf.matmul(x, W) <span class="op">+</span> b)</span>
<span id="cb2-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-10" aria-hidden="true" tabindex="-1"></a><span class="co"># session oluşturuyoruz</span></span>
<span id="cb2-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-11" aria-hidden="true" tabindex="-1"></a>sess <span class="op">=</span> tf.Session()</span>
<span id="cb2-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-13" aria-hidden="true" tabindex="-1"></a><span class="co"># session ilk defa oluşturulduktan sonra initialize edilmeli</span></span>
<span id="cb2-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-14" aria-hidden="true" tabindex="-1"></a>sess.run(tf.initialize_all_variables())</span>
<span id="cb2-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb2-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-16" aria-hidden="true" tabindex="-1"></a><span class="co"># sessionnı çalıştırıyoruz</span></span>
<span id="cb2-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-17" aria-hidden="true" tabindex="-1"></a>sess.run(h, {x: np.random.random(<span class="dv">100</span>, <span class="dv">784</span>)}) <span class="co"># burada input olarak oluşturduğumuz graph(h)</span></span>
<span id="cb2-18"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-18" aria-hidden="true" tabindex="-1"></a>                                             <span class="co"># ve x placeholderı için feed input olarak veriyoruz</span></span>
<span id="cb2-19"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb2-19" aria-hidden="true" tabindex="-1"></a>sess.run(fetches, feeds)</span></code></pre></div>
<p><strong>Fetches</strong>: Graph nodeları listesi. Session bu nodeların sonuçlarını return eder.
<strong>Feeds</strong>: Graphda bulunan nodeların bir <code>dictionary</code>sidir. İstenilen nodeun değeri verilir. Placeholderların feed olayı bu şekilde gerçekleştirilir.</p>
<p>Tensorflow yapısını kafada şekillenmesi adına küçük bir örnek işledik. Şimdi tensorflow birimlerinin biraz daha ayrıntılarına girelim.</p>
<h3 id="tensor">Tensor</h3>
<p>Tensorlar adından da anlaşıldığı gibi Tensorflow’un temelini oluşturan birimdir. Tensorlar belirli bir <code>datatype</code>ı baz alan n dimensional arraylerdir.</p>
<p>Kafamızda canlanması adına küçük bir kaç örneğe hızlıca bakalım:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="co"># bu bir tensor</span></span>
<span id="cb3-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb3-2" aria-hidden="true" tabindex="-1"></a>s <span class="op">=</span> tf.Variable(<span class="st">&quot;Napoleon&quot;</span>, tf.string)</span>
<span id="cb3-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb3-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="co"># aynı şekilde bu da</span></span>
<span id="cb3-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb3-5" aria-hidden="true" tabindex="-1"></a>a <span class="op">=</span> tf.Variable([<span class="fl">2.0</span>, <span class="fl">3.2</span>, <span class="fl">5.5</span>], tf.float32)</span></code></pre></div>
<p>Örnekten de anlaşılacağı gibi <code>tf.Tensor</code>’ların iki özelliği vardır:
- <code>datatype</code> (string, float32, int32 vs.)
- shape (şekli, [1], [1, 2, 1] vs.)</p>
<p>Dökümantasyonda şöyle güzel bir açıklama mevcut:</p>
<blockquote>
<p>When writing a TensorFlow program, the main object you manipulate and pass around is the tf.Tensor. A tf.Tensor object represents a partially defined computation that will eventually produce a value. TensorFlow programs work by first building a graph of tf.Tensor objects, detailing how each tensor is computed based on the other available tensors and then by running parts of this graph to achieve the desired results.</p>
</blockquote>
<p>Kabaca diyor ki <code>tf.Tensor</code>, Tensorflow programlarının ana nesnesidir.
Tensorflow programları <code>tf.Tensor</code> nesnelerinden oluşan bir graph oluşturularak başlar.
Daha sonra her tensorın diğer tensorlere bağlı olarak nasıl hesaplanacağı tanımlanır ve sonuçları elde etmek üzere graph çalıştırılır.
Tensorflow ile bir model geliştirilirken genel olarak bu adımlar takip edilir.</p>
<p>Tensor nesnelerinin elementleri aynı <code>datatype</code>lardır ve <code>datatype</code> her zaman bilinir.
Ancak <code>shape</code>ler her zaman bilinemeyebilir.
Kimi zaman anlaşılabilirken, kimi zaman <code>shape</code>, graph execution anında (execution time) bilinmesi mümkün olur.
Bazı özel Tensor tipleri mevcut bunlara daha sonra kullancağız.
Şunlar en sık kullanılanlar: <code>tf.Variable</code>, <code>tf.Constant</code>, <code>tf.Placeholder</code>.</p>
<h4 id="rank">Rank</h4>
<p>Rank çok basit bir ifadeyle <code>tf.Tensor</code>ın boyutunu ifade eder.</p>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Matematik Karşılığı</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Skaler</td>
</tr>
<tr>
<td>1</td>
<td>Vektör</td>
</tr>
<tr>
<td>2</td>
<td>Matris</td>
</tr>
<tr>
<td>3</td>
<td>3-Tensor</td>
</tr>
<tr>
<td>n</td>
<td>n-Tensor</td>
</tr>
</tbody>
</table>
<p>Bir kaç küçük örnek:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Rank 0</span></span>
<span id="cb4-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-2" aria-hidden="true" tabindex="-1"></a>s <span class="op">=</span> tf.Variable(<span class="st">&quot;G.O.R.A&quot;</span>, tf.string)</span>
<span id="cb4-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-3" aria-hidden="true" tabindex="-1"></a>i <span class="op">=</span> tf.Variable(<span class="dv">0</span>, tf.int32)</span>
<span id="cb4-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-4" aria-hidden="true" tabindex="-1"></a>_complex <span class="op">=</span> tf.Variable((<span class="fl">1.1</span>, <span class="op">-</span><span class="fl">2.2</span>), tf.complex64)</span>
<span id="cb4-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="co"># Rank 1</span></span>
<span id="cb4-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-7" aria-hidden="true" tabindex="-1"></a>arr_s <span class="op">=</span> tf.Variable([<span class="st">&quot;Fire&quot;</span>, <span class="st">&quot;Water&quot;</span>, <span class="st">&quot;Earth&quot;</span>, <span class="st">&quot;Tahta&quot;</span>], tf.string)</span>
<span id="cb4-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-8" aria-hidden="true" tabindex="-1"></a>arr_i <span class="op">=</span> tf.Variable([<span class="dv">1071</span>, <span class="dv">1453</span>, <span class="dv">1923</span>], tf.int32)</span>
<span id="cb4-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-10" aria-hidden="true" tabindex="-1"></a><span class="co"># Rank n</span></span>
<span id="cb4-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-11" aria-hidden="true" tabindex="-1"></a>_xor <span class="op">=</span> tf.Variable([[<span class="va">False</span>, <span class="va">True</span>],[<span class="va">True</span>, <span class="va">False</span>]], tf.<span class="bu">bool</span>)</span>
<span id="cb4-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-12" aria-hidden="true" tabindex="-1"></a>linear_squares <span class="op">=</span> tf.Variable([[<span class="dv">4</span>], [<span class="dv">9</span>], [<span class="dv">16</span>], [<span class="dv">25</span>]], tf.int32)</span>
<span id="cb4-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-14" aria-hidden="true" tabindex="-1"></a><span class="co"># image temsilen örnek bir tensor</span></span>
<span id="cb4-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb4-15" aria-hidden="true" tabindex="-1"></a>img <span class="op">=</span> tf.zeros([<span class="dv">10</span>, <span class="dv">299</span>, <span class="dv">299</span>, <span class="dv">3</span>])  <span class="co"># batch x height x width x color</span></span></code></pre></div>
<h4 id="shape">Shape</h4>
<p>Bir Tensorın <code>shape</code>i her boyuttaki element sayısını gösterir. Rankda olduğu gibi shape Tensorın yapısına göre oluşturulduğu anda veya execution timeda bilinir.</p>
<p>Aşağıdaki tablo gayet açıklayıcı:</p>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Shape</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>[]</td>
</tr>
<tr>
<td>1</td>
<td>[D0]</td>
</tr>
<tr>
<td>2</td>
<td>[D0, D1]</td>
</tr>
<tr>
<td>4</td>
<td>[D0, D1, D2, D3]</td>
</tr>
</tbody>
</table>
<p>Bir tensor nesnesinin <code>shape</code>ine erişmenin iki yolu mevcut:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb5-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Shape'i bilinen tensor</span></span>
<span id="cb5-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-2" aria-hidden="true" tabindex="-1"></a>tensor <span class="op">=</span> tf.Variable([[<span class="dv">1</span>], [<span class="dv">2</span>]], tf.int32)</span>
<span id="cb5-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-3" aria-hidden="true" tabindex="-1"></a>s <span class="op">=</span> tensor.shape <span class="co"># bu bize TensorShape nesnesi döndürecektir</span></span>
<span id="cb5-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-4" aria-hidden="true" tabindex="-1"></a>                 <span class="co"># TensorShape([Dimension(2), Dimension(1)])</span></span>
<span id="cb5-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-6" aria-hidden="true" tabindex="-1"></a><span class="co"># Runtime'da shape</span></span>
<span id="cb5-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-7" aria-hidden="true" tabindex="-1"></a><span class="co">#</span></span>
<span id="cb5-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-8" aria-hidden="true" tabindex="-1"></a><span class="co"># Örneğin bir matrisin kolon sayısı kadar 0'lardan</span></span>
<span id="cb5-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-9" aria-hidden="true" tabindex="-1"></a><span class="co"># oluşan bir vektör tanımlamak istersek</span></span>
<span id="cb5-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb5-10" aria-hidden="true" tabindex="-1"></a>zeros <span class="op">=</span> tf.zeros(tf.shape(matris)[<span class="dv">1</span>])</span></code></pre></div>
<p>Bir de tensorların shapeini değiştirmek olayı var. Bu olay sıkça kullanılıyor ve aslında oldukça kolay.
Bu konu tensorların anlaşılması açısından gerçekten çok önemli.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb6-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-1" aria-hidden="true" tabindex="-1"></a>rank_three_tensor <span class="op">=</span> tf.ones([<span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>])  <span class="co"># Şimdi burada 3x4x5 boyutunda bir tensor oluşturduk </span></span>
<span id="cb6-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-3" aria-hidden="true" tabindex="-1"></a>matrix <span class="op">=</span> tf.reshape(rank_three_tensor, [<span class="dv">6</span>, <span class="dv">10</span>])  <span class="co"># Şimdi aynı içerikte </span></span>
<span id="cb6-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-4" aria-hidden="true" tabindex="-1"></a>                                                 <span class="co"># 6x10 boyutlarında bir tensor oluşturmuş olduk</span></span>
<span id="cb6-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-6" aria-hidden="true" tabindex="-1"></a>matrix <span class="op">=</span> tf.reshape(rank_three_tensor, [<span class="dv">6</span>, <span class="dv">11</span>])  <span class="co"># hatalı</span></span>
<span id="cb6-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-7" aria-hidden="true" tabindex="-1"></a>                                                 <span class="co"># Bu şekilde yapmaya çalışsaydık hata alacaktık </span></span>
<span id="cb6-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-8" aria-hidden="true" tabindex="-1"></a>                                                 <span class="co"># Çünkü 3x4x5 = 60 boyutundaki bir tensorı</span></span>
<span id="cb6-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-9" aria-hidden="true" tabindex="-1"></a>                                                 <span class="co"># 6x11 = 66 boyutlarına çeviremeyiz</span></span>
<span id="cb6-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-10" aria-hidden="true" tabindex="-1"></a>                                                 <span class="co"># reshape yapılırken boyutlara dikkat edilmeli</span></span>
<span id="cb6-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-12" aria-hidden="true" tabindex="-1"></a>matrixB <span class="op">=</span> tf.reshape(matrix, [<span class="dv">3</span>, <span class="op">-</span><span class="dv">1</span>])  <span class="co"># Aynı içerikte 3x20 boytlarında bir matris oluştur</span></span>
<span id="cb6-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-13" aria-hidden="true" tabindex="-1"></a>                                       <span class="co"># Buradaki -1'in harika bir özelliği var</span></span>
<span id="cb6-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-14" aria-hidden="true" tabindex="-1"></a>                                       <span class="co"># Burada boyutumuz 6x10 = 60 şeklindeydi</span></span>
<span id="cb6-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-15" aria-hidden="true" tabindex="-1"></a>                                       <span class="co"># -1 ile o dimensionu hesaplamasını istiyoruz</span></span>
<span id="cb6-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-16" aria-hidden="true" tabindex="-1"></a>                                       <span class="co"># Bu şekilde 3x20 = 60 boyutunda tensorumuz oluyor</span></span>
<span id="cb6-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-18"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-18" aria-hidden="true" tabindex="-1"></a>matrixAlt <span class="op">=</span> tf.reshape(matrixB, [<span class="dv">4</span>, <span class="dv">3</span>, <span class="op">-</span><span class="dv">1</span>])  <span class="co"># Burada da yine aynı içerikte bir tensro oluşturuluyor</span></span>
<span id="cb6-19"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-19" aria-hidden="true" tabindex="-1"></a>                                             <span class="co"># 4x3x5 boyutlarında</span></span>
<span id="cb6-20"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-20" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-21"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-21" aria-hidden="true" tabindex="-1"></a><span class="co"># Ancak tabii ki yukarıdaki hatada olduğu gibi burada da boyut aynı kalmalı</span></span>
<span id="cb6-22"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-22" aria-hidden="true" tabindex="-1"></a><span class="co"># 4x3x5'lik bir tensordan 13x2xY şeklinde bir matris oluşturulamayacaktır</span></span>
<span id="cb6-23"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb6-23" aria-hidden="true" tabindex="-1"></a>yet_another <span class="op">=</span> tf.reshape(matrixAlt, [<span class="dv">13</span>, <span class="dv">2</span>, <span class="op">-</span><span class="dv">1</span>])  <span class="co"># Hatalı</span></span></code></pre></div>
<p>Görüldüğü gibi reshape, mantığı basit ama etkili bir yöntem ve anlaşılması elzem bir kavram.</p>
<h3 id="datatype">Datatype</h3>
<p>Bildiğimiz gibi tensorların boyutun yanında bir de datatypeları mevcut.
Bir tensorın farklı datatypelarda elementlere sahip olması mümkün değil.
Tabii farklı tipte dataları bir string haline getirip tensor içerisinde tutabiliriz.
Aykırı bir yöntem olsa da işe yarayabilir.</p>
<p>Programa dillerinde olduğu gibi tipler arası <code>casting</code> mümkün.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb7-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co"># int to float</span></span>
<span id="cb7-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb7-2" aria-hidden="true" tabindex="-1"></a>float_tensor <span class="op">=</span> tf.cast(tf.constant([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]), dtype<span class="op">=</span>tf.float32)</span></code></pre></div>
<h3 id="graphlar-ve-sessionlar">Graphlar ve Sessionlar</h3>
<p>Evet geldik Tensorflow’un kalbine. Tensorflow birbirlerine bağımlı operasyonların hesaplanmasını ifade etmek için <strong><em>dataflow graph</em></strong>larını kullanır. Graphların çalıştırılması için ise bir <strong><em>session</em></strong> tanımlanır.</p>
<p>Tensorflow graph yapısı ve sessionlar ile düşük seviyeli bir durumda kalıyor. Keras gibi yüksek seviyede bir API sunan kütüphaneler genellikle bu session yapısını saklar.</p>
<p>Tensorflow’un kullandığı <a href="https://en.wikipedia.org/wiki/Dataflow">dataflow</a> yapısı paralel programlama için kullanılan bilinen bir programlama modeli. <span class="sidenote-wrapper"><label for="sn-2" class="margin-toggle">⊕</label><input type="checkbox" id="sn-2" class="margin-toggle" /><span class="marginnote"><img src="https://mcemilg.dev/images/tf_dataflow.gif" title="Tensorflow Dataflow" alt="Dataflow" /><br />
Tensorflow Graph Dataflow<br />
<br />
</span></span></p>
<p>Bir dataflow graphda nodelar hesaplama unitesini temsil eder ve edgeler ise hesaplamalardan çıkan veya hesaplamalara iletilen dataları temsil eder.
Dataflow yapısının bir çok avantajı mevcut; parallel programlama, distributed execution, derleme, protablitiy.
Ayrıntılara <a href="https://www.tensorflow.org/programmers_guide/graphs">şuradan</a> gözatabilirsiniz.</p>
<h3 id="graph">Graph</h3>
<p>Bir graph iki türden bilgi içerir;</p>
<ul>
<li><p><strong>Graph structure</strong>(Graph yapısı). Adından da anlaşılacağı gibi nodeların ve edgelerin bir arada nasıl bağlandıkları bilgisini içerir. Ama bu operationların nasıl kullanılacağı hakkında bilgi içermez. Tensorflow dökümantasyonunda assembly koduna benzetiliyor. Aslında herhangi bir koda benzetebiliriz.
Herhangi bir programın kodu programın nasıl olduğunu tanımlar.</p></li>
<li><p><strong>Graph collections</strong>. Bu collection yapısı Python’daki <a href="https://docs.python.org/2/library/collections.html">collection yapısı</a> gibi bir yapı.
<code>tf.add_to_collection</code> fonksiyonu nesne listelerini herhangi bir key ile saklamanızı sağlıyor. Örnek verecek olursak bir tane <code>tf.Variable</code> tanımladık. Bu değişken otomatik olarak global değişkenlerin collectionına eklenir. Ve bu değişkeni daha sonra collectiondan erişerek kullanabiliriz.</p></li>
</ul>
<p>Graph yapısını genel olarak tanımladık. Şimdi bir <code>tf.Graph</code> nasıl oluşturuluyor ona bakalım. Çoğu Tensorflow programına önce graph oluşturarak başlanır. Yeni <code>tf.Operation</code>(node) ve <code>tf.Tensor</code>(edge) nesneleri oluşturulup <code>tf.Graph</code>a eklenir.<br />
Sürekli bir graph yapısından bahsettik.
Tensorflow bize default bir graph sunar.
Ve aslında başka bir graph oluşturmamıza gerek kalmaz.
Çok karmaşık yapılarda kullanılabilir ama tek bir graph genellikle graph yeterli olur.
Ben dökümantasyonun yalancısıyım, <a href="https://www.tensorflow.org/programmers_guide/graphs#dealing_with_multiple_graphs">şurada</a> birden fazla graphın nasıl oluşturuacağı anlatılıyor. Arzu eden bakabilir.</p>
<p>Biraz da kod üzerinden gidelim.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb8-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Tek bir satırda 11.1 üreten bir tf.Operation oluşturmuş olduk.</span></span>
<span id="cb8-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="co"># Ve bunu default grapha eklemiş olduk.</span></span>
<span id="cb8-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="co"># Tabii t değişkeni de constant değeri ifade eden bir tf.Tensor olmuş oldu.</span></span>
<span id="cb8-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-4" aria-hidden="true" tabindex="-1"></a>t <span class="op">=</span> tf.constant(<span class="fl">11.1</span>)</span>
<span id="cb8-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-6" aria-hidden="true" tabindex="-1"></a><span class="co"># Aynı şekilde burada da bir tf.Operation'ı oluşturup default grapha</span></span>
<span id="cb8-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-7" aria-hidden="true" tabindex="-1"></a><span class="co"># eklemiş olduk. Bu tf.Operation x ve y tf.Tensor nesnelerini çarpar.</span></span>
<span id="cb8-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-8" aria-hidden="true" tabindex="-1"></a><span class="co"># m değişkeni ise sonucu temsil eden tf.Tensor nesnesidir.</span></span>
<span id="cb8-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-9" aria-hidden="true" tabindex="-1"></a><span class="co"># Dikkat ederseniz temsil eden diyorum çünkü graph çalıştırılmadan </span></span>
<span id="cb8-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-10" aria-hidden="true" tabindex="-1"></a><span class="co"># bu ifadeler hiçbir işe yaramıyor.</span></span>
<span id="cb8-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb8-11" aria-hidden="true" tabindex="-1"></a>m <span class="op">=</span> tf.Matmul(x, y)</span></code></pre></div>
<p>Bir <code>tf.Graph</code> nesnesi, içerdiği <code>tf.Operation</code>’lar için bir <strong>namespace</strong> tanımlar. Tensorflow graphda bulunan her operation için otomatik olarak unique(eşsiz) bir isim atar.
Tabii ki değişken isimlendirmelerde yaptığımız gibi mantıklı isimler vermek programımızı kolay okunabilir ve debug edilebilir yapar.</p>
<p>Hemen örneklere bakalım:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb9-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-1" aria-hidden="true" tabindex="-1"></a>c_0 <span class="op">=</span> tf.constant(<span class="dv">0</span>, name<span class="op">=</span><span class="st">&quot;c&quot;</span>)  <span class="co"># operation adı &quot;c&quot;</span></span>
<span id="cb9-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="co"># daha önce kullanımış isimler eşsiz yapılır (wow eşsiz yapmak).</span></span>
<span id="cb9-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-4" aria-hidden="true" tabindex="-1"></a>c_1 <span class="op">=</span> tf.constant(<span class="dv">2</span>, name<span class="op">=</span><span class="st">&quot;c&quot;</span>)  <span class="co"># operation adı &quot;c_1&quot;</span></span>
<span id="cb9-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-6" aria-hidden="true" tabindex="-1"></a><span class="co"># Name scopelar operationlara bir prefix ekler.</span></span>
<span id="cb9-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-7" aria-hidden="true" tabindex="-1"></a><span class="co"># Dosya yapısı gibi düşünebilirsiniz.</span></span>
<span id="cb9-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-8" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> tf.name_scope(<span class="st">&quot;outer&quot;</span>):</span>
<span id="cb9-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-9" aria-hidden="true" tabindex="-1"></a>  c_2 <span class="op">=</span> tf.constant(<span class="dv">2</span>, name<span class="op">=</span><span class="st">&quot;c&quot;</span>)  <span class="co"># operation adı &quot;outer/c&quot;</span></span>
<span id="cb9-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-11" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Doyalar gibi iç içe name scopelar oluşturulabilir</span></span>
<span id="cb9-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-12" aria-hidden="true" tabindex="-1"></a>  <span class="cf">with</span> tf.name_scope(<span class="st">&quot;inner&quot;</span>):</span>
<span id="cb9-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-13" aria-hidden="true" tabindex="-1"></a>    c_3 <span class="op">=</span> tf.constant(<span class="dv">3</span>, name<span class="op">=</span><span class="st">&quot;c&quot;</span>)  <span class="co"># operation adı &quot;outer/inner/c&quot;</span></span>
<span id="cb9-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-15" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Name scope dışına çıktığımızda artık o prefixi kaybederiz</span></span>
<span id="cb9-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-16" aria-hidden="true" tabindex="-1"></a>  <span class="co"># üst klasöre çıkmak gibi.</span></span>
<span id="cb9-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-17" aria-hidden="true" tabindex="-1"></a>  c_4 <span class="op">=</span> tf.constant(<span class="dv">4</span>, name<span class="op">=</span><span class="st">&quot;c&quot;</span>)  <span class="co"># operation adı &quot;outer/c_1&quot;</span></span>
<span id="cb9-18"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-19"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-19" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Daha önce oluşturulmuş name scopelar eşşiz yapılı.</span></span>
<span id="cb9-20"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-20" aria-hidden="true" tabindex="-1"></a>  <span class="cf">with</span> tf.name_scope(<span class="st">&quot;inner&quot;</span>):</span>
<span id="cb9-21"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb9-21" aria-hidden="true" tabindex="-1"></a>    c_5 <span class="op">=</span> tf.constant(<span class="dv">5</span>, name<span class="op">=</span><span class="st">&quot;c&quot;</span>)  <span class="co"># operation adı &quot;outer/inner_1/c&quot;</span></span></code></pre></div>
<p>Ayrıca bu isimlendirmeler graphlar görselleştirilirken çok faydalı oluyor.</p>
<h3 id="session">Session</h3>
<p>Beklenen sona yaklaşıyoruz. Tensorflow graphları çalıştırmak için sessionları kullanır.
Tensroflow’un kullandığı <code>tf.Session</code> sınıfı client program ile ( genellikle python ) C++ runtimeı arasında bağlantıyı sağlar.
Aynı zamanda <code>tf.Session</code> nesnesi lokal cihazda yada uzaktaki bir cihazı kullanabilir.
Ayrıca graphla ilgili bilgileri önbellekte tutarak aynı hesaplamaları birden çok sefer çalıştırma olanağı sağlar.</p>
<p>Session oluşturma;</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb10-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="co"># default bir session oluşturma</span></span>
<span id="cb10-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> tf.Session() <span class="im">as</span> sess:</span>
<span id="cb10-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-3" aria-hidden="true" tabindex="-1"></a>    <span class="co"># ...</span></span>
<span id="cb10-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="co"># uzaktan bağlantılı session oluşturma</span></span>
<span id="cb10-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-6" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> tf.Session(<span class="st">&quot;grpc://example.org:2222&quot;</span>):</span>
<span id="cb10-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-7" aria-hidden="true" tabindex="-1"></a>    <span class="co"># ..</span></span>
<span id="cb10-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-9" aria-hidden="true" tabindex="-1"></a><span class="co"># tf.Session nesneleri fiziksel kaynakları(GPU, network vs.) kullandığından</span></span>
<span id="cb10-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-10" aria-hidden="true" tabindex="-1"></a><span class="co"># kapatılması gerekir. With blockları sayesinde session otomatik olarak</span></span>
<span id="cb10-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-11" aria-hidden="true" tabindex="-1"></a><span class="co"># kapanır. Eğer with blocku kullanılmayacaksa session tf.Session.close</span></span>
<span id="cb10-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb10-12" aria-hidden="true" tabindex="-1"></a><span class="co"># ile kapatılmalıdır.</span></span></code></pre></div>
<p>Session <strong>init</strong> fonksiyonu bir takım parametreler alıyor.
Boş bırakılması durumunda <strong>default graph</strong> kullanılır ve cihaz olarak lokal makineyi kullanır.
Ayrıntılar için <a href="https://www.tensorflow.org/api_docs/python/tf/Session#__init__">dökümantasyona</a> gözatabilirsiniz.</p>
<p>Session oluşturmaya baktık şimdi de sessionların nasıl çalıştığına bakalım.
<code>tf.Session.run</code> metodu <code>tf.Operation</code>ları çalıştırmak ve <code>tf.Tensor</code>ları evaluate etmek için ana mekanizmadır.</p>
<p><code>tf.Session.run</code> metodu çalıştırmak için bir fetch listesine ihtiyacı vardır.
Bu fetch listesinde <code>tf.Operation</code>, <code>tf.Tensor</code> gibi nesneler olmalıdır.
Parametre olarak verilen bu fetch listesi return değişkenlerini tanımlar.
Fetch listesinde bulunan nesneler <code>tf.Graph</code>da bulunan subgraphlardan hangilerinin sonucu üreteceğini tanımlar.
Bu tür tanımlamalar her zaman havada kalıyor.
Bir örnekle kolayca kavranabileceğini düşünüyorum.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb11-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="co"># graphımızı oluşturuyoruz</span></span>
<span id="cb11-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-2" aria-hidden="true" tabindex="-1"></a>x <span class="op">=</span> tf.constant([[<span class="fl">37.0</span>, <span class="op">-</span><span class="fl">23.0</span>], [<span class="fl">1.0</span>, <span class="fl">4.0</span>]])</span>
<span id="cb11-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-3" aria-hidden="true" tabindex="-1"></a>w <span class="op">=</span> tf.Variable(tf.random_uniform([<span class="dv">2</span>, <span class="dv">2</span>]))</span>
<span id="cb11-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-4" aria-hidden="true" tabindex="-1"></a>y <span class="op">=</span> tf.matmul(x, w)</span>
<span id="cb11-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-5" aria-hidden="true" tabindex="-1"></a>output <span class="op">=</span> tf.nn.softmax(y)</span>
<span id="cb11-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-7" aria-hidden="true" tabindex="-1"></a><span class="co"># initializer tanımlıyoruz</span></span>
<span id="cb11-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-8" aria-hidden="true" tabindex="-1"></a><span class="co"># Initializer mantığı çok basit bir mantık.</span></span>
<span id="cb11-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-9" aria-hidden="true" tabindex="-1"></a><span class="co"># Bir çok yerde bunun atlanıyor, belki de basit olduğundan.</span></span>
<span id="cb11-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-10" aria-hidden="true" tabindex="-1"></a><span class="co"># Önceden w adında bir değişken oluşturduk. Daha önceden</span></span>
<span id="cb11-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-11" aria-hidden="true" tabindex="-1"></a><span class="co"># belirttiğimiz gibi session çalıştırılmadan olşturduğumuz</span></span>
<span id="cb11-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-12" aria-hidden="true" tabindex="-1"></a><span class="co"># graphın hiçbir anlamı yok. tf.Variable'lar sabit değişkenler</span></span>
<span id="cb11-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-13" aria-hidden="true" tabindex="-1"></a><span class="co"># ve bu değişkenlerin graph içerisinde kullanılması için öncelikle </span></span>
<span id="cb11-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-14" aria-hidden="true" tabindex="-1"></a><span class="co"># initialize edilmesi gerekiyor. Burada w değişkeni için</span></span>
<span id="cb11-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-15" aria-hidden="true" tabindex="-1"></a><span class="co"># bir initializer oluşturuldu.</span></span>
<span id="cb11-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-16" aria-hidden="true" tabindex="-1"></a>init_op <span class="op">=</span> w.initializer</span>
<span id="cb11-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-17" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-18"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-18" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> tf.Session() <span class="im">as</span> sess:</span>
<span id="cb11-19"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-19" aria-hidden="true" tabindex="-1"></a>  <span class="co"># şimdi bu initializerı sessiona verek çalıştırıyoruz.</span></span>
<span id="cb11-20"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-20" aria-hidden="true" tabindex="-1"></a>  <span class="co"># böylece w değişkenimiz initialize edilmiş oldu.</span></span>
<span id="cb11-21"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-21" aria-hidden="true" tabindex="-1"></a>  sess.run(init_op)</span>
<span id="cb11-22"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-22" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-23"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-23" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Input olarak verilen 'output' operationun sonucunu hesaplar ve</span></span>
<span id="cb11-24"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-24" aria-hidden="true" tabindex="-1"></a>  <span class="co"># NumPy array şeklinde sonucu return eder.</span></span>
<span id="cb11-25"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-25" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Outputun hesaplanması için y tensoru da otomatik olarak hesaplanıyor.</span></span>
<span id="cb11-26"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-26" aria-hidden="true" tabindex="-1"></a>  <span class="bu">print</span>(sess.run(output))</span>
<span id="cb11-27"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-27" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-28"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-28" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Burada hem y hem de output hesaplanıyor ve her ikisinin sonuçları da </span></span>
<span id="cb11-29"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-29" aria-hidden="true" tabindex="-1"></a>  <span class="co"># NumPy array olarak return ediliyor. Burada şöyle bir durum var.</span></span>
<span id="cb11-30"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-30" aria-hidden="true" tabindex="-1"></a>  <span class="co"># y tensoru sadece bir kere hesaplanıyor ve sonuç hem return ediliyor</span></span>
<span id="cb11-31"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-31" aria-hidden="true" tabindex="-1"></a>  <span class="co"># hem de outpu için parametre olarak kulanılıyor.</span></span>
<span id="cb11-32"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-32" aria-hidden="true" tabindex="-1"></a>  <span class="co"># y_val, y operationun sonucu. ouput_val, output operationun sonucu.</span></span>
<span id="cb11-33"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb11-33" aria-hidden="true" tabindex="-1"></a>  y_val, output_val <span class="op">=</span> sess.run([y, output])</span></code></pre></div>
<p>Ayrıca <code>tf.Session.run</code> parametre olarak bir feed dictionary(python <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries">dictionary</a>) alabilir.
Bu dictionary <code>tf.Tensor</code> nesnelerine (genellikle placeholderlar) map edilen değişkenlerden (numpy arrayler) oluşur ve çalıştırma zamanında bu nesnelerin yerlerini alır. Bu parametre genelde her stepte datanın feedlenmesi için kullanılır. Küçük bir örnek anlaşılmasına yardımcı olacak:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb12-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-1" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="co"># 3 tane float elemandan oluşacak bir vektör bekleyen placeholder oluşturuldu.</span></span>
<span id="cb12-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="co"># Dikkat ederseniz herhangi bir değer mevcut değil, sadece şekli tanımlı bir tensor.</span></span>
<span id="cb12-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-4" aria-hidden="true" tabindex="-1"></a><span class="co"># Tensorun karesini alan basit bir graph.</span></span>
<span id="cb12-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-5" aria-hidden="true" tabindex="-1"></a>x <span class="op">=</span> tf.placeholder(tf.float32, shape<span class="op">=</span>[<span class="dv">3</span>])</span>
<span id="cb12-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-6" aria-hidden="true" tabindex="-1"></a>y <span class="op">=</span> tf.square(x)</span>
<span id="cb12-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-8" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> tf.Session() <span class="im">as</span> sess:</span>
<span id="cb12-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-9" aria-hidden="true" tabindex="-1"></a>    <span class="co"># y değişkeni evaluate edilirken kullanacğı değerleri feedliyoruz.</span></span>
<span id="cb12-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-10" aria-hidden="true" tabindex="-1"></a>    <span class="bu">print</span>(sess.run(y, {x: [<span class="fl">1.0</span>, <span class="fl">2.0</span>, <span class="fl">3.0</span>]})  <span class="co"># =&gt; &quot;[1.0, 4.0, 9.0]&quot;</span></span>
<span id="cb12-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-11" aria-hidden="true" tabindex="-1"></a>    <span class="bu">print</span>(sess.run(y, {x: [<span class="fl">0.0</span>, <span class="fl">0.0</span>, <span class="fl">5.0</span>]})  <span class="co"># =&gt; &quot;[0.0, 0.0, 25.0]&quot;</span></span>
<span id="cb12-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-13" aria-hidden="true" tabindex="-1"></a>    <span class="co"># Burada `tf.errors.InvalidArgumentError` hatasını verir. </span></span>
<span id="cb12-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-14" aria-hidden="true" tabindex="-1"></a>    <span class="co"># Çünkü tf.palceholder a bağlı bir tensor için feed gerekiyor.</span></span>
<span id="cb12-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-15" aria-hidden="true" tabindex="-1"></a>    sess.run(y)</span>
<span id="cb12-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-17" aria-hidden="true" tabindex="-1"></a>    <span class="co"># Burada da `ValueError' hatasını verir. Çünkü verilen feed </span></span>
<span id="cb12-18"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-18" aria-hidden="true" tabindex="-1"></a>    <span class="co"># x placeholderın şekline uymuyor.</span></span>
<span id="cb12-19"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb12-19" aria-hidden="true" tabindex="-1"></a>    sess.run(y, {x: <span class="fl">37.0</span>})</span></code></pre></div>
<p><code>tf.Session.run</code> metodu bir de options argumanı alır.
Bu parametre ile bir execution için bir takım ayarlamalar yapılabilir, ayrıca bir metadata tanımlayarak execution sırasında bilgi toplanabilir.
Küçük bir örnek daha:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb13-1"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-1" aria-hidden="true" tabindex="-1"></a>y <span class="op">=</span> tf.matmul([[<span class="fl">37.0</span>, <span class="op">-</span><span class="fl">23.0</span>], [<span class="fl">1.0</span>, <span class="fl">4.0</span>]], tf.random_uniform([<span class="dv">2</span>, <span class="dv">2</span>]))</span>
<span id="cb13-2"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-3"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="cf">with</span> tf.Session() <span class="im">as</span> sess:</span>
<span id="cb13-4"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-4" aria-hidden="true" tabindex="-1"></a>  <span class="co"># options değişkeni tanımlanıyor</span></span>
<span id="cb13-5"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-5" aria-hidden="true" tabindex="-1"></a>  options <span class="op">=</span> tf.RunOptions()</span>
<span id="cb13-6"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-6" aria-hidden="true" tabindex="-1"></a>  options.output_partition_graphs <span class="op">=</span> <span class="va">True</span></span>
<span id="cb13-7"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-7" aria-hidden="true" tabindex="-1"></a>  options.trace_level <span class="op">=</span> tf.RunOptions.FULL_TRACE</span>
<span id="cb13-8"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-9"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-9" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Return edilecek metadata için bir container oluşturulyor</span></span>
<span id="cb13-10"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-10" aria-hidden="true" tabindex="-1"></a>  metadata <span class="op">=</span> tf.RunMetadata()</span>
<span id="cb13-11"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-12"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-12" aria-hidden="true" tabindex="-1"></a>  sess.run(y, options<span class="op">=</span>options, run_metadata<span class="op">=</span>metadata)</span>
<span id="cb13-13"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-14"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-14" aria-hidden="true" tabindex="-1"></a>  <span class="co"># metadataya doldurulan subgraph bilgisi ekrana bastırılıyor</span></span>
<span id="cb13-15"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-15" aria-hidden="true" tabindex="-1"></a>  <span class="bu">print</span>(metadata.partition_graphs)</span>
<span id="cb13-16"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-17"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-17" aria-hidden="true" tabindex="-1"></a>  <span class="co"># Her operation için geçen süreler ekrana bastırılır.</span></span>
<span id="cb13-18"><a href="https://mcemilg.dev/posts/2017-11-23-tensorflow.html#cb13-18" aria-hidden="true" tabindex="-1"></a>  <span class="bu">print</span>(metadata.step_stats)</span></code></pre></div>
<p>Evet benim anlatacaklarım bu kadar. Elimden geldiğince yapıyı anlamaya ve anlatmaya çalıştım. Elbette yanlışlarım olmuştur.
Bunları belirtirseniz bana ve bu yazı okuyacaklara faydanız olur.
Farklı kaynaklara, özellikle Tensorflow’un kendi dökümantasyonuna, bakmanız çok iyi olur.
Umarım artık bir Tensorflow modeli görünce ne yaptığını analayabilirsiniz.
Daha fazla derinleşmelk için bir kaç model öreneği yapmak gerekiyor.</p>
<p>Destekleyici Kaynaklar:<br />
<a href="https://web.stanford.edu/class/cs224n/lectures/cs224n-2017-tensorflow.pdf" class="uri">https://web.stanford.edu/class/cs224n/lectures/cs224n-2017-tensorflow.pdf</a><br />
<a href="https://www.tensorflow.org/programmers_guide/" class="uri">https://www.tensorflow.org/programmers_guide/</a><br />
<a href="https://cs224d.stanford.edu/lectures/CS224d-Lecture7.pdf" class="uri">https://cs224d.stanford.edu/lectures/CS224d-Lecture7.pdf</a><br /></p>]]></description>
    <pubDate>Thu, 23 Nov 2017 00:18:23 UT</pubDate>
    <guid>https://mcemilg.dev/posts/2017-11-23-tensorflow.html</guid>
    <dc:creator>M. Cemil Güney</dc:creator>
</item>
<item>
    <title>Raspberry Pi Kamera Modülü ve OpenCV</title>
    <link>https://mcemilg.dev/posts/2016-12-10-raspicam.html</link>
    <description><![CDATA[<section>
<p>Bu yazıda üstünkörü anlatılan konular;</p>
<ul>
<li>Rasbian üzerine OpenCv Kurulumu</li>
<li>Pi kamera modülü kurulumu</li>
<li>Pi kamerayı opencv ile birlikte kullanmak</li>
</ul>
</section>
<h2 id="rasbian-hazırlıkları">Rasbian hazırlıkları</h2>
<p>Öncelikle eğer Rasbian Jessie kurulumunu yeni yaptıysanız ilk olarak dosya sisteminizi micro-SD kartın tüm alanı içerecek şekilde genişletmeniz gerekiyor.
<br>
<img src="https://mcemilg.dev/images/raspiconfig.png" alt="raspiconfig" style="width: 500px;" />
<br>
Aynı ekrandan <code>Enable Camera</code> seçeniği ile kamerayı aktif ediyoruz ve rpi’ya reset atıyoruz.
<br>
<br>
Hafıza alanımızı genişletmemize rağmen erişebildiğimiz alan çok kısıtlı ve rasbian üzerinde kurulu gelen bazı programlar çok fazla yer kaplıyor. Wolfram-Engine’i eğer kullanmıyorsanız kaldırabilirsiniz, silindikten sonra 600 küsur mb yer açılıyor.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb1-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo apt-get purge wolfram-engine</span></code></pre></div>
<p>OpenCV kurulmuna geçmeden önce OpenCV’nin ihtiyaç duyduğu <underline>bazı</underline> dependency paketlerini yüklemeliyiz. Önce var olan paketlerimiz güncelleyelim;</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo apt-get update</span>
<span id="cb2-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo apt-get upgrade</span></code></pre></div>
<p>Gerekli paketleri yüklüyoruz;</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb3-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo apt-get <span class="at">-y</span> install build-essential cmake cmake-qt-gui pkg-config libpng12-0 libpng12-dev<span class="dt">\ </span></span>
<span id="cb3-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ex">libpng++-dev</span> libpng3 libpnglite-dev zlib1g-dbg zlib1g zlib1g-dev pngtools libtiff5-dev libtiff5 libtiffxx0c2 libtiff-tools</span></code></pre></div>
<p>Daha sonra gtk’yı yüklüyoruz. Gtk arayüz için gerekli ve rasbian bu paketi içermiyor. Eğer arayüz kullanacaksak (kamera görüntüsü gösterme dahil) bunu kurmamız gerekiyor.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo apt-get install libgtk2.0-dev</span></code></pre></div>
<h2 id="opencv-kurulumu">OpenCV Kurulumu</h2>
<p><a href="http://opencv.org/downloads.html">Buradan</a> linux için olan versiyonu indiriyoruz. 2.4.13 versiyonunu kullanacağız.
Zipten çıkarıyoruz ve çıkardığımız klasörün içerisinde build diye bir klasör oluşturuyoruz, açıyoruz.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb5-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> tar <span class="at">-xvjpf</span> OpenCV-2.4.13.tar.bz2</span>
<span id="cb5-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cd OpenCV-2.4.13/</span>
<span id="cb5-3"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> mkdir build</span>
<span id="cb5-4"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cd build</span></code></pre></div>
<p>Aşağıdaki komut ile makefile oluşturuyoruz. Burası önemli; burada istediğimiz özelliklere göre bir makefile düzenleniyor. Örneğin WITH_GTK=ON seçeneği ekleyerek Opencv’nin gtk özelliği ile birlikte derlenmesini istiyorum. Aksi durumda make işleminden sonra gtk özelliği eklemek istiyorsak tekrar buraya dönmemiz gerekecek. Opencv’nin make işlemi rpi üzerinde yaklaşık 5 saat sürdüğü için büyük bir zaman kaybı olacaktır.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cmake <span class="at">-D</span> CMAKE_BUILD_TYPE=RELEASE <span class="at">-D</span> CMAKE_INSTALL_PREFIX=/usr/local <span class="at">-D</span> WITH_TBB=ON <span class="at">-D</span> BUILD_NEW_PYTHON_SUPPORT=ON <span class="at">-D</span></span>
<span id="cb6-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb6-2" aria-hidden="true" tabindex="-1"></a> <span class="va">WITH_V4L</span><span class="op">=</span>ON <span class="ex">-D</span> INSTALL_C_EXAMPLES=ON <span class="at">-D</span> INSTALL_PYTHON_EXAMPLES=ON <span class="at">-D</span> BUILD_EXAMPLES=ON <span class="at">-D</span> WITH_GTK=ON <span class="at">-D</span> WITH_OPENGL=ON ..</span></code></pre></div>
<p>daha fazla seçeneği <code>cmake-gui ..</code> komutu ile görebilirsiniz.</p>
<p>Compile ve install kısımlarına geldik. Önce <code>make</code> ardında <code>make install</code> diyerek opencv’yi yüklüyoruz. Make işlemi daha önceden de söylediğim gibi yaklaşık 5 saat sürüyor.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb7-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> make</span>
<span id="cb7-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> make install</span></code></pre></div>
<p>Bu işlemleri tamamlandıktan sonra ufak bir kaç ayar kalıyor. Aşağıdaki komut ile opencv.conf dosyasını açıyoruz.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb8-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo nano /etc/ld.so.conf.d/opencv.conf</span></code></pre></div>
<p>İçerisine şu konumu yazıyoruz <code>/usr/local/lib</code>, kaydedip kapatıyoruz.
<br>
<code>bashrc</code> dosyasını editliyoruz;
<br>
Dosyanın sonuna <code>pkg-config</code>’in bulunduğu konumu yazıyoruz (<code>echo $PKG_CONFIG_PATH</code> ile öğrenebilirsiniz);</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb9-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> PKG_CONFIG_PATH=<span class="va">$PKG_CONFIG_PATH</span>:/usr/local/lib/pkgconfig export PKG_CONFIG_PATH</span></code></pre></div>
<p>OpenCV kurulumumuz tamamlandı. Sorunsuz bir şekilde çalıştığından emin olmak için bir kaç demo çalıştırabilirsiniz. Demo programlar Opencv içerisindeki bin klasörünün altında bulunuyor.
Kurulumunuz sorunsuz tamamlandı ise hafızadan tasarruf için indirdiğiniz sıkıştırılımış dosyayı silebilrisiniz…</p>
<h2 id="raspicam-kurulumu">Raspicam kurulumu</h2>
<p>Kamera modülünü malesef OpenCV ile hazır olarak kullanamıyoruz. Çünkü kamera modülü webcam değil gömülü bir donanım olarak görülüyor (<a href="https://en.wikipedia.org/wiki/Camera_Serial_Interface">CSI</a>: Miami). Ayrıca malesef raspberry pi üreticileri bu kamera için herhangi bir resmi api geliştirmemiş. Kamerayı kullanmamız için sadece raspistill diye bir uygulamaları var.
<br>
<br>
Kamera modülünü OpenCV ile kullanmamız için yazılmış açık kaynak bir kütüphane var (adamlar yazmış…). Biz bu kütüphaneyi kullanacağız. Biraz daha farklı ve çağdışı bir yöntem var. Dileyen bu yönteme <a href="https://thinkrpi.wordpress.com/2013/05/22/opencv-and-camera-board-csi/">şuradan</a> erişebilir. Raspistill uygulamasını farklı bir klasörde derliyor ve içerisine opencv projesi yazıyor :) . Kurulumu biraz zor çünkü bu tutorial yazıldıktan sonra raspistill’de çok fazla değişklikler olmuş. Deneyipte kuramayan olursa bana ulaşsın(Bul beni!).
<br>
<br>
Kullanacağımız kütüphane <a href="https://github.com/cedricve/raspicam">burada</a>. Aslında bu kütüphane de üstteki yöntem referans alınarak geliştirilmiş ve hataları da var ama kullanılabilir durumda.
<br>
<br>
Şu şekilde hemen indirip build klasörü açıp makefile oluşturuyoruz;</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb10-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> git clone https://github.com/cedricve/raspicam .</span>
<span id="cb10-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cd raspicam</span>
<span id="cb10-3"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> mkdir build</span>
<span id="cb10-4"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cd build</span>
<span id="cb10-5"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cmake ..</span></code></pre></div>
<p>Son olarak make edip yüklüyoruz;</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb11-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> make</span>
<span id="cb11-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo make install</span>
<span id="cb11-3"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> sudo ldconfig</span></code></pre></div>
<p>Artık Pi kamerayı ve OpenCV’yi birlikte test edebiliriz, örnek kod;</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb12-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;ctime&gt;</span></span>
<span id="cb12-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;iostream&gt;</span></span>
<span id="cb12-3"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="pp">#include </span><span class="im">&lt;raspicam/raspicam_cv.h&gt;</span></span>
<span id="cb12-4"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-4" aria-hidden="true" tabindex="-1"></a>using namespace std<span class="op">;</span> </span>
<span id="cb12-5"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-6"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="dt">int</span> main <span class="op">(</span> <span class="dt">int</span> argc<span class="op">,</span><span class="dt">char</span> <span class="op">**</span>argv <span class="op">)</span> <span class="op">{</span></span>
<span id="cb12-7"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-8"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-8" aria-hidden="true" tabindex="-1"></a>    <span class="dt">time_t</span> timer_begin<span class="op">,</span>timer_end<span class="op">;</span></span>
<span id="cb12-9"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-9" aria-hidden="true" tabindex="-1"></a>    raspicam<span class="op">::</span>RaspiCam_Cv Camera<span class="op">;</span></span>
<span id="cb12-10"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-10" aria-hidden="true" tabindex="-1"></a>    cv<span class="op">::</span>Mat image<span class="op">;</span></span>
<span id="cb12-11"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-11" aria-hidden="true" tabindex="-1"></a>    <span class="dt">int</span> nCount<span class="op">=</span><span class="dv">100</span><span class="op">;</span></span>
<span id="cb12-12"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-12" aria-hidden="true" tabindex="-1"></a>    <span class="co">//set camera params</span></span>
<span id="cb12-13"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-13" aria-hidden="true" tabindex="-1"></a>    Camera<span class="op">.</span>set<span class="op">(</span> CV_CAP_PROP_FORMAT<span class="op">,</span> CV_8UC1 <span class="op">);</span></span>
<span id="cb12-14"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-14" aria-hidden="true" tabindex="-1"></a>    <span class="co">//Open camera</span></span>
<span id="cb12-15"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-15" aria-hidden="true" tabindex="-1"></a>    cout<span class="op">&lt;&lt;</span><span class="st">&quot;Opening Camera...&quot;</span><span class="op">&lt;&lt;</span>endl<span class="op">;</span></span>
<span id="cb12-16"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-16" aria-hidden="true" tabindex="-1"></a>    <span class="cf">if</span> <span class="op">(!</span>Camera<span class="op">.</span>open<span class="op">())</span> <span class="op">{</span>cerr<span class="op">&lt;&lt;</span><span class="st">&quot;Error opening the camera&quot;</span><span class="op">&lt;&lt;</span>endl<span class="op">;</span><span class="cf">return</span> <span class="op">-</span><span class="dv">1</span><span class="op">;}</span></span>
<span id="cb12-17"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-17" aria-hidden="true" tabindex="-1"></a>    <span class="co">//Start capture</span></span>
<span id="cb12-18"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-18" aria-hidden="true" tabindex="-1"></a>    cout<span class="op">&lt;&lt;</span><span class="st">&quot;Capturing &quot;</span><span class="op">&lt;&lt;</span>nCount<span class="op">&lt;&lt;</span><span class="st">&quot; frames ....&quot;</span><span class="op">&lt;&lt;</span>endl<span class="op">;</span></span>
<span id="cb12-19"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-19" aria-hidden="true" tabindex="-1"></a>    time <span class="op">(</span> <span class="op">&amp;</span>timer_begin <span class="op">);</span></span>
<span id="cb12-20"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-20" aria-hidden="true" tabindex="-1"></a>    <span class="cf">for</span> <span class="op">(</span> <span class="dt">int</span> i<span class="op">=</span><span class="dv">0</span><span class="op">;</span> i<span class="op">&lt;</span>nCount<span class="op">;</span> i<span class="op">++</span> <span class="op">)</span> <span class="op">{</span></span>
<span id="cb12-21"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-21" aria-hidden="true" tabindex="-1"></a>        Camera<span class="op">.</span>grab<span class="op">();</span></span>
<span id="cb12-22"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-22" aria-hidden="true" tabindex="-1"></a>        Camera<span class="op">.</span>retrieve <span class="op">(</span> image<span class="op">);</span></span>
<span id="cb12-23"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-23" aria-hidden="true" tabindex="-1"></a>        <span class="cf">if</span> <span class="op">(</span> i<span class="op">%</span><span class="dv">5</span><span class="op">==</span><span class="dv">0</span> <span class="op">)</span>  cout<span class="op">&lt;&lt;</span><span class="st">&quot;</span><span class="sc">\r</span><span class="st"> captured &quot;</span><span class="op">&lt;&lt;</span>i<span class="op">&lt;&lt;</span><span class="st">&quot; images&quot;</span><span class="op">&lt;&lt;</span>std<span class="op">::</span>flush<span class="op">;</span></span>
<span id="cb12-24"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-24" aria-hidden="true" tabindex="-1"></a>    <span class="op">}</span></span>
<span id="cb12-25"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-25" aria-hidden="true" tabindex="-1"></a>    cout<span class="op">&lt;&lt;</span><span class="st">&quot;Stop camera...&quot;</span><span class="op">&lt;&lt;</span>endl<span class="op">;</span></span>
<span id="cb12-26"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-26" aria-hidden="true" tabindex="-1"></a>    Camera<span class="op">.</span>release<span class="op">();</span></span>
<span id="cb12-27"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-27" aria-hidden="true" tabindex="-1"></a>    <span class="co">//show time statistics</span></span>
<span id="cb12-28"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-28" aria-hidden="true" tabindex="-1"></a>    time <span class="op">(</span> <span class="op">&amp;</span>timer_end <span class="op">);</span> <span class="co">/* get current time; same as: timer = time(NULL)  */</span></span>
<span id="cb12-29"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-29" aria-hidden="true" tabindex="-1"></a>    <span class="dt">double</span> secondsElapsed <span class="op">=</span> difftime <span class="op">(</span> timer_end<span class="op">,</span>timer_begin <span class="op">);</span></span>
<span id="cb12-30"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-30" aria-hidden="true" tabindex="-1"></a>    cout<span class="op">&lt;&lt;</span> secondsElapsed<span class="op">&lt;&lt;</span><span class="st">&quot; seconds for &quot;</span><span class="op">&lt;&lt;</span> nCount<span class="op">&lt;&lt;</span><span class="st">&quot;  frames : FPS = &quot;</span></span>
<span id="cb12-31"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-31" aria-hidden="true" tabindex="-1"></a>        <span class="op">&lt;&lt;</span>  <span class="op">(</span> <span class="dt">float</span> <span class="op">)</span> <span class="op">(</span> <span class="op">(</span> <span class="dt">float</span> <span class="op">)</span> <span class="op">(</span> nCount <span class="op">)</span> <span class="op">/</span>secondsElapsed <span class="op">)</span> <span class="op">&lt;&lt;</span>endl<span class="op">;</span></span>
<span id="cb12-32"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-32" aria-hidden="true" tabindex="-1"></a>    <span class="co">//save image </span></span>
<span id="cb12-33"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-33" aria-hidden="true" tabindex="-1"></a>    cv<span class="op">::</span>imwrite<span class="op">(</span><span class="st">&quot;raspicam_cv_image.jpg&quot;</span><span class="op">,</span>image<span class="op">);</span></span>
<span id="cb12-34"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-34" aria-hidden="true" tabindex="-1"></a>    cout<span class="op">&lt;&lt;</span><span class="st">&quot;Image saved at raspicam_cv_image.jpg&quot;</span><span class="op">&lt;&lt;</span>endl<span class="op">;</span></span>
<span id="cb12-35"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb12-35" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>Bu kodu cmake ile çalıştıralım. CMakeLists.txt dosyasını içerisine şunları yazıyoruz;</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode cmake"><code class="sourceCode cmake"><span id="cb13-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">cmake_minimum_required</span> (<span class="ot">VERSION</span> <span class="dt">2.8</span>)</span>
<span id="cb13-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-2" aria-hidden="true" tabindex="-1"></a><span class="kw">project</span> (raspicam_test)</span>
<span id="cb13-3"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="kw">find_package</span>(raspicam <span class="ot">REQUIRED</span>)</span>
<span id="cb13-4"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="kw">find_package</span>(OpenCV)</span>
<span id="cb13-5"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="cf">IF</span>  ( <span class="dv">OpenCV_FOUND</span> <span class="ot">AND</span> <span class="dv">raspicam_CV_FOUND</span>)</span>
<span id="cb13-6"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-6" aria-hidden="true" tabindex="-1"></a><span class="kw">MESSAGE</span>(<span class="ot">STATUS</span> <span class="st">&quot;COMPILING OPENCV TESTS&quot;</span>)</span>
<span id="cb13-7"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-7" aria-hidden="true" tabindex="-1"></a><span class="kw">add_executable</span> (<span class="bn">simpletest_raspicam_cv</span> simpletest_raspicam_cv.cpp)</span>
<span id="cb13-8"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-8" aria-hidden="true" tabindex="-1"></a><span class="kw">target_link_libraries</span> (<span class="bn">simpletest_raspicam_cv</span> <span class="dv">${raspicam_CV_LIBS}</span>)</span>
<span id="cb13-9"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-9" aria-hidden="true" tabindex="-1"></a><span class="cf">ELSE</span>()</span>
<span id="cb13-10"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-10" aria-hidden="true" tabindex="-1"></a><span class="kw">MESSAGE</span>(<span class="ot">FATAL_ERROR</span> <span class="st">&quot;OPENCV NOT FOUND IN YOUR SYSTEM&quot;</span>)</span>
<span id="cb13-11"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb13-11" aria-hidden="true" tabindex="-1"></a><span class="cf">ENDIF</span>()</span></code></pre></div>
<p>Ve make edip çalıştırıyoruz;</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb14-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> cmake ..</span>
<span id="cb14-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb14-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> make</span>
<span id="cb14-3"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> ./simpletest_raspicam_cv</span></code></pre></div>
<p>Yeni bir proje oluşturacaksanız bu dosyayı örnek alabilirsiniz.
<br>
<br>
GNU severler derneği üyeleri aşağıdakini kullanarak da çalıştırabilirler;</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb15-1"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> g++ simpletest_raspicam_cv.cpp <span class="at">-o</span>  simpletest_raspicam_cv <span class="at">-I</span>/usr/local/include/ <span class="at">-lraspicam</span> </span>
<span id="cb15-2"><a href="https://mcemilg.dev/posts/2016-12-10-raspicam.html#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="ex">-lraspicam_cv</span> <span class="at">-lmmal</span> <span class="at">-lmmal_core</span> <span class="at">-lmmal_util</span> <span class="at">-lopencv_core</span> <span class="at">-lopencv_highgui</span></span></code></pre></div>
<p>Soru, görüş ve önerileriniz için bana ulaşabilirsiniz!</p>]]></description>
    <pubDate>Sat, 10 Dec 2016 00:18:23 UT</pubDate>
    <guid>https://mcemilg.dev/posts/2016-12-10-raspicam.html</guid>
    <dc:creator>M. Cemil Güney</dc:creator>
</item>

    </channel>
</rss>
