<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmet Tuğrul Bayrak on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Tuğrul Bayrak on Medium]]></description>
        <link>https://medium.com/@ahmettugrulbayrak?source=rss-a46b24db02e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ddUXRfoZtrot0TE9.jpg</url>
            <title>Stories by Ahmet Tuğrul Bayrak on Medium</title>
            <link>https://medium.com/@ahmettugrulbayrak?source=rss-a46b24db02e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:26:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmettugrulbayrak/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Genetik Algoritmalar]]></title>
            <link>https://ahmettugrulbayrak.medium.com/genetik-algoritmalar-d6f004df2a30?source=rss-a46b24db02e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f004df2a30</guid>
            <category><![CDATA[levenshtein-distance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <dc:creator><![CDATA[Ahmet Tuğrul Bayrak]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 12:42:29 GMT</pubDate>
            <atom:updated>2021-11-19T12:44:04.824Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“Ne en güçlü olan tür hayatta kalır, ne de en zeki olan… Değişime en çok adapte olabilendir, hayatta kalan.”</em></blockquote><p>Diyor Charles Darwin. Bir evrimsel algoritma çeşidi olan genetik algoritmanın temelinde de bu yatıyor; ulaşılmak istenen hedefe adapte olmak.</p><p>Genetik algoritmalar, doğadaki evrimsel süreçleri baz alarak çalışan, optimizasyon ve arama problemlerinde kullanılan bir yöntemidir. Temel ilkesi, ulaşmak istenen hedefe götürecek adaylardan zayıf olanların elenerek en güçlü olanları kalmasıdır. Bilim, mühendislik, sosyal bilimler gibi hemen her alandaki problemlerde uygulanabilmektedir.</p><p>Yöntemden kısaca bahsetmek gerekirse, her bir aday çözüm bir kromozom ile temsil edilir. Kromozomu oluşturan genler ise aday çözümün sahip olduğu değerlerdir. Popülasyonda bulunan kromozomlar birbirleriyle etkileşime geçerek yeni nesiller üretir (cross-over) ve hedefe yaklaşmaya çalışır. Bununla beraber, doğadaki evrime benzer bir süreçle, topluluktaki bireyler değişikliğe uğrar (mutation). Bu işlemler sonucunda oluşan yeni bireyler eğer güçlülerse toplulukta yer almaya devam eder, eğer zayıflarsa elenerek topluluğun kalitesini düşürmezler. Bu şekilde, belirlenmiş olan hedefe ulaşıldığında/yaklaşıldığında ya da belirli bir iterasyon sayısı sonucunda genetik algoritma sonlanır.</p><p>Bahsedilen adım ve kavramların daha net oturması için anlaşılması kolay bir örnek üzerinden ilerleyeceğiz. Amacımız, rastgele 5 rakamdan oluşan ve toplandığında 100 yapan bir sayı dizisi oluşturmak.</p><p><strong>Bireylerin kromozom olarak temsili</strong></p><p>Popülasyondaki bireyler, biyolojideki kromozom kavramıyla temsil edilir. Kromozomu oluşturan genler ise, bireylerin özellikleridir. Problemimizi bu kavramlara uyarlayacak olursak, <em>[1, 23, 67, 12, 52]</em> değerlerinden oluşan bir kromozom şu şekilde gösterilebilir;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*yTj8vHAa3AisakX_PW_Ibw.png" /><figcaption>Şekil 1. Kromozom temsili</figcaption></figure><p>Genetik algoritmadaki en önemli adımlardan biri, kromozom temsilinin doğru ve etkili bir şekilde yapılmasıdır. Bu temsil, hem uygulamanın verimini hem de başarısını doğrudan etkiler.</p><p><strong>Popülasyon üretimi</strong></p><p>Problemin çözümüne ulaştıracak kromozomların genleri başlangıçta rastgele oluşturulabileceği gibi, probleme özgü mantıkla daha akıllı bir şekilde de oluşturulabilir. <em>N</em> sayıda kromozom ile oluşturulan popülasyon ile model iterasyona hazır hale gelir.</p><p><strong>Uygunluk değeri (Fitness value)</strong></p><p>Hedefimizi ne kadar yaklaştığımızı anlayabilmek için, popülasyondaki kromozomların (bireylerin) ne kadar güçlü/başarılı olduğu ölçülmelidir. Bu sayede, zayıf kromozomlar elenecek, popülasyonun kalitesi arttırılarak hedefe ulaşma ihtimali artacaktır. Genetik algoritma problemlerinin en önemli adımı, ulaşılmak istenen uygunluk değerinin ne olduğunun ve nasıl hesaplanacağının belirlenmesidir. Örneğimizdeki kromozom’un uygunluk değeri <em>|100-155| -&gt; 55</em> olarak hesaplanabilir. Aradaki fark sıfıra ne kadar yakınsa, o kromozom bizim için o kadar güçlüdür.</p><p><strong>Çaprazlama (Cross-over)</strong></p><p>Popülasyonu oluşturduktan sonra, seçilen 2 kromozom kendi aralarında etkileşime geçerek yeni kromozomlar üretirler. Bu etkileşim gen alışverişi şeklinde gerçekleşir. Örnek ikinci kromozomumuz <em>[45, 12, 8 ,6, 11]</em> iken bu iki kromozom, genlerinin (sayıların) bir kısmını değiştirerek yeni kromozomlar oluşturacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*X5cvzbcrVIudc8wjFJjE7A.png" /><figcaption>Şekil 2. Çaprazlanacak iki kromozom</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*iztOXzjsqqbgxC_ddT5NgQ.png" /><figcaption>Şekil 3. Çaprazlama sonrası oluşan yeni kromozomlar</figcaption></figure><p>Örnekte, birinci kromozomun ilk iki geni ile ikinci kromozomun son iki geni değiştirilmiştir. Bu işlem sonucunda, uygunluk değerleri 55 ve 18 olan iki kromozomdan, 41 ve 11 olan iki yeni kromozom elde edildi, ki bu yeni kromozomlardan biri bahsedilen dörtlü arasında en güçlü olanı.</p><p>Değiştirilen genler farklı şekillerde ya da tamamen rastgele de seçilebilir. Benzer şekilde hangi iki kromozomun çaprazlanacağının seçiminde de farklı yöntemler uygulanabilir. En güçlü kromozomların çaprazlanma ihtimalinin yüksek olduğu bir sistem kurulabileceği gibi, bu seçilim de tamamen rastgele yapılabilir.</p><p><strong>Mutasyon (Mutation)</strong></p><p>Popülasyondaki kromozomlar kendi aralarında gen alışverişi yaparak yeni bireyler oluştururlarken, belirli bir süre sonra gen çeşitliğinin az olmasında dolayı, popülasyon lokal minimum’da takılacak, daha güçlü kromozomlar oluşmayacaktır. Bu sorunu çözmek ve popülasyonda çeşitliliği arttırmak için, kromozomların genlerinin bir kısmı değiştirilerek, kromozomlar mutasyona uğratılır. Çaprazlama ile benzer şekilde, mutasyon sonucunda da daha güçlü bireyler oluşabilecekken, daha zayıf bireyler de oluşabilir. Ayrıca, mutasyon her iterasyonda yapılmak zorunda değildir. Belirli bir olasılık değeriyle ya da popülasyonun lokal minimum’a takıldığı durumlarda da uygulanabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*WKTsRp23cyx8fqwMS3RsWA.png" /><figcaption>Şekil 4. Mutasyon sonrası oluşan kromozom</figcaption></figure><p><strong>Eleme</strong></p><p>Çaprazlama ve mutasyon sonucunda oluşan yeni bireylerin uygunluk değerleri hesaplandıktan sonra, popülasyon sayısını sabit tutacak şekilde en zayıf adaylar (eskiden popülasyonda olan ya da yeni üretilen) elenir. Bu sayede, popülasyonun toplam başarısı artmış olabileceği gibi, daha da önemlisi azalmayacağı garanti altına alınmış olunur.</p><p>Yapılan tüm işlemleri toparlayacak olursak akış aşağıdaki şekildedir;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*wXUjh7E8MBy-Qu4bjoEmYg.png" /><figcaption>Şekil 5. Akış diyagramı</figcaption></figure><p><strong>Örnek uygulamalar</strong></p><p>Yukarıda bahsettiğimiz problem için, yani rastgele 5 farklı rakamdan oluşan kromozomlardan, sayı değerleri toplamı 100 yapan bir kromozom oluşturmaya çalışalım. Aşağıdaki 3 farklı çıktıda sırasıyla; çaprazlama ve mutasyon, sadece çaprazlama, sadece mutasyon uygulanmıştır. Grafiklerdeki “En küçük”, “En büyük” ve “Ortalama” değerleri sırasıyla; popülasyondaki en başarılı, en başarısız ve ortalama uygunluk değerlerini gösteriyor. Birinci yaklaşım, 48. iterasyonda istenen değere ulaşan sayıları üretmiştir (<em>[39, 11, 12, 30, 8]</em>). İkinci yaklaşımda ise 248. iterasyonda gerekli değere ulaşılmıştır (<em>[8, 9, 37, 9, 37]</em>). Üçüncü yaklaşımda ise 1000. İterasyon sonucu ulaşılmak istenen değere yaklaşılsa da, ulaşılamamıştır (<em>[22, 1, 10, 14, 55]</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*sY0wnrzYPkdZGV6-mbrj7A.png" /><figcaption>Şekil 6. Çaprazlama ve mutasyonun etkileri</figcaption></figure><p>Bu deney sonucunda, çaprazlama ve mutasyonun beraber kullanıldığı durumun en başarılı yöntem olduğu görülüyor. Sadece çaprazlamanın kullanıldığı ikinci yöntemde, gen alışverişi sonrasında çeşitlilik gittikçe azaldığından en düşük, en yüksek ve ortalama uygunluk değerleri birbirine yaklaşıyor. Sadece çaprazlama kullanmak çözümün lokal minimumda takılmasına sebep oluyor. Birinci yöntemde kullanılan mutasyon sayesinde çeşitlilik artıyor ve mavi renkli olan en güçlü uygunluk değeri ikinci yöntemdeki gibi sabit kalmıyor. Sadece mutasyon yapılan diğer yöntem ise rastgele arama (random search) yöntemi şeklinde davranıyor ve sonuca ulaşamıyor.</p><p>Uygulama olarak bir amacı olmasa da, genetik algoritmanın farklı bir alanda uygulamasını göstermek için ikinci bir deneme daha yapalım. Buradaki amacımız da, rastgele piksel değerlerinden oluşan kromozomlardan, istediğimiz bir görsele (Şekil 7) ulaşmak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*5DjxmMWyEZzmVSlJKrdnrA.png" /><figcaption>Şekil 7. Oluşturulmak istenen hedef görsel</figcaption></figure><p>Bu problemde uygunluk değeri olarak kromozomlarla orijinal görseldeki piksellerin farkını alalım. Fark ne kadar küçükse, orijinal görsele o kadar yakınız. Önceki probleme benzer bir mantıkla yaklaşılan bu problemde de, farklı iterasyonlardaki en güçlü kromozomlar ve modeldeki iyileşme aşağıdaki şekilde görülüyor;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*BMUgFtbVHGr8494mbmnrsg.gif" /><figcaption>Farklı iterasyonlardaki en güçlü kromozomlar</figcaption></figure><p>İlk uygulama, genetik algoritmaların çalışma mantığının daha rahat takip edilebilmesi için, daha verimli bir şekilde geliştirilebilecekken daha açık bir şekilde ve bir genetik algoritma kütüphanesi kullanılmadan yazıldı. İkinci uygulamanın kodu ise, hazır bir kütüphanenin nasıl kullanıldığı göstermek için PyGAD kütüphanesi kullanılarak yazıldı. Bu kodları github üzerinden inceleyebilirsiniz; <a href="https://github.com/tbayrak/genetic-algorithms/blob/main/basic_ga.py">örnek1</a>, <a href="https://github.com/tbayrak/genetic-algorithms/blob/main/image_generator_ga.py">örnek2</a></p><p>Teşekkürler:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f004df2a30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Word Embedding?]]></title>
            <link>https://ahmettugrulbayrak.medium.com/what-is-word-embedding-40e942a4fe02?source=rss-a46b24db02e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e942a4fe02</guid>
            <category><![CDATA[gensim]]></category>
            <category><![CDATA[fasttext]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[Ahmet Tuğrul Bayrak]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 21:40:36 GMT</pubDate>
            <atom:updated>2022-04-19T22:12:25.310Z</atom:updated>
            <content:encoded><![CDATA[<p>Word embedding is one of the fundamental concepts of natural language processing. Since the posts about word embedding methods are generally too technical, it might be difficult to understand for beginners. So, rather than mentioning how the methods work, I will simply talk about what they do and for what purpose they can be used.</p><p>A numerical form of data is required to create machine learning models. Therefore, data in other types should be converted into numerical form. Categorical data can be converted into numerical values in different ways. The values {“low”, “medium”, “high”} have a greatness relation and they can be represented by the numbers {1, 2, 3} in an ordered way. Or, if we have days of the week, they can be numbered from 1 to 7. In that case, although the 1st and 7th days are actually consecutive, the 7th day has a value far from the 1st day. In such cases, the categorical values are based on a sine or cosine wave, making the distance between values more realistic.</p><p>Of course, not all categorical data is sortable. If we have movie genres, such as {“horror”, “thriller”, “romantic”, “comedy”}, we can not assign sequential numbers to them. Then, the values can be represented with 0 or 1 with one-hot encoding. The numerical conversion of the data in a table with columns in the three cases we mentioned can be seen in Figure 1 (code sample<a href="https://github.com/tbayrak/word-embedding/blob/main/encoding_example__en.ipynb">*</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*3LKvUzB9GATDaIPkdsgLcQ.png" /><figcaption>Figure 1. Converting categorical data into numerical values</figcaption></figure><p>So far, we have talked about assigning numbers to the words, which is encoding. But in some cases, such a simple transformation may not be enough. If we want to cluster the data in the example, we do not do anything about the semantic relationships between the values, while the horror and thriller movies should be close in the genre.</p><p>If our variables were sentences, then how would we represent those sentences? The first method that comes to mind is to create a column (bag of words) for each word in the sentence, similar to encoding. Then, points can be given according to the frequency of occurrence of the words (TF-IDF). But here, too, we cannot catch the relationship between words. Also, this method is not applicable for more complex problems as we will need to create a new column for each value (curse of dimensionality). Let’s move on to embedding.</p><p>In embedding, words are located so that they are most closely related to the words they are with. This relation can be in many different categories. For example, the country name of England should be close to other country names, but also to the expressions that are specific to England. In this way, a structure with hundreds of layers can be established while creating an embedding model. The example below shows several countries, their capitals, and their relationship to a football team. While line number 1 keeps the country relation, line number 2 capitals, line number 3 football teams; Lines 4, 5 and 6 represent the country’s relation to its capital and its football team (Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*eeW6ngAgN33kfC6OtSZMiw.png" /><figcaption>Figure 2. A word space representation</figcaption></figure><p>Of course, this relation will not be the same in all. Countries can be mentioned more with each other or with a country capital. Figure 3 is a more accurate representation in this respect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Y2f4QSjKUsFm3BnbV9kzpA.png" /><figcaption>Figure 3. A more realistic word space representation</figcaption></figure><p>After learning what word embedding is, let’s talk about a few embedding methods. As mentioned earlier, the similarity of the words to each other is based on how often they appear together on the same sentences. Let’s retrieve some articles on “artificial intelligence” from Wikipedia and do an experiment. We’re going to use n-grams here. Although “n” is a variable value, it produces n words that are adjacent to each other.</p><p>“first example of word embedding”</p><p>2-grams of this sentence after removing stop-words;</p><p>“first example”</p><p>“example word”</p><p>“word embedding”</p><p>After doing the preprocessing steps on the corpus that we created with the data retrieved from Wikipedia and the content is put into the required format, let’s find the words that are adjacent to 2-grams and look at their frequencies. The 8 most common words, together with the word “artificial” can be seen in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*_t4ARZxPyZ_3WTjz0bgF0A.png" /><figcaption>Figure 4. Words close to the word “artificial”</figcaption></figure><p>Although our corpus is small, the results are reasonable. Accordingly, in our vocabulary, the word “artificial” should be the nearest to the word “intelligence”.</p><p>Word2Vec &amp; FastText, among the most used embedding methods, are artificial neural network models in which the words in the corpus are trained with CBOW or skip-gram. There are embedding models that are readily trained for many different languages. However, since these contain general expressions, they may not be very efficient in studies to be done specifically in a field. If there is enough data in field-specific studies, training a model specific to that area is also an option. Even necessary in most cases.</p><p>Let’s take chemistry-related content from Wikipedia this time and find the words nearest to the word “artificial” with 2-grams. Figure 5 contains the nearest words to the word “artificial” for artificial intelligence and chemistry contents. As can be seen, it is completely context-dependent and different outputs are produced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*WI93wLhbN45FlhktiMNaBQ.png" /><figcaption>Figure 5. 2-gram outputs created by the corpus of “artificial intelligence” and “chemistry”</figcaption></figure><p>Let’s train a FastText model this time with the assembly we have. As a result of the trained model, words are located in the word space according to many different categories. Figure 6 shows the 60-dimensional vector created for the word “artificial” (code sample <a href="https://github.com/tbayrak/word-embedding/blob/main/embedding_example__en.ipynb">*</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*kWv_kDHOfJjc1w0XR2KuhA.png" /><figcaption>Figure 6. Vector showing the position of the word “artificial” in the word space.</figcaption></figure><p>And again, based on the model, words that are close to the word “artificial” are present in Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*VGlUh0xaLZ0zaziK-1olqg.png" /><figcaption>Figure 7. Words that are close to the word “artificial” with the FastText model</figcaption></figure><p>The word spaces created by the model established with the words in the corpus can be visualized at <a href="https://projector.tensorflow.org/">https://projector.tensorflow.org/</a>. To do that, you should create a file with the .tsv extension (code sample <a href="https://github.com/tbayrak/word-embedding/blob/main/embedding_example__en.ipynb">*</a>). The word space of the FastText model we have trained is as follows (Figure 8). The word space is a small space because the corpus is not too big. The relationships are shown simply in Figure 3 actually consist of many more layers in this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*DQjuO87bTfp1achm0nOU2Q.png" /><figcaption>Figure 8. Word space in the model</figcaption></figure><p>To emphasize again that the models we have created with “artificial intelligence” and “chemistry” corpus produce content-specific output, we see the nearest words to the word “artificial” for models in Figure 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*ALvOhNNm8_diLxrBInPdtA.png" /><figcaption>Figure 9. Words close to the word “artificial” in “artificial intelligence” and “chemistry” models</figcaption></figure><p>Finally, let’s briefly talk about the advantages of the FastText model. FastText, which is based on Word2Vec, also works for words that are not in the collection or are misspelled. When we want to find the closest words to the word “artifcial” with FastText, we get a result like in Figure 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*B1yUfH7cMqEK0RSkTxHLNw.png" /><figcaption>Figure 10. Words that are close to the misspelled word “artifcial”</figcaption></figure><p>When we try the same expression with the word2Vec model, we get the following error:</p><pre>KeyError: “word ‘artifcial’ not in vocabulary”</pre><p>FastText has this characteristic since, during the model training, small parts (characters grams) of the words are used. Because it is a more advanced model, it takes longer to train and occupies more memory than word2Vec. It can be decided which one to choose according to the needs and time/memory constraints.</p><p>I tried to explain the word embedding concept in a simple way without going into too much detail. Experiments can be done on a different corpus with code samples. In my next article, I will talk about embedding methods in more detail and compare the methods used.</p><p>Teşekkürler:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e942a4fe02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Word Embedding Nedir?]]></title>
            <link>https://ahmettugrulbayrak.medium.com/word-embedding-nedir-6d49b6a91fd2?source=rss-a46b24db02e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d49b6a91fd2</guid>
            <category><![CDATA[gensim]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[fasttext]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[Ahmet Tuğrul Bayrak]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 21:40:12 GMT</pubDate>
            <atom:updated>2021-04-21T12:34:47.352Z</atom:updated>
            <content:encoded><![CDATA[<p>Word embedding, doğal dil işlemenin temel kavramlarındandır. Word embedding yöntemleri ile ilgili yapılan paylaşımlar genel olarak fazla teknik olduğundan, bu konulara yeni başlamış kişiler için anlaması zor olabiliyor. Bu yüzden, kullanılan birkaç yöntemin nasıl çalıştıklarından ziyade, sade bir şekilde ne yaptıklarından ve hangi amaçla kullanıldıklarından bahsedeceğim.</p><p>Makine öğrenmesi algoritmaları ile model oluşturmak için, verilerin nümerik halde olması yani sayılardan oluşması gerekmektedir. Bu yüzden diğer tiplerde bulunan veriler de nümerik hale çevrilmeli. Kategorik veriler farklı şekillerde nümerik hale dönüştürülebilir. Aralarında büyüklük ilişkisi olan {“az”, “orta”, “çok”} değerleri {1, 2, 3} rakamları ile yine sıralı bir şekilde temsil edilebilir. Ya da elimizde haftanın günleri varsa bunlar da 1–7 arası numaralandırılabilir. Bu durumda da 1. ve 7. gün aslında art arda olmasına rağmen 7. gün 1. günden uzak bir değere sahip oluyor. Bu tür durumlarda kategorik değerler bir sinüs ya da cosinus dalgası üzerine oturtularak, değerler arasındaki mesafe daha gerçekçi bir hal alır.</p><p>Tabi ki kategorik verilerin hepsi sıralı olmak zorunda değil. Elimizde film türleri varsa, {“korku”, “gerilim”, “romantik”, “komedi”} gibi, bunlar için sıralı sayılar verme şansımız yok. Bu durumda da, yani aralarında sıralı bir ilişki bulunmayan kategorik değerler ise one-hot encoding ile 0 ya da 1 ile temsil edilebilir. Bahsettiğimiz üç durumun olduğu kolonlara sahip bir tablodaki verilerin nümerik hale dönüştürülmesi Şekil 1&#39;de görülebilir (kod örneği <a href="https://github.com/tbayrak/word-embedding/blob/main/encoding_example__tr.ipynb">*</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nMAjl_qutxX7j9zXo_kmKQ.png" /><figcaption>Şekil 1. Kategorik verilerin nümerek hale dönüştürülmesi</figcaption></figure><p>Şu ana kadar bahsettiğimiz kısımda bir kelime bir sayısal değer ile eşleştirildi, yani encoding yapmış olduk. Ama bazı durumlarda bu kadar basit bir dönüşüm yeterli olmayabiliyor. Örnekteki veriyi kümelemek istesek, korku ve gerilim türünden filmlerin tür bazında yakın olması gerekirken değerler arasındaki anlamsal ilişkiler için bir şey yapmadık.</p><p>Peki değişkenlerimiz cümle olsa, bu durumda o cümleleri nasıl temsil ederdik? Akla ilk gelebilecek yöntem, encoding’e benzer şekilde cümledeki her bir kelime için bir kolon oluşturmak (bag of words). Sonra da kelimelerin geçme sıklığına göre de puan verilebilir (TF-IDF). Ama burada da kelimeler arasındaki ilişkiyi yakalayamıyoruz. Ayrıca her bir değer için yeni bir kolon oluşturmamız gerekeceğinden, daha karmaşık problemler için bu yöntem pek uygulanabilir değil (curse of dimensionality). O zaman embedding’e geçiyoruz.</p><p>Embedding’te, kelimeler en fazla beraber bulundukları kelimeler ile yakın olacak şekilde konumlandırılır. Bu yakınlık farklı birçok kategoride olabilir. Örneğin İngiltere ülke adı olarak diğer ülke isimleriyle yakın olmalı, aynı zamanda İngiltere’ye özgü olan ifadelere de. Bu sayede bir embedding modeli oluştururken yüzlerce katmanlı bir yapı kurulabilir. Aşağıdaki örnekte birkaç ülke, başkentleri ve ülkenin bir futbol takımıyla ilişkisi görülüyor. 1 numaralı doğru ülke yakınlıklarını, 2. numaralı doğru başkentleri, 3. numaralı doğru futbol takımlarını tutarken; 4, 5 ve 6 numaralı doğrular ise o ülkenin kendi başkenti ve futbol takımına olan yakınlığını temsil ediyor (Şekil 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*dBpil48R2a6EZlSf_05NCA.png" /><figcaption>Şekil 2. Kelime uzayı temsili</figcaption></figure><p>Tabi bu yakınlık hepsinde aynı olmayacaktır. Ülkeler birbirleriyle ya da bir ülke başkenti ile daha fazla anılabilir. Şekil 3 bu açıdan daha doğru bir temsil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*fzBUlc55CONcJBNTeZZr5w.png" /><figcaption>Şekil 3. Daha gerçekçi bir kelime uzayı temsili</figcaption></figure><p>Embedding’in ne olduğunu öğrendikten sonra birkaç embedding yöntemine değinelim. Bahsedildiği gibi, kelimelerin birbirlerine olan yakınlıklarında, beraber geçtikleri kelimeler baz alınır. Wikipedia’dan “yapay zeka” konulu birkaç içerik çekip bir deneme yapalım. Burada n-gram kullanacağız. “n” değişebilen bir değer olmakla beraber, yan yana olan n kelimeyi üretir.</p><p>“word embedding konusunun ilk örneği”</p><p>Cümlesinin 2-gram’ları;</p><p>“word embedding”</p><p>“embedding konusunun”</p><p>“konusunun ilk”</p><p>“ilk örneği”</p><p>Wikipedia’dan çektiğimiz verilerle oluşturduğumuz derlem (corpus) üzerinde ön işleme adımlarını yaptıktan sonra içerik gerekli formata sokulduktan sonra, 2-gram ile yan yana geçen kelimeleri bulup, frekanslarına bakalım. “yapay” kelimesi ile beraber en fazla geçen 8 kelime Şekil 4’te görülüyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*rWugqh3q_uwvaRH0vuBLPg.png" /><figcaption>Şekil 4. “yapay” kelimesine yakın olan kelimeler</figcaption></figure><p>Derlemimiz küçük olsa da çıkan sonuçlar makul. Buna göre kelime uzayımızda “yapay” kelimesine en yakın “zeka” kelimesi olmalı.</p><p>En çok kullanılan embedding yöntemlerinden word2Vec &amp; FastText, derlemdeki kelimelerin, CBOW ya da skip-gram ile eğitilmiş olduğu yapay sinir ağı modelleridir. Birçok farklı dil için hazır olarak eğitilmiş embedding modelleri bulunuyor. Ama bunlar genel ifadeleri içerdiklerinden, bir alana özgü yapılacak çalışmalarda fazla verimli olmayabiliyor. Alana özgü yapılacak çalışmalarda, yeterli miktarda veri bulunması halinde o alana özgü bir model eğitmek de bir seçenek. Hatta çoğu durumda gerekli.</p><p>Wikipedia’dan bu sefer de kimya ile ilgili bir içerik çekip 2-gram ile “yapay” kelimesine en yakın olan kelimeleri bulalım. Şekil 5’te yapay zeka ve kimya içerikleri için “yapay” kelimesine en yakın kelimeler bulunuyor. Görüldüğü gibi tamamen içeriğe bağlı ve farklı çıktılar üretiliyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*APc75ZSZc005i814Mv6gUg.png" /><figcaption>Şekil 5. “yapay zeka” ve “kimya” içerikli derlemler ile oluşturulan 2-gram çıktıları</figcaption></figure><p>Elimizdeki derlem ile bu sefer bir FastText modeli eğitelim. Eğitilen model sonucunda kelimeler birçok farklı kategoriye göre uzaya yerleştiriliyor. Şekil 6’da “yapay” kelimesi için oluşturulmuş 60 boyutlu vektör görülüyor (kod örneği <a href="https://github.com/tbayrak/word-embedding/blob/main/embedding_example__tr.ipynb">*</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*kWv_kDHOfJjc1w0XR2KuhA.png" /><figcaption>Şekil 6. “yapay” kelimesinin kelime uzayındaki konumunu gösteren vektör</figcaption></figure><p>Ve yine kurulan modele göre “yapay” kelimesine yakın olan kelimeler Şekil 7’de mevcut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*MV3Bepnu9_B9H_IukEeDmw.png" /><figcaption>Şekil 7. FastText modeli ile “yapay” kelimesine yakın olan kelimeler</figcaption></figure><p>Derlemde geçen kelimeler ile kurulan modelin oluşturduğu kelime uzayları <a href="https://projector.tensorflow.org/">https://projector.tensorflow.org/</a> sitesinden görselleştirilebilir. Bunun için model’den oluşturulan .tsv uzantili dosya yeterli (kod örneği <a href="https://github.com/tbayrak/word-embedding/blob/main/embedding_example__tr.ipynb">*</a>). Eğittiğimiz FastText modelinin kelime uzayı ise şu şekilde aşağıdaki gibi (Şekil 8). Derlem fazla deniş olmadığından küçük bir uzay. Şekil 3&#39;te basitçe gösterilen ilişkiler, aslında bu şekilde çok daha fazla katmandan oluşuyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*VLssGz3rwnPChVN8IOl2uw.png" /><figcaption>Şekil 8. Modeldeki kelime uzayı</figcaption></figure><p>“yapay zeka” ve “kimya” derlemleri ile oluşturduğumuz modellerin, içeriğe özgü çıktı ürettiğini tekrar vurgulamak için, modeller için “yapay” kelimesine en yakın kelimeleri de Şekil 9’da görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*1_vue2ZmUTHe_LsXiA7sJQ.png" /><figcaption>Şekil 9. “yapay zeka” ve “kimya” modellerinde “yapay” kelimesine yakın olan kelimeler</figcaption></figure><p>Son olarak, kısaca FastText modelinin avantajlarından bahsedelim. Word2Vec’i baz alarak çalışan FastText derlemde bulunmayan ya da yanlış yazılan kelimeler için de çalışıyor. FastText ile “yapy” kelimesine en yakın kelimeleri bulmak istediğimizde Şekil 10’daki gibi bir sonuç alıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*MssOwCzK2lzhW_pyO-EYPw.png" /><figcaption>Şekil 10. Yanlış yazılmış “yapy” kelimesine yakın olan kelimeler</figcaption></figure><p>Aynı ifadeyi word2Vec modeli ile denediğimizde ise şu hatayı alıyoruz:</p><pre>KeyError: “word ‘yapy’ not in vocabulary”</pre><p>FastText’e bu özelliği veren, model eğitimi sırasında, kelimelerin küçük parçalar (karakter gramları) halinde eğitilmesi. Daha gelişmiş bir model olması sebebiyle word2Vec’e göre, hem eğitilmesi daha uzun sürüyor ve hafızada daha fazla yer kaplıyor. İhtiyaca ve zaman/hafıza kısıtlarına göre hangisinin seçileceği karar verilebilir.</p><p>Word embedding kavramını fazla detaya girmeden, sade bir şekilde anlatmaya çalıştım. Kod örnekleri ile farklı derlemler üzerinde denemeler yapılabilir. Sonraki yazımda, embedding yöntemlerinden daha detaylı bahsedip, kullanılan yöntemleri karşılaştıracağım.</p><p>Teşekkürler:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d49b6a91fd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Genetic Algorithm?]]></title>
            <link>https://ahmettugrulbayrak.medium.com/what-is-a-genetic-algorithm-6eb51cbb22e1?source=rss-a46b24db02e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eb51cbb22e1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[levenshtein-distance]]></category>
            <dc:creator><![CDATA[Ahmet Tuğrul Bayrak]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 21:29:53 GMT</pubDate>
            <atom:updated>2022-04-19T22:41:26.913Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“It is not the strongest species that survive, nor the most intelligent, but the ones most responsive to change.”</blockquote><p>Says Charles Darwin. This is the basis of the genetic algorithm, which is a type of evolutionary algorithm; To adapt to the desired goal. The genetic algorithm is a method used in optimization and search problems based on evolutionary processes in nature. Its basic principle is to eliminate the weakest candidates and keep the strongest ones. It can be applied to problems in almost every field such as applied sciences, engineering, social sciences.</p><p>To briefly mention the method, each candidate solution is represented by a chromosome. The genes that make up the chromosome are the values of the candidate solution. The chromosomes in the population interact with each other to generate new generations (cross-over) and try to get closer to the target. Besides, in a process similar to evolution in nature, individuals in the population change (mutation) over time. New individuals formed as a result of these processes continue to be in the population if they are strong; otherwise, they are eliminated for the sake of not reducing the quality of the community. In this way, the genetic algorithm is terminated when the specified target is reached/approached or as a result of a certain number of iterations.</p><p>We will proceed with an easy-to-understand example to make the mentioned steps and concepts more clear. Our goal is to create a sequence of random 5 numbers, which makes 100 when added.</p><p><strong>Representation of individuals as chromosomes</strong></p><p>Individuals in the population are represented by the chromosome concept in biology. The genes that make up the chromosome are the features of individuals. If we adapt our problem to these concepts, a chromosome consisting of the values [1, 23, 67, 12, 52] can be seen in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*_xCLSnCHRVY_logeNIBTXw.png" /><figcaption>Figure 1. Chromosome representation</figcaption></figure><p>One of the essential steps in the genetic algorithm is the correct and efficient chromosome representation. This representation directly affects both the efficiency and success of the application.</p><p><strong>Population generation</strong></p><p>The group of the chromosomes that will lead to the solution of the problem can be generated randomly at the beginning, or they can be created more intelligently with the logic specific to the problem. With the population created with N number of chromosomes, the model becomes ready for iteration.</p><p><strong>Fitness value</strong></p><p>How strong/successful the chromosomes (individuals) in the population are must be measured in order to understand how close we are to our goal. In this way, weak chromosomes will be eliminated, the quality of the population will increase and the probability of reaching the target will increase. The most important step in the genetic algorithm problems is to determine what the fitness value is desired to be reached and how it will be calculated. The fitness value of the chromosome in our example can be calculated as | 100–155 | -&gt; 55. The closer the difference is to zero, the stronger that chromosome is for us.</p><p><strong>Cross-over</strong></p><p>After creating the population, the 2 selected chromosomes interact with each other to produce new chromosomes. This interaction takes place in the form of gene exchange. While our example is our second chromosome [45, 12, 8, 6, 11], these two chromosomes will change some of their genes (numbers) to form new chromosomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*p5qH-qIHzu3pIkSd1lL0Jw.png" /><figcaption>Figure 2. Two chromosomes to cross-over</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*3qD-iRvmNi7AHJbM8avG2A.png" /><figcaption>Figure 3. New chromosomes formed after cross-over</figcaption></figure><p>In the example, the first two genes of the first chromosome and the last two genes of the second chromosome have been replaced (Figure 2). As a result of this process, two new chromosomes with fitness values 48 and 11 are obtained from the two chromosomes with fitness values 55 and 18 (Figure 3). The altered genes can be chosen in different ways or completely at random. Similarly, different methods can be applied to choose which two chromosomes to cross. Just as one approach with a high probability of crossing the strongest chromosomes can be applied, this selection can be completely random.</p><p><strong>Mutation</strong></p><p>While the chromosomes in the population create new individuals by exchanging genes among themselves (Figure 4), after a certain period of time due to the low gene variety, the population will be attached at the local minimum and stronger chromosomes will not be formed. To solve this problem and increase the diversity in the population, some of the genes of the chromosomes are changed and the chromosomes are mutated. Similar to cross-over, both stronger or weaker individuals may be formed as a result of mutation. Also, the mutation does not have to be made in every iteration. It can also be applied with a certain probability value or in cases where the population is stuck to the local minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*WKTsRp23cyx8fqwMS3RsWA.png" /><figcaption>Figure 4. Chromosome formed after mutation</figcaption></figure><p><strong>Elimination</strong></p><p>After the fitness values of new individuals formed as a result of cross-over and mutation are calculated, the weakest candidates (formerly in the population or newly produced) are eliminated to keep the population number constant. In this way, it is ensured that the total success of the population may be increased, and more importantly, it is guaranteed that it will not decrease. If we sum up all the transactions made, the flow is as follows in Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*LKbqEh77nWVCGn7KqaGGrw.png" /><figcaption>Figure 5. Genetic algorithm flow</figcaption></figure><p><strong>Example applications</strong></p><p>For the problem mentioned above, let’s try to create a chromosome from chromosomes consisting of 5 random numbers, whose numerical values add up to 100. In the following 3 different outputs, respectively; mutation only, cross-over only, cross-over and mutation together were applied. The “Smallest”, “Largest” and “Average” values in the graphs are respectively; shows the most successful, unsuccessful and average fitness values in the population (Figure 6). The third approach produced numbers that reached the desired value in the 48th iteration ([39, 11, 12, 30, 8]). In the second approach, the required value was reached at the 248th iteration ([8, 9, 37, 9, 37]). In the first approach, although the desired value was approached as a result of the 1000th iteration, it was not reached ([22, 1, 10, 14, 55]).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*0FqYr36K9xRyKaDF-eIjTA.png" /><figcaption>Figure 6. Effects of cross-over and mutation</figcaption></figure><p>As a result of this experiment, it is seen that using cross-over and mutation together is the most successful method. For the method where the only cross-over is used, the lowest, highest and average fitness values converge as the diversity gradually decreases after gene exchange. Also, using only the cross-over causes the solution to be stuck at a local minimum. The other method with only mutations acts as a random search method and cannot reach the result. In the case where mutation and crossing are used together, the diversity increases thanks to the mutation and the strongest fitness value, which is blue, does not remain stationary as in the second method.</p><p>Let’s do a second example to illustrate the application of the genetic algorithm in a different field, although it has no purpose as a practice. This time, our goal is to get a target sentence from random letters. As the fitness value, let’s use the Leveinstein distance, which indicates how many changes need to be made to get from one expression to the other one. The smaller this distance, the closer the two expressions will be. We are trying to converge to the target of the genetic algorithm (<em>“genetic algorithm is actually pretty cool”</em>), which is established with a structure similar to the previous example. Figure 7 shows the population’s strongest chromosome in each iteration and the fitness value of that chromosome. In this way, we achieve the goal by getting better step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*dSRRpMxY9V_qwU7U0IQuvg.png" /><figcaption>Figure 7. Steps to converge to the target sentence</figcaption></figure><p>Finally, for another example, let’s try to reach a target image (Figure 8) by using random pixel values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*5DjxmMWyEZzmVSlJKrdnrA.png" /><figcaption>Figure 8. Target image to be created</figcaption></figure><p>In this problem, we take the difference between the chromosomes and the pixels in the original image as the fitness value. The smaller the difference, the closer we are to the original image. The strongest chromosomes in different iterations and the improvement in the model are shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*xUkdQRm9-YhYf9Zk627Fqw.gif" /><figcaption>Strongest chromosomes in different iterations</figcaption></figure><p>The first two applications were implemented not in the most efficient but a straightforward way in order to follow the working logic of genetic algorithms better without using a library. Yet, the code for the last example was developed using the PyGAD to show how to use a library for genetic algorithms. You can access these codes of the examples on GitHub; <a href="https://github.com/tbayrak/genetic-algorithms/blob/main/basic_ga.py">example1</a>, <a href="https://github.com/tbayrak/genetic-algorithms/blob/main/sentence_generator_ga">example2</a>, <a href="https://github.com/tbayrak/genetic-algorithms/blob/main/image_generator_ga.py">example3</a>.</p><p>Teşekkürler:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eb51cbb22e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>