<?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 İbrahim Halil Kaplan on Medium]]></title>
        <description><![CDATA[Stories by İbrahim Halil Kaplan on Medium]]></description>
        <link>https://medium.com/@ibrahimhalilkaplan1?source=rss-dd99dfacf7df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_ICgJKkN4DjXGh2p.jpg</url>
            <title>Stories by İbrahim Halil Kaplan on Medium</title>
            <link>https://medium.com/@ibrahimhalilkaplan1?source=rss-dd99dfacf7df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:45:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibrahimhalilkaplan1/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[Scikit-Learn Kütüphanesi ile Data Ölçeklendirme]]></title>
            <link>https://medium.com/machine-learning-t%C3%BCrkiye/scikit-learn-k%C3%BCt%C3%BCphanesi-ile-data-%C3%B6l%C3%A7eklendirme-86dbff831393?source=rss-dd99dfacf7df------2</link>
            <guid isPermaLink="false">https://medium.com/p/86dbff831393</guid>
            <category><![CDATA[standardization]]></category>
            <category><![CDATA[scaler]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İbrahim Halil Kaplan]]></dc:creator>
            <pubDate>Mon, 24 Jan 2022 21:41:28 GMT</pubDate>
            <atom:updated>2022-01-26T09:08:21.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*19pvcrmhruiqNpjlTHJasg.jpeg" /><figcaption>Aslan kadar aslan olmalı. Belki de kedi kadar olmalı :))</figcaption></figure><p>Datayı ölçeklendirme, verilerin standartlaştırılması için gerekli olan önemli ön işlemlerden biridir. Her sütundaki değer aralığı çok farklı olduğunda, bunları ortak bir düzeye indirgememiz yani ölçeklendirmemiz gerekir. Bu sebeple, makine öğrenmesi algoritmalarından önce bazı ön işlemler yapmamız algoritmamızın başarısı için çok önemli bir husustur. Bunlar eksik değerlerin ve aykırı değerlerin ele alınması ve veri temizliği gibi bazı temel veri analizi süreçleri olabileceği gibi esas inceleyeceğimiz konu ölçekleme yani veri dönüştürmedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*9O5dr8WwpZmXwxaU5c99ZA.png" /><figcaption>Böyle bir kümeleme olmaz olsun !</figcaption></figure><p>Ölçekleme zorunlu değildir, yukarıdaki gibi ölçeklenmemiş bir data ile çok kötü bir sonuç alabiliriz. Ölçeklemenin temel amacı, daha büyük sayısal aralıkların etkilerinden kaçınmaktır ve bazı makine öğrenimi algoritmalarından önce verileri ölçeklendirmek daha iyi performans gösterecektir. Özellikle KNN (k-En Yakın Komşu), K-Means Clustering, SVM (Support Vector Machine), PCA (Principal Component Analysis) algoritmaları gibi mesafenin önemli olduğu makine öğrenmesi algoritmaları için çok önemlidir.</p><p>Aşağıdaki dağılım grafiklerinde, PCA sürecinde ölçekleme kullanılan ile ölçekleme olmayan arasındaki farkı kontrol edebilirsiniz. Gördüğünüz gibi veriler arasındaki mesafe ölçekleme olmadan çok geniştir, bu nedenle noktaları ayırmak zordur. Ölçekleme kullanıldığında ise sınıflandırma kolaylaştığından verimlilik artar ve modelimiz daha iyi bir performans sağlar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Y61YmuYn3Pei3fSOoXtOAA.png" /></figure><p>Daha önce belirtildiği gibi, ölçeklemenin amacı, veri kümesindeki her bir veriyi birbirine yaklaştırmaktır. Diğer amaç, hesaplama sırasında bazı sayısal zorluklardan kaçınmaktır. Örneğin Gradient Descent tabanlı optimizasyon algoritması ölçeklemeyi sever ve ölçekleme ile daha iyi performans gösterir. Gradient Descent kullanan yaygın algoritmalar olan Lineer Regresyon ve Lojistik Regresyon da ölçeklenebilir. Diğer makine öğrenimi algoritmaları ve Sinir Ağları için de ölçekleme uygulayabiliriz. Daha iyi performans ve daha iyi sonuçlar elde edebiliriz. Sonuçları ölçekleme ile ve ölçekleme olmadan karşılaştırabiliriz. Karar Ağacı, Rastgele Orman, Adaboost gibi bazı algoritmaların ölçeklenmesine gerek yoktur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vayZwV0LsydyfOBbESPZiA.png" /><figcaption><a href="https://stackoverflow.com/questions/46686924/why-scaling-data-is-very-important-in-neural-networklstm/46688787#46688787">Kaynak</a></figcaption></figure><p>Ölçekleme tiplerinden en çok kullanılanlar üzerinden devam edelim. StandardScaler, RobustScaler, MinMaxScaler ve MaxAbsScaler.</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler"><strong>1- StandardScaler</strong></a></p><p>StandardScaler, ortalamaya dayalı bir ölçekleme yöntemidir. StandardScaler formülü (Xi-Xmean)/Xstd’dir, bu nedenle ortalamayı 0 olarak ayarlar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*zWEteb3XuPnSBSGGZ742Nw.jpeg" /><figcaption><a href="https://www.geeksforgeeks.org/ml-feature-scaling-part-2/">Kaynak</a></figcaption></figure><p>StandardScaler, aykırı değerlerden olumsuz etkilenir çünkü aykırı değerler ortalamayı etkiler. Normal bir dağılımınız varsa veya normale yakın verileriniz varsa, StandardScaler verilerinizi standart normal dağılıma yaklaştırır. Ancak, aykırı değerleriniz varsa StandardScaler iyi performans göstermez. StandardScaler’ı grafiklerde kontrol edelim:</p><pre>from sklearn.preprocessing import StandardScaler<br>df_scale = StandardScaler().fit_transform(df)</pre><p>Burada öncelikle şu hususu anlatmalıyım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*0Wxo2lqj5txG4aqbK_RmkQ.png" /><figcaption><a href="https://www.statisticshowto.com/probability-and-statistics/skewed-distribution/">Kaynak</a></figcaption></figure><p>Yukarıda gördüğünüz normal dağılımdır ve sağa ya da sola bir eğilim, meyil ya da çarpıklık yoktur. Sola eğik bir dağılımın uzun bir uzantısı vardır. Sola çarpık dağılımlara negatif çarpık dağılımlar da denir. Bunun nedeni, sayı doğrusunda negatif yönde uzun bir kuyruk olmasıdır. Ortalama aynı zamanda zirvenin solundadır.</p><p>Sağa eğik bir dağılımın uzun bir sağ kuyruğu vardır. Sağa çarpık dağılımlara pozitif çarpık dağılımlar da denir. Bunun nedeni, sayı doğrusunda pozitif yönde uzun bir kuyruk olmasıdır. Ortalama da tepenin sağındadır. Sağa eğimli ve sola eğimli dağılımlara dair mod, meydan ve ortalama bilgileri de aşağıdaki görselde gösterilmektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*4n2tvkqwpREDFaXl56FpLA.jpeg" /><figcaption><a href="https://www.statisticshowto.com/probability-and-statistics/skewed-distribution/">Kaynak</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ok55cj5H_mTMY565q-DgVw.png" /></figure><p>Yukarıdaki örneğimizde ise şekilden de anlaşılacağı üzere sağa eğimli verilerimiz bulunmaktadır. StandardScaler uygulamasından sonra verilerimiz 0 civarında kümelenir, ancak yine de sağa çarpıktır ve büyük bir ölçeğe sahiptir (-1 ve 3). Veriler kümelenmiş durumda ve büyük aykırı değerlere sahip değildir. Aykırı değer olarak daha büyük değerlerimiz varsa, StandardScaler ile iyi sonuçlar alamayız. Çünkü aykırı değerler bu örnekte olduğu gibi tüm ölçekleme verilerini etkileyecektir. Bu gibi durumlarda, öncelikle aykırı değerleri kaldırmak daha iyidir. Şimdilik log dönüşümünü kullanacağız. Aykırı değerlerle başa çıkma yöntemlerine dair detaylı bilgilere <a href="https://hersanyagci.medium.com/detecting-and-handling-outliers-with-pandas-7adbfcd5cad8">buradan</a> ulaşabilirsiniz.</p><pre>from sklearn.preprocessing import StandardScaler<br>import numpy as np</pre><pre>df_log = np.log(df)<br>df_scale = StandardScaler().fit_transform(df_log)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wpGjZRxlmGYvEDu-2JiY_Q.png" /></figure><p>Log dönüşümü, veri dağılımını normal dağılıma dönüştürür. Dönüşümden sonra, StandardScaler uygulaması verilerimizi standart normal dağılıma yakınlaştırır. Bu yöntem daha iyi performans gösterir ve aykırı değerlerin etkilerini ortadan kaldırır. StandardScaler’ı aykırı olmayan verilere uygulamak daha iyidir.</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html#sklearn.preprocessing.RobustScaler"><strong>2 - RobustScaler</strong></a></p><pre>from sklearn.preprocessing import RobustScaler</pre><p>RobustScaler, medyan tabanlı bir ölçekleme yöntemidir. RobustScaler formülü (Xi-Xmedian) / Xiqr olduğundan aykırı değerlerden etkilenmez. Medyan kaldırarak veriler nicelik aralığına göre ölçeklenir (IQR: Interquartile Range). IQR, 1. çeyrek (25. nicelik) ile 3. çeyrek (75. nicelik) arasındaki aralıktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*9g4ekhRB326uwZm2cW_9Hw.png" /><figcaption><a href="https://seleritysas.com/blog/2020/12/18/techniques-of-feature-scaling-with-sas-custom-macro/">Kaynak</a></figcaption></figure><p>Çeyrekler arası aralığı kullandığından, ölçekleme sırasında aykırı değerlerin etkilerini minimum hale getirir. Çeyrekler arası aralık (Q3 — Q1), veri noktasının yarısına sahiptir. Modelini etkileyebilecek aykırı değerleriniz varsa ve bunları kaldırmak istemiyorsanız, RobustScaler en iyi seçimdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*WqL7CYKqt-B4u8d_hdMoWw.png" /></figure><p>Yukarıda, orijinal veriler (ölçeksiz) 250000 ve 200000 noktalarında aykırı değerlere sahiptir, RobustScaler’dan sonra 150 ve 200 olarak değişirler, ancak StandardScaler onları 25 ve 35 yapar. Aykırı değerler StandardScaler’ı etkiler ve ortalama noktaya çok yaklaşır. RobustScaler, aykırı değerleri veri ortalamasından uzakta olmaları gereken yerde tutar.</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler"><strong>3 - MinMaxScaler</strong></a></p><pre>from sklearn.preprocessing import MinMaxScaler</pre><p>Datamızın özelliklerini/değişkenlerini normalleştirmenin bir başka yolu (özellikleri μ=0 ve σ=1 olacak şekilde ölçekleyen standardizasyon dışında) Min-Max ölçekleyicidir. Bunu yaparak, tüm özellikler [0,1] aralığına dönüştürülecektir, yani bir özelliğin/değişkenin minimum ve maksimum değeri sırasıyla 0 ve 1 olacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*-axEn9iot1cIzangHiioZg.jpeg" /><figcaption><a href="https://www.geeksforgeeks.org/ml-feature-scaling-part-2/">Kaynak</a></figcaption></figure><p>Ölçekleme minimum ve maksimum noktalarla hesaplanır, bu nedenle veriler aykırı değerlerden etkilenebilir. Aykırı değerler için uygun değildir. MinMaxScaler’ı uygulamadan önce aykırı değerlerle ilgili işlemler yapmak faydalı olacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5jqLobCG13efNe86Ys5b7Q.png" /></figure><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MaxAbsScaler.html#sklearn.preprocessing.MaxAbsScaler"><strong>4 - MaxAbsScaler</strong></a></p><p>MaxAbsScaler, eğitim setindeki her bir özelliğin maksimum mutlak değeri 1.0 olacak şekilde her özelliği ayrı ayrı ölçekleyerek dönüştürür. Verileri kaydırmaz/ortalamaz ve bu nedenle herhangi bir seyrekliği yok etmez.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*AtRSAmnMpketjGvEvwCmtg.png" /><figcaption><a href="https://towardsdatascience.com/everything-you-need-to-know-about-min-max-normalization-in-python-b79592732b79">Kaynak</a></figcaption></figure><p>Veriler negatif değerlere sahipse, MaxAbsScaler verileri -1 ile 1 arasında ayarlar. Verileri mutlak maksimuma göre ölçeklendirir, bu nedenle aykırı değerler için uygun değildir. Aykırı değerlerle işleme gibi ön işlemeye ihtiyaç duyar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*iNMDUhnWwcaz502QWRCCfQ.png" /></figure><p>Sonuç</p><p>Ölçeklendirmenin temel amacı, her bir değişkeni standart bir ölçekte yeniden ifade etmek ve optimizasyon algoritmalarını hızlandırmak için potansiyel olarak çok büyük sayıların neden olduğu sayısal kararsızlıklardan kaçınmaktır. Ölçeklemeyle ilgili en önemli sorun, hem eğitim hem de test verilerinin ölçeklendirmesini uyguladığınızdan emin olmaktır. Diğer türlü pek bir anlamı olmayabilir, yani esas olan tüm verileri aynı seviyeye ölçeklendirmektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*IXkHAkHLqTM18gSYDchbRg.png" /><figcaption><a href="https://medium.com/lets-talk-ml/scaling-the-data-for-machine-learning-standardisation-and-normalisation-26ae02b1d101">Kaynak</a></figcaption></figure><p><strong>StandartScaler</strong></p><ul><li>Aykırı değerlere sahip veriler için uygun değildir.</li><li>Ortalamayı 0&#39;a ayarlar.</li></ul><p><strong>RobustScaler</strong></p><ul><li>Aykırı değerleri olan veriler için daha uygundur.</li></ul><p><strong>MinMaxScaler</strong></p><ul><li>Aykırı değerlere sahip veriler için uygun değildir.</li><li>0 ile 1 arasındaki verileri ayarlar.</li></ul><p><strong>MaxAbsScaler</strong></p><ul><li>Aykırı değerlere sahip veriler için uygun değildir.</li><li>-1 ile 1 arasındaki verileri ayarlar.</li></ul><p>Yazısı ve izni için <a href="https://hersanyagci.medium.com/">Hasan Ersan YAĞCI</a> ’ya çok teşekkür ederim.</p><p>Kaynak :</p><p><a href="https://hersanyagci.medium.com/feature-scaling-with-scikit-learn-for-data-science-8c4cbcf2daff">Feature Scaling with Scikit-Learn for Data Science</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86dbff831393" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-t%C3%BCrkiye/scikit-learn-k%C3%BCt%C3%BCphanesi-ile-data-%C3%B6l%C3%A7eklendirme-86dbff831393">Scikit-Learn Kütüphanesi ile Data Ölçeklendirme</a> was originally published in <a href="https://medium.com/machine-learning-t%C3%BCrkiye">Machine Learning Turkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tree-Based Algorithms — Decision Tree and Random Forest]]></title>
            <link>https://python.plainenglish.io/tree-based-algorithms-decision-tree-and-random-forest-cb5c5ccaf43b?source=rss-dd99dfacf7df------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5c5ccaf43b</guid>
            <category><![CDATA[entropy]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[İbrahim Halil Kaplan]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 15:49:46 GMT</pubDate>
            <atom:updated>2022-01-20T05:29:05.220Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Tree-Based Algorithms — Decision Tree and Random Forest</strong></h3><h4>Learn about the two tree-based algorithms: Decision Tree and Random Forest.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zKHsxhKd8_6681Aa" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Decision Tree</strong></h4><p>Decision Trees algorithm is a non-parametric, tree-based algorithm used for classification and regression under the title of Supervised Learning of machine learning.</p><p>What do non-parametric and parametric mean?</p><p>Parametric algorithms can generate assumptions that greatly simplify the learning process on the data they will process, and in this way, they can transform the function into a known pattern and simplify it. Of course, this can also limit what the algorithm can learn.</p><p>Non-parametric algorithms are algorithms that do not make any assumptions about the data they will process. We have a huge amount of data and if we don’t know much about it, we don’t know much about which features to use. Here, it would be more accurate to operate with non-parametric algorithms. Of course, this does not mean that the data has no parameters. It means that the algorithm operates without an assumption.</p><p>The structure of the Decision Tree algorithm is as follows.</p><p>The place where the first division begins in the tree structure is called the root, the parts that develop with the elongation of the branches, and the lower ends where the final decision is made are called leaves. The decision tree takes the training set and divides it into smaller subsets according to the features. We see a simple decision tree algorithm in the figure below.</p><p>Will you go on a picnic? If so, who will you go with? We are trying to decide on the activity to be done with their questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*C9Y5od8eN0IUtJJk38KNNA.png" /><figcaption>Decision Tree</figcaption></figure><p>As can be seen from the figure, it acts like an if-else structure. Is it sunny for a picnic? The part where the question takes place is called the root node, and the branches formed are called the leaf node (terminal node), the lowest points of the node tree. In addition, the “parent node” is the branched nodes, “children nodes” are the nodes that are not divided into branches but are connected to a branch, and the “sub-tree” is the part of a parent and children enclosed in the red circle we see in the tree. )” is called.</p><p>The <strong>inductive bias</strong> (also known as <strong>learning bias</strong>) of a learning algorithm is the set of assumptions that the learner uses to predict outputs of given inputs that it has not encountered. Inductive bias is solely a consequence of the ordering of hypotheses by its search strategy. The inductive bias of the Decision Tree is as follows:</p><p>Shorter trees are preferred over taller trees. Trees that embed high information-gain qualities close to the root are preferred to those that do not. The hypothesis space of all decision trees is a complete space of finite discrete-valued and it maintains only a single current hypothesis.</p><p>Some key terms of a decision tree are defined below.</p><ul><li>Root node: The base of the decision tree.</li><li>Splitting: The process of dividing a node into multiple sub-nodes.</li><li>Decision node: When a sub-node is further split into additional sub-nodes.</li><li>Leaf node: When a sub-node does not further split into additional sub-nodes; represents possible outcomes.</li><li>Pruning: The process of removing sub-nodes of a decision tree.</li><li>Branch: A subsection of the decision tree consisting of multiple nodes.</li><li>Parent and Child Node: A node, which is divided into sub-nodes is called a parent node of sub-nodes whereas sub-nodes are the child of a parent node.</li></ul><p>The purpose of the algorithm is to split the features as quickly and cost-effectively as possible. When starting to build the tree, it examines the features and selects the purest feature according to the distribution of the data, making this feature a root. Two different methods are also used to calculate purity:</p><ul><li>Entropy:</li></ul><p>Entropy is the amount of uncertainty present in the data. Before the split, we were pretty indecisive about which points were positive and which points were negative. But we are more confident after the breakup. If we have a pure subset then we are completely sure, on the other hand, if we have 50–50%, then we are completely uncertain about the points in that split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*URnaL-3ECepcZ3yUDsz1DA.png" /><figcaption>Entropy</figcaption></figure><p>Intuitively, we can say that the entropy should be as small as possible. As seen in the graph above, when the probability is 0.5, entropy takes its maximum value. Therefore, when calculating Entropy, it is necessary to start dividing the tree by the feature with the lowest value. So, we aim to always have 0 or always 1 so that the probability is 0 or 1, so the entropy is 0.</p><ul><li>Information Gain:</li></ul><p>Information gain, or IG, is a statistical feature that measures how well a particular trait discriminates training samples based on their target classification. Building a decision tree is about finding an attribute that returns the highest information gain and the smallest entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*lfXhZCMnV5iTyny5vST0UA.png" /><figcaption>Information Gain</figcaption></figure><p>Where “before” is the dataset before the split, K is the number of subsets generated by the split, and (j, after) is subset j after the split.</p><ul><li>Gini impurity:</li></ul><p>It is a measure of inequality developed by the Gini coefficient. Contrary to entropy, it takes a value between 0 and 0.5. The purpose is to minimize Gini impurity in the leaves as much as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*frf9QsgzOtDqTIB6lm2SuQ.png" /><figcaption>Gini and Entropy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*OjyTw7bTr2XcUEcjQk5Jdw.png" /><figcaption>Gini</figcaption></figure><p>The Gini index and entropy are criteria for calculating information gain. Decision tree algorithms use information gain to split a node. A node with more than one class is impure, while a node with only one class is pure. If a node has more than one class, then that node has disorder.</p><p><strong>Hyperparameters:</strong></p><p>criterion : {“gini”, “entropy”}, default=“gini”. The criteria we will use when calculating the purity we mentioned above.</p><p>splitter : {“best”, “random”}, default=”best”. The strategy where we choose the split at each node.</p><p>max_depth : int, default=None. The maximum depth of the decision tree. Depth; It represents the number of divisions from the root node to the leaf node. If “None” is selected, the nodes are split until the leaf nodes are completely pure.</p><p>min_samples_split : int or float, default=2. The minimum number of samples required to split the nodes. E.g.; If 10 is selected, the node is not split when there are less than 10 samples in the node.</p><p>min_samples_leaf : int or float, default=1. The minimum number of instances that must be in the leaf node. If no value is entered, it continues to split the nodes until 1 sample remains in the leaf node.</p><p>min_weight_fraction_leaf : float, default=0.0. Ratio of weighted samples in total samples.</p><p>After explaining the parameters, let’s list the advantages and disadvantages of decision trees.</p><p><strong>Pros:</strong></p><ul><li>It is easy to understand, visualize and interpret.</li><li>Data does not need to be scaled.</li><li>There is no need to normalize the data.</li><li>It can work with categorical data as well as numerical data.</li><li>Compared to other algorithms, less time is required for data preparation.</li></ul><p><strong>Cons:</strong></p><ul><li>A small change in the data can cause a big change in the structure of the tree.</li><li>Its computation may be more complex than other algorithms.</li><li>It takes more time to train.</li><li>Regression application is not sufficient compared to other algorithms.</li><li>Most importantly, the probability of over-fitting is high.</li></ul><p>The most important issue when using the decision tree algorithm should be “over-fitting”. The algorithm is suitable for memorization due to its structure. The nodes reach the leaves by dividing. If we do not interfere with the hyperparameters, the nodes are split until one sample remains. <br>Our algorithm, which sees only the training set in a large data, can memorize the data in this way. To prevent this, the technique we call “pruning” is applied. The most commonly used hyperparameters for pruning are max_depth, min_samples_split, min_samples_leaf, max_leaf_nodes, and min_impurity_decrease, which we have explained above.</p><p>As an example, we can use the widely known Titanic dataset. We will design a Decision Tree model where we can classify Survived or Not Survived according to the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*MsV4RWGgo9WtGnNUC4RO_w.png" /><figcaption>Titanic Dataset</figcaption></figure><p>After some Feature Engineering activities, we split our dataset for train test.</p><pre>X_train = titanic_df.drop(“Survived”,axis=1)<br>y_train = titanic_df[“Survived”]<br>X_train1, X_test1, y_train1, y_test1 = model_selection.train_test_split(X_train, y_train, test_size=0.2,random_state=42)<br>model_dt = DecisionTreeClassifier()<br>model_dt.fit(X_train1,y_train1)<br>parameters = {“criterion”:[‘gini’,’entropy’],<br>              “max_depth”: range(3,20),<br>              “min_samples_leaf”:range(3,20)<br>             }<br>grid_dt = GridSearchCV(estimator=model_dt,param_grid= parameters,<br>                       cv=3,return_train_score=True,n_jobs= -1<br>                       )</pre><pre>grid_dt.fit(X_train1, y_train1)<br>grid_dt.best_params_<br>grid_dt.best_score_<br>0.8202318902244442</pre><p>Our tree and scores are given below with the values ​​we obtained from the GridSearchCV.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4PzuDVN0OCuWlVJRGUzGA.png" /><figcaption>Pruned Tree (max_depth=3)</figcaption></figure><pre>predsdt =grid_dt.best_estimator_.predict(X_test1)<br>print(classification_report(y_test1,predsdt))</pre><pre>               precision    recall  f1-score   support</pre><pre>           0       0.80      0.90      0.84       105<br>           1       0.82      0.68      0.74        74</pre><pre>accuracy                               0.80       179<br>macro avg          0.81      0.79      0.79       179 <br>weighted avg       0.81      0.80      0.80       179</pre><p>Decision tree is advantageous in terms of short data preparation time, easy understanding, interpretation, and visualization, on the other hand, it should be considered when using because it is computationally expensive and prone to overfit.</p><h4><strong>Random Forest</strong></h4><p>Random forest is a type of ensemble learning method in which a group of weak models combines to form a strong model. The Random Forest starts with a standard machine learning technique called a “decision tree”, which in ensemble terms corresponds to our weak model. In a decision tree, an entry is entered at the top, and data is aggregated into smaller and smaller clusters as you move down the tree. In Random Forest, we grow multiple trees instead of a single tree. To classify a new object based on attributes, each tree gives a classification score. Random Forest chooses the classification with the most votes (over all trees in the forest) and averages the outputs of different trees in the regression case.</p><p>Random Forest, in the simplest terms, can be defined as the reproduction of the decision tree algorithm with random trees. Let’s continue with the subject of how is reproduction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*Zj-khQp2jab3nSX-F-Paeg.png" /><figcaption><a href="https://www.tibco.com/sites/tibco/files/media_entity/2021-05/random-forest-diagram.svg">https://www.tibco.com/sites/tibco/files/media_entity/2021-05/random-forest-diagram.svg</a></figcaption></figure><p>What does the ensemble method mean?</p><p>We all use the Decision Tree Technique in everyday life to make decisions. Ensemble methods combine different decision trees to provide better prediction results, rather than using a single decision tree. The basic principle behind the ensemble model is that a group of weaker models come together to create a model that works better.</p><p>There are two techniques given below that are used to implement the ensemble (community) method decision tree.</p><p>Bagging:</p><p>Bagging algorithms are used when our goal is to reduce the variance of a decision tree. The concept here is to generate several data subsets from a randomly selected training sample with replacement. Now each subset of data collection is used to prepare the decision trees so that we get a collection of various models. The average of all assumptions from many weak trees, stronger than a single decision tree, is used.</p><p>Bootstrapping is a statistical procedure that resamples a single dataset to generate many simulated examples. This process allows you to calculate standard errors, construct confidence intervals, and perform hypothesis testing for many sample statistics types. Rows are selected randomly from the original dataset and stored in the dataset called bootstrap. Generally, 1/3 of the original dataset is not represented in the bootstrap dataset. The data that is not represented in the Bootstrap dataset is called the “Out-of-Bag Dataset”.</p><p>Boosting:</p><p>It is another ensemble procedure for making a collection of estimators. In other words, we insert consecutive trees, usually random samples, and the goal at each step is to resolve the net error from the previous trees. If a particular input is misclassified by the previous hypothesis, its weight increases so that at the end of the upcoming hypothesis it is more likely to classify it correctly by consolidating the entire set, turning poor learners into better performing models.</p><p>The inductive bias of a decision tree is that the answer can be arrived at by asking a series of simple binary questions. However, allowing a large number of questions to be asked allows them to fit any arbitrarily complex edge boundary. Arbitrarily complex functions can lead to over-fitting, but that can be combated by building ensembles of trees called decision forests.</p><p>By using rotation to ensure diversity and disrupt the blockiness bias of the standard tree we arrive at a classifier with an incredibly weak inductive bias. What this means in practice is that decision forests perform well when data is plentiful and relationships are complex. However, limiting can also be done using the max_features hyperparameter.</p><p><strong>Pros:</strong></p><ul><li>Random Forest is unbiased as we train multiple decision trees and each tree is trained on a subset of the same training data.</li><li>If we include new data points in the dataset, it is very stable as the new data point does not affect as much as it affects one tree and it is quite difficult to affect all trees.</li><li>It also works well when we have both categorical and numerical properties in the problem statement.</li><li>It performs very well to NaN values ​​in the dataset.</li></ul><p><strong>Cons:</strong></p><ul><li>Complexity is the biggest drawback of this algorithm. More computational resources are required and also result in the aggregation of multiple decision trees.</li><li>Due to their complexity, the training time is longer than other algorithms.</li></ul><p>Again, the results of our grid search model based on the random forest model made with the titanic dataset are given below.</p><pre>parameters = {&quot;criterion&quot;:[&#39;gini&#39;,&#39;entropy&#39;],<br>              &quot;max_depth&quot;: range(1,20),         <br>              &quot;min_samples_leaf&quot;:range(1,20)<br>             }</pre><pre>grid_rf = GridSearchCV(estimator=model_rf, param_grid= parameters,  <br>                       cv=3,return_train_score=True,n_jobs= -1<br>                      )<br>grid_rf.fit(X_train1,y_train1)<br>grid_rf.best_score_<br>0.8174189507026438</pre><pre>predsrf = grid_rf.best_estimator_.predict(X_test1)<br>print(classification_report(y_test1,predsrf))</pre><pre>                precision    recall  f1-score   support</pre><pre>           0       0.82      0.89      0.85       105 <br>           1       0.82      0.73      0.77        74</pre><pre>accuracy                               0.82       179 <br>macro avg          0.82      0.81      0.81       179<br>weighted avg       0.82      0.82      0.82       179</pre><p>You can find the code block about Decision Tree and Random forest <a href="https://github.com/ibrakaplan/Decision-Tree-and-Random-Forest">here</a>. Thank you for your patience.</p><p><strong>References:</strong></p><ul><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">DecisionTreeClassifier</a></li><li><a href="https://abdullahatcili.medium.com/karar-agaclari-algoritmasi-b823c23997d0">Karar Agaclari Algoritmasi</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our</em><strong><em> </em></strong><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5c5ccaf43b" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/tree-based-algorithms-decision-tree-and-random-forest-cb5c5ccaf43b">Tree-Based Algorithms — Decision Tree and Random Forest</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Destek Vektor Makineleri (Support Vector Machine-SVM)]]></title>
            <link>https://medium.com/machine-learning-t%C3%BCrkiye/destek-vektor-makineleri-support-vector-machine-svm-ddaa0d003aa3?source=rss-dd99dfacf7df------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddaa0d003aa3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[destek-vektör-makineleri]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İbrahim Halil Kaplan]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 15:24:33 GMT</pubDate>
            <atom:updated>2022-01-15T10:12:47.631Z</atom:updated>
            <content:encoded><![CDATA[<p>SVM, denetimli bir makine öğrenme algoritması (supervised learning) çeşidi olup hem sınıflandırma hem de regresyon (SVR) amacıyla kullanılabilen oldukça basit ve etkili bir algoritmadır.</p><p>Sınıflandırma için bir düzlemde bulunan iki grup arasına, bu iki grubun üyelerine en uzak yerden olmak üzere karar sınırı çizilerek grupları ayırma mantığı üzerine kurgulanmıştır ve dağılım hakkında herhangi bir bilgi veya varsayım olmayan, nonparametrik sınıflayıcılardır. Parametrik ve nonparametrik verilere uygulanabilmektedir. Parametrik veriler belirli bir dağılım çeşidine sahip olduğu ve verilerin arasında böyle bir ilişkinin olduğu varsayılan verilerdir. Nonparametrik veriler ise herhangi bir dağılıma, ilişkiye dayalı olmayan verilerdir.</p><p>Neden destek vektör makineleri ismi kullanılmaktadır?</p><p>Karar sınırı oluşturulurken sınırın kenarlarında iki gruba ait veri noktaları seçilir. Bu veri noktaları destek vektörü vazifesi görerek kenar hatlarının belirlenmesini sağlarlar. Destek vektör makineleri ismi buradan gelir.</p><p>SVM’de karar sınırı, farklı sınıflardan en yakın veri noktalarına olan mesafeyi maksimize edilerek oluşturulur. Yani veri noktaları arasındaki mesafe, SVM’nin seçtiği karar sınırını etkiler. Başka bir deyişle, bir SVM’yi ölçeklenen ve ölçeklenmeyen veriler üzerinden eğitmek, farklı modellerin üretilmesine yol açar. Bu yüzden veri çeşidine göre ‘scaler’ kullanmak gerekebilir.</p><p>Sınıflandırma problemlerinde genellikle ‘Binary Cross-Entropy Loss’ denilen çapraz entropi kuralı kullanılır. Yani hangi sınıfa ait olduğu hesaplanmaya çalışılan verinin gerçek ve tahmin edilen olasılık dağılımındaki ortalama farka çapraz entropi denilir. Bu fark yani hata ne kadar az olursa tahmin o kadar başarılı olur. Bu hata fonksiyonu tahminlerini {0,1} aralığında yapmaktadır. İşte burada SVM çapraz entropi’ye alternatif ‘hinge loss’ denilen farklı bir hata fonksiyonu ile daha doğru tahminler yapabilmektedir. ‘Hinge loss’ hata fonksiyonu tahminlerini {-1,+1} arasında yapmaktadır. Bu şekilde gerçek ve tahmin edilen sınıf değerleri arasında işarette bir fark olduğunda daha fazla hata atayarak verileri doğru işarete sahip olmasını sağlamaya çalışır. Bu şekilde oluşturulan model çapraz entropi’ye göre daha iyi bir performans gösterebilmektedir.</p><p>SVM veri setinin lineer olup olmamasına göre ikiye ayrılmaktadır.</p><p>Doğrusal (Lineer) SVM:</p><p>Doğrusal SVM, doğrusal olarak ayrılabilen veri kümeleri için kullanılır. Aşağıdaki görselden de anlaşılacağı üzere düz bir çizgi iki grubu etkili bir şekilde ayırıp sınıflandırma yapabiliyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1f5INNYcg5sgIB5ghfYiew.png" /><figcaption>Şekil-1</figcaption></figure><p>Görüldüğü üzere bu iki grubu ayıran karar doğrusunun mümkün olan en iyi şekilde oluşturulması çok önemlidir. Genellikle ‘hinge loss’ kayıp fonksiyonu kullanıldığından sınıflar (-1,+1) şeklinde etiketlendirilirler.</p><p>Peki burada düşünmemiz gereken önemli bir husus var:</p><p>SVM’nin başka bir sınıflandırma çeşidi olan Lojistik Regresyon’dan ne farkı var?</p><p>En önemli nokta burası. Lojistik Regresyon iki grup arasındaki ayrım düzlemini belirlerken iki gruba ait tüm veri noktaları hesaba dahil olur. <br>SVM de ise sadece destek vektörlerin konumu hesaplanır. Bu yüzden SVM’deki çekilen hiperdüzlem lojistik regresyona göre bariz farklılıklar gösterebilir. Özellikle de veri kümesinde aykırı değerler olması durumunda SVM aykırı değerlerden etkilenmediği için Lojistik Regresyona göre daha başarılı bir performans sergileyebilir.</p><p>Doğrusal Olmayan (Nonlinear) SVM:</p><p>Doğrusal Olmayan SVM ise düz bir çizgi ile ayrılamayan veri kümeleri için kullanılmaktadır. Doğrusal bir hiperdüzlem kullanılamadığı için “kernel trick” denilen yapılar kullanılır. Bu sayede yüksek sınıflandırma oranı elde edilir. Kernel trick çeşitleri ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’ ve ‘precomputed’ olmak üzere beş çeşittir ancak en çok kullanılanlar ‘poly’ ile ‘rbf’ tir.</p><p>- Poly : Polinomdan gelmektedir ve eğitim datasının polinomları üzerindeki benzerliğini temsil ederek, doğrusal olmayan modellerin öğrenilmesini sağlar.</p><p>- RBF (Radial Basis Function) : RBF, Gauss dağılımına benzerliği nedeniyle en yaygın kullanılan kernel’lerden biridir. Veri kümesindeki iki noktanın konumlarına göre birbirlerine benzerliklerini hesaplar.</p><p>Yine daha iyi anlamak için aşağıdaki görseli inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*qjghI6jgAxRvQaTQtbRouQ.png" /><figcaption>Şekil-2</figcaption></figure><p>Görselde RBF kernel kullanılmış bir sınıflandırma görüyoruz. Kırmızı işaretli veri noktaları iki sınıfa ait destek vektörleridir. Bu şekilde doğrusal olmayan veri kümesini yüksek doğruluk oranıyla sınıflandırmış oluyoruz.</p><p>Burada bazı önemli hiperparametrelerden bahsetmek istiyorum.</p><p>‘C’ Hiperparametresi :</p><p>Şekil-1’i incelersek orada Margin genişliği olarak ifade edilen alanın her iki gruba ait destek vektörlerinin arasında kalan alan olduğunu görebiliriz. Bu alan ne kadar dar olursa o kadar keskin bir sınıflandırma yapmamız mümkün olur. Buna ‘hard margin’ adı verilir. Ancak bir yandan da veri setinin dağılımına göre ya da doğrusal olup olmamasına göre bu dar margin sınıflandırma hatası yapmamıza da neden olabilir. Burada bu margin genişliğini artırarak ‘soft margin’ adı verilen daha geniş bir margin uygulayabiliriz. Bu şekilde bazı eğitim verilerimiz destek vektörü olmamasına rağmen margin içerisinde kalabilir ama bu sınıflandırma esnasında daha doğru sonuçlar verecektir. İşte bu margin genişliğini C parametresi ile kontrol edebiliriz. C ne kadar büyük olursa margin o kadar dar, C ne kadar küçük olursa margin o kadar büyük olacaktır.</p><p>Doğrusal olmayan veri yapılarında minimum hata ile sınıflandırma yaparken ‘C’ parametresinin, ‘soft margin’ olacak kadar küçük, overfit olmayacak kadar da büyük olmasına dikkat etmeli, optimum dengeyi sağlamalıyız. <br>’C’ parametresinin etkisini görmek için aşağıdaki görseli inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSCqzn7Dew_K14Ph8pKqRw.png" /><figcaption>Şekil-3</figcaption></figure><p>‘gamma’ Hiperparametresi:</p><p>‘gamma’ parametresine daha çok doğrusal olmayan veri yapılarını modellendirmede ihtiyacımız olacaktır. Farklı kernel çeşitleriyle işlem yaparken sınıflandırmada kullanılan normal dağılımın genişliğini ‘gamma’ parametresi ile kontrol edebiliriz. Aşağıdaki görseli inceleyecek olursak: ‘gamma = 1’ ile ‘gamma = 10’ arasında farkı görürüz. ‘gamma’ ne kadar küçükse dağılım o kadar geniş, ne kadar büyükse dağılım o kadar dar olur. Yani ‘gamma’ değeri maksimum sınıflandırma kalitesi olacak kadar büyük, overfit olmayacak kadar da küçük olmalıdır. Overfit durumunda düşürmeli, underfit durumunda artırmalıyız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16WOcfcds93vEdvTk27aAA.png" /><figcaption>Şekil-4</figcaption></figure><p>SVM hiperparametreleri elbette bunlarla sınırlı değil ancak modelin kalitesine en fazla etkiyi bu iki parametrenin yaptığını söyleyebiliriz.</p><p>SVM, yazı metinleri gibi doğrusal olmayan veri kümelerinde başarılı performanslar sergileyebilmektedir.</p><p>Genel hatlarıyla SVM hakkında aktaracaklarım bu kadar. Umarım faydalı olmuştur. Bu yazıda kullanılan kod bloğuna <a href="https://github.com/ibrakaplan/SVM-Example/blob/main/SVM%20Classification.ipynb">buradan</a> ulaşabilirsiniz. Teşekkürler.</p><p>Kaynak:</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC">https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddaa0d003aa3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-t%C3%BCrkiye/destek-vektor-makineleri-support-vector-machine-svm-ddaa0d003aa3">Destek Vektor Makineleri (Support Vector Machine-SVM)</a> was originally published in <a href="https://medium.com/machine-learning-t%C3%BCrkiye">Machine Learning Turkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Localized Regression (KNN with Local Regression)]]></title>
            <link>https://medium.com/machine-learning-t%C3%BCrkiye/localized-regression-knn-with-local-regression-7b4d302adb85?source=rss-dd99dfacf7df------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b4d302adb85</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[localized]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İbrahim Halil Kaplan]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 10:10:49 GMT</pubDate>
            <atom:updated>2022-01-07T08:44:35.394Z</atom:updated>
            <content:encoded><![CDATA[<p>Can we blend the KNN regression algorithm with other algorithms? Can we achieve more efficient results this way?</p><p>First of all, let me briefly explain how KNN regression and linear regression work.</p><p>The K nearest neighbor is a simple supervised machine learning algorithm that memorizes the available training data and estimates the numerical target based on a similarity measure (e.g. distance functions). It arrives at a numerical value by averaging the nearest neighbors. KNN regression uses the same distance functions as KNN classification. Although Euclidean distance is usually used, a wide variety of distance measurement metrics can be used. You can see them in the image below. You can also find more detailed information about the KNN classification algorithm and distance measurements <a href="https://medium.com/machine-learning-t%C3%BCrkiye/knn-k-en-yak%C4%B1n-kom%C5%9Fu-7a037f056116">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qq6pytAw-0B8I-rXHWsdVg.png" /><figcaption>Distance Measurements</figcaption></figure><p>Linear Regression is a machine learning algorithm based on supervised learning and models a target predictive value based on independent variables. It is mostly used to find the relationship between variables and prediction. In other words, they make an estimation of a new data point, whichever target values ​​they actually got according to the characteristics of the given training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xEyDeM4MzQ3VGqLEDmXeBw.png" /></figure><p>After briefly mentioning algorithms, let’s come to what we want to do. <strong>What can we do if the KNN algorithm saves the dataset and determines the commands of the data point we want to predict, and if we want to follow a different path instead of averaging these neighbors?</strong></p><p>Let’s try it.</p><p>We created a dataset with 100 samples in the image for KNN regression. Then we separated it as training and test data and fit it with KNN regressor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*fm9ANd76XLU4FC-O6TKsYA.png" /></figure><p>Then we started linear model here, located the neighbors and x, y data were created from close neighbors.</p><pre>nearestneighbor=model.kneighbors(np.array(X_test[0]).reshape(-1,2))[1] # We located the neighbors.</pre><pre>neighbors_x = [] # x and y data were created from close neighbors here.<br>neighbors_y = []<br>for i in nearestneighbor:<br>    neighbors_x.append(X_train[i])<br>    neighbors_y.append(y_train[i])</pre><p>Neighbors_x and neighbors_y are converted to np.array to be able to reshape. Then linear model fitted.</p><pre>neighbors_x = np.array(neighbors_x) # The list has been converted to np.array to be able to reshape.</pre><pre>neighbors_y = np.array(neighbors_y)</pre><pre>linermodel = LinearRegression()</pre><pre>linermodel.fit(neighbors_x.reshape(-1,2),neighbors_y.reshape(-1,1))</pre><p>The prediction is impressive.</p><pre>linermodel.predict(np.array(X_test[0]).reshape(-1,2))# linear model predicted based on point X_test[0]<br>array([[18.16595607]])</pre><pre>y_test[0] # real data point.<br>18.16595607153592</pre><p>What would be the result if we made a prediction on the knn regressor model?</p><pre>y_predknn = model.predict(np.array(X_test[0]).reshape(-1,2))</pre><pre>y_predknn # KNN models prediction<br>array([13.12238492])</pre><p>When we examine the results, we can say that the method we applied is useful.</p><p>If we make this method we follow into a simple class, we can do it as follows.</p><pre>class LocalizedRegressor(KNeighborsRegressor):<br> def predict(self,X):<br> y_preds = []<br> dist,inds=self.kneighbors(X)<br> features = self._fit_X[inds]<br> labels = self._y[inds] <br> for i in range(X.shape[0]):<br> X_lin = features[i]<br> y_lin = labels[i]<br> model_for_this_point = LinearRegression()<br> model_for_this_point.fit(X_lin,y_lin)<br> prediction = model_for_this_point.predict(X[i:i+1])<br> y_preds.append(prediction[0])<br> y_preds = np.array(y_preds)<br> return y_preds</pre><pre>m = LocalizedRegressor(n_neighbors=25)</pre><pre>m.fit(X_train,y_train)<br>LocalizedRegressor(n_neighbors=25)</pre><pre>m.predict(X_test[0:1])<br>array([18.16595607])</pre><p>Let’s see how Localized regression performs by mixing the dataset a bit.</p><pre>X, _ = make_regression(n_samples=100,n_features=2,n_informative=2)<br>y = 2. * X[:, 0] ** 2–0.7 * X[:, 1] ** 3–0.54</pre><pre>Knn_model.score(X_test,y_test)<br>0.6495531202875833</pre><pre>LocalReg.score(X_test,y_test)<br>0.9428817200363483</pre><p>Looks like it’s working :)</p><p>You can find the whole code blog <a href="https://github.com/ibrakaplan/Local-Regression-KNN-with-Local-Regression-/blob/main/Local%20Regression%20(KNN%20with%20Local%20Regression).ipynb">here</a>.</p><p>Thank you for reading , I hope it was useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b4d302adb85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-t%C3%BCrkiye/localized-regression-knn-with-local-regression-7b4d302adb85">Localized Regression (KNN with Local Regression)</a> was originally published in <a href="https://medium.com/machine-learning-t%C3%BCrkiye">Machine Learning Turkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cost Function]]></title>
            <link>https://ibrahimhalilkaplan1.medium.com/cost-function-18347656c984?source=rss-dd99dfacf7df------2</link>
            <guid isPermaLink="false">https://medium.com/p/18347656c984</guid>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İbrahim Halil Kaplan]]></dc:creator>
            <pubDate>Mon, 03 May 2021 21:41:28 GMT</pubDate>
            <atom:updated>2021-05-03T21:41:28.104Z</atom:updated>
            <content:encoded><![CDATA[<p>“Cost function” yani kayıp fonksiyon lineer regresyon modeli ile yapılan uygulamaların en önemli noktasıdır. Çözüme ulaşmak için kayıp fonksiyonun hesaplanması gerekir. Yalnız kayıp fonksiyona geçmeden dilerseniz lineer regresyon modelinden bir örnek ile bahsedelim.</p><p>Lineer regresyon modelini bazı parametrelerin bir evin fiyatını belirlemeye etkisi üzerinden anlatabiliriz. Evin konumu, metrekaresi, oda sayısı, merkeze uzaklığı, ulaşım araçlarına uzaklığı, kaçıncı katta olduğu, kaç yıllık bir bina olduğu gibi değişkenler evin fiyatını belirlemektedir. Biz bu değişkenlerin evin fiyatını ne kadar etkilediğini doğru hesaplarsak başka herhangi bir evin fiyatını da o derecede doğru tahmin edebiliriz. Bunu aşağıdaki denklemle ifade etmeye çalışalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*DcBuT1YFJIaEOoVPv6bJfA.png" /></figure><p><em>y </em>: Evin fiyatın,</p><p><em>β</em>: Belirleyeceğimiz katsayılar,</p><p><em>x </em>: Evin konumu, metrekaresi gibi değişkenler.</p><p>Bu denkleme göre yaptığımız tahminlerle aşağıdaki grafikteki gibi noktalar elde ettiğimizi farz ve kabul edersek, ortalarından geçen doğrunun da aslında ulaşmak istediğimiz doğru olduğunu anlayabiliriz. Yani bizim hesaplamalarımızdaki küçük hatalardan dolayı tam olarak o doğruyu oluşturamadık ama en yakın doğrunun o doğru olduğu net şekilde anlaşılmaktadır. Seçtiğimiz parametreye göre evin fiyatını bu doğru üzerinden görebileceğimiz anlamına gelmektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*OFgzHWyJ3vmSkFJ4NpJTJQ.png" /></figure><p>İşte kayıp fonksiyon tam olarak burada önemli olmaktadır. Kayıp fonksiyon bizim tahmin ettiğimiz değer ile doğru üzerindeki gerçek değer arasındaki farktır. Bu fark ne kadar az olursa bizim tahminlerimiz o kadar gerçeğe yakın olacaktır. Aşağıdaki grafikte ne demek istediğimiz daha iyi anlaşılacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*98KjBJ3FFsWz5cSdAf8W1g.png" /></figure><p>Kayıp fonksiyonu hesaplamak için kullanacağımız denklem aşağıda belirtilmiştir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*SRL-gew7_rvqFbobl8wfJA.png" /></figure><p>Burada kullanılan parametrelerin açıklaması şöyledir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*WFOF8ASmp517zgjhAYzDTQ.png" /></figure><p>Biz yapacağımız örnek hesaplamalarda kaç adet tahmin yaparsak ve bu tahminlerimizdeki değerler ne ise bu formül yardımıyla kolayca hesaplama yapıp sonuca ulaşabiliriz.</p><p>İyi günler.:)</p><p>Kaynakça:</p><p><a href="https://miro.medium.com/max/378/1*VanG05Ab6yknqJ2bRGFzrQ.png">https://miro.medium.com/max/378/1*VanG05Ab6yknqJ2bRGFzrQ.png</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18347656c984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Descent]]></title>
            <link>https://ibrahimhalilkaplan1.medium.com/gradient-descent-c2e4560c9294?source=rss-dd99dfacf7df------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e4560c9294</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İbrahim Halil Kaplan]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 02:38:30 GMT</pubDate>
            <atom:updated>2021-04-24T02:38:30.686Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning uygulamalarında, bir problemin çözümü esnasında en iyi sonuca ulaşmak ya da diğer bir deyişle en az hata ile sonuca ulaşmak için optimizasyon teknikleri kullanılır. Gradient Descent (Gradyan Azalma) bu tekniklerden birisidir.</p><p>Gradyen Azalma tekniğinde çözümümüz her iterasyonda adım adım global minimuma doğru ilerler. Doğru çalışan bir kod bloku ile son adımda eğim 0’a eşit olacaktır. Tam olarak bu nokta global minimum noktasıdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nQkl8iMuDlDzQF7-9ltqCQ.png" /></figure><p>Yukarıdaki şekilde de görüldüğü üzere parabolik grafik üzerinde rasgele alacağımız bir noktadaki eğim değeri <strong><em>F(x)= ax</em> </strong>olsun. Parabol denklemi ise <br><strong><em>p = (y-ax)² </em></strong>olacaktır. Biz global minimuma ulaşabilmek için parabol denkleminin türevini kullanacağız:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*xFX8-OjC8riiKzk3bpZqSQ.png" /></figure><p>Her iterasyonda global minimuma yaklaşmak için atacağımız adımlarda en önemi nokta learning rate (öğrenme katsayısı) dir.</p><p>Learning rate çok dengeli bir sayı olmalıdır. Aksi takdirde çok küçük adımlar global minimuma ulaşmadan iterasyonlar tamamlanır ve çok zaman kaybetmeye sebep olur. Çok büyük adımlar hedefe yaklaştırmak yerine uzaklaştırabilir. Bu yüzden kullandığımız fonksiyon ve modele göre optimum değeri seçmemiz gerekmektedir.</p><p>Bu aşamadan sonra a değerimiz her iterasyonda yenilenir ve en son değeri alır. Bu şekilde global minimuma gelmiş oluruz.</p><p>Konuyu daha iyi anlamaya yardımcı olmak adına Python’da yazılmış kod bloku da aşağıda sunulmuştur.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f2d1967e90790be4d4b759b021d014/href">https://medium.com/media/e4f2d1967e90790be4d4b759b021d014/href</a></iframe><p>Esenlikler Dilerim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e4560c9294" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>