<?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 Muhammet Bektaş on Medium]]></title>
        <description><![CDATA[Stories by Muhammet Bektaş on Medium]]></description>
        <link>https://medium.com/@mbektas?source=rss-be6295ca36c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*GO0dLjM5YwUM7nVmZwQ82w.jpeg</url>
            <title>Stories by Muhammet Bektaş on Medium</title>
            <link>https://medium.com/@mbektas?source=rss-be6295ca36c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:45:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mbektas/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[A comprehensive Guide to Scikit-learn Part 2: The Datasets Module]]></title>
            <link>https://medium.com/bootrain-blog/a-comprehensive-guide-to-scikit-learn-part-2-the-datasets-module-eb6e8c16fd73?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6e8c16fd73</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 07:31:01 GMT</pubDate>
            <atom:updated>2020-07-03T07:31:01.190Z</atom:updated>
            <content:encoded><![CDATA[<p>Scikit-learn is the most popular machine learning library and this is no without a reason. <a href="https://medium.com/bootrain-blog/a-comprehensive-guide-to-scikit-learn-part-1-overview-of-the-package-b766f1da50da?source=friends_link&amp;sk=7713347f0f2352feef49bd4234c7b30d">In the previous article</a>, we provided a wholistic view of the scikit-learn architecture and highlighted the factors that make scikit-learn the de-facto standard in the machine learning community. In this article, we’ll talk about the “datasets” module of the scikit-learn. In the next articles, we’ll go over the other modules one-by-one to make you grasp the scikit-learn package well.</p><p>Scikit-learn provides various cleaned and built-in datasets so that you can jump start playing with machine learning models right away. These datasets are among the most well-known datasets which you can easily load them with a few lines of codes. The modules that contain these datasets is called “<strong>datasets</strong>”. Additionally, you can use this module to create your own datasets by making use of the random sample generators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lyfg_zn2UrSAKrlB.png" /><figcaption>Source: <a href="https://www.codingforentrepreneurs.com/blog/dataset-resources-for-machine-learning/">codingforentrepreneurs.com/blog/dataset-resources-for-machine-learning/</a></figcaption></figure><p>To start with, you need to import the datasets module from the scikit-learn as follows:</p><pre>import sklearn.datasets</pre><p>However as we’ll see shortly, instead of importing all the module, we can import only the functionalities we use in our code. We’ll give our examples in this article by following this best practice.</p><p>Throughout this article, we will learn how we can load and examine the datasets in this module. Specifically, we’ll cover the followings:</p><ol><li>Built-in datasets</li><li>Fetching external datasets</li><li>Generating new random datasets</li><li>and the others :)</li></ol><p>We begin with the built-in datasets.</p><h4><strong>1. Built-in Datasets</strong></h4><p>Some datasets are maintained and hosted by the scikit-learn community and datasets module enables us to load these datasets with a single line of code. These datasets are usually small size datasets that are useful in the sense that they provide a ready playground to experiment with the different machine learning algorithms implemented in the scikit-learn. As an example, we show you how we can load <strong>the boston house prices dataset</strong>, a classical dataset that is suitable for regression analysis.</p><p>Loading a built-in dataset from the datasets module is quite easy. We just need to import the function from the datasets module that loads the data we want. For example, we can load the boston house prices dataset by calling the load_boston() function as follows:</p><pre>from sklearn.datasets import load_boston</pre><pre>boston_dataset = load_boston()</pre><p>Now the dataset is loaded to a variable called boston_dataset. This variable is a dictionary type object that includes keys and values that are returned by load_boston() function. We can check this as follows:</p><pre>boston_dataset.keys()<br>dict_keys([&#39;data&#39;, &#39;target&#39;, &#39;feature_names&#39;, &#39;DESCR&#39;,&#39;filename&#39;])</pre><p>This dictionary contains a key called <strong>DESCR</strong> that gives a description of the dataset as well as some other useful information as values of the contain <strong>feature_names</strong> and <strong>target_names</strong> keys:</p><pre>print(boston_dataset[&#39;DESCR&#39;][20:255] + &quot;\n...&quot;)<br>Boston house prices dataset<br>---------------------------<br><br>**Data Set Characteristics:**  <br><br>    :Number of Instances: 506 <br><br>    :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.<br>...</pre><p>The value of the key target_names is an array of strings, containing the prices of houses that we want to predict.</p><p>The value of feature_names is a list of strings, giving the description of each feature:</p><pre>boston_dataset[&#39;feature_names&#39;]<br>array([&#39;CRIM&#39;, &#39;ZN&#39;, &#39;INDUS&#39;, &#39;CHAS&#39;, &#39;NOX&#39;, &#39;RM&#39;, &#39;AGE&#39;,    &#39;DIS&#39;,<br>&#39;RAD&#39;, &#39;TAX&#39;, &#39;PTRATIO&#39;, &#39;B&#39;, &#39;LSTAT&#39;], dtype=&#39;&lt;U7&#39;)</pre><p>Boston house prices dataset is just an example of the datasets available in the datasets module. In addition, there are many other popular datasets are available through this module that every machine learning enthusiast can work on to improve their skillset. Among these datasets are iris dataset, diabets dataset, breast cancer wisconsin dataset, wine dataset etc.</p><h4><strong>2. Fetching External Datasets</strong></h4><p>There are many useful datasets that are publicly available in the internet and most of them are maintained and hosted by people or institutions that are not related to scikit-learn. Scikit-learn provides versatile methods to load these datasets from the internet. As an example, we show you how to load the <strong>“Labeled Faces in the Wild (LFW) people”</strong> dataset. Its size is more than 200 MB and when doing computer vision projects this dataset can be used for face detection or recognition tasks. We can load the dataset as follows:</p><pre>from sklearn.datasets import fetch_lfw_people<br>lfw_people = fetch_lfw_people(min_faces_per_person=70,resize=0.4)</pre><p>As you can see, datasets module provides a method called <strong>fetch_lfw_people()</strong> and we can call this method to load the dataset. As usual, the method returns a dictionary with several keys. For example, we can look at the target values (the name of the people) like this:</p><pre>for name in lfw_people.target_names:<br>    print(name)<br>Ariel Sharon<br>Colin Powell<br>Donald Rumsfeld<br>George W Bush<br>Gerhard Schroeder<br>Hugo Chavez<br>Tony Blair</pre><p>We can also take a look at the images by using matplotlib’s <strong>imshow()</strong> method as follows:</p><pre>plt.imshow(lfw_people.images[1],cmap=&#39;gray&#39;)</pre><p>We have only dwelled on LFW people dataset. Another well known datasets can be listed such as Olivetti faces data-set, LFW pairs dataset, kddcup99 dataset and California housing dataset that can also be loaded by fetchers.</p><h4><strong>3. Generating Random Datasets</strong></h4><p>Scikit-learn contains various random sample generators to create artificial datasets of controlled size and variety. There are lots of generators for classification, clustering, biclustering, regression, manifold learning and decomposition. We will give an example by creating a data generator for a classification task. For other types of generators, you can look at <a href="https://scikit-learn.org/stable/datasets/index.html#generated-datasets">the documentation</a>.</p><p>Below, we import the make_classification() method from the datasets module. This method will generate us random data points given some parameters. We can play with the parameters however we want. Among the available parameters are number of sample, features, classes etc.</p><pre>from sklearn.datasets import make_classification</pre><pre>plt.subplot(121)<br>plt.title(&quot;Two features, two classes&quot;)<br>X, Y = make_classification(n_features=2, n_redundant=0,<br>n_informative=2, n_clusters_per_class=2)<br>plt.scatter(X[:, 0], X[:, 1], c=Y,edgecolor=&#39;k&#39;)</pre><pre>plt.subplot(122)<br>plt.title(&quot;Two features, three classes&quot;)<br>X, Y = make_classification(n_features=2, n_redundant=0,<br>n_informative=2, n_clusters_per_class=1,n_classes=3)<br>plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolor=&#39;k&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*nghe84zTt0ksxkgM0Lk6XQ.png" /></figure><h4><strong>4. Other Datasets</strong></h4><p>There are several other types of datasets that are available through the datasets module. For example, some jpeg images are available that are added to the repository by the scikit-learn authors. Those images may be of practical use when testing some algorithms when prototyping or experimenting. To load these images, we can use <strong>load_sample_images()</strong> function as follows:</p><pre>from sklearn.datasets import load_sample_image<br>plt.imshow(load_sample_image(&#39;flower.jpg&#39;))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*WJfOAszDBA1lYliCPBLapg.png" /></figure><p>Second, <a href="https://openml.org/">openml.org</a> repository allows everyone to upload open source datasets for machine learning studies. Those datasets can be fetched as shown below:</p><pre>from sklearn.datasets import fetch_openml<br>minist = fetch_openml(name=&#39;minist_784&#39;, version=4)</pre><p>Third, there are datasets in svmlight/libsvm format that is particularly favorable for sparse datasets. If we have those datasets already downloaded into our local machines, then we can load them into our code as follows:</p><pre>from sklearn.datasets import load_svmlight_file<br>X_train, y_train = load_svmlight_file(&quot;/path/to/train_dataset.txt&quot;)</pre><h4><strong>Conclusion</strong></h4><p>We’re done with the datasets submodule of the scikit-learn. In the next article, we’ll explore the “<strong>preprocessing</strong>” module of the scikit-learn. So, stay tuned and please follow us in other platforms as well.</p><p>LinkedIn: <a href="https://www.linkedin.com/company/bootrain">https://www.linkedin.com/company/bootrain</a></p><p>Twitter: <a href="https://twitter.com/BootrainSchool">https://twitter.com/BootrainSchool</a></p><p>Web: <a href="https://www.bootrain.com/">www.bootrain.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6e8c16fd73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bootrain-blog/a-comprehensive-guide-to-scikit-learn-part-2-the-datasets-module-eb6e8c16fd73">A comprehensive Guide to Scikit-learn Part 2: The Datasets Module</a> was originally published in <a href="https://medium.com/bootrain-blog">Bootrain Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow Ortamında Nesne Tanıma Uygulaması (Defect Type Detection using Faster R-CNN)]]></title>
            <link>https://medium.com/@mbektas/tensorflow-ortam%C4%B1nda-nesne-tan%C4%B1ma-uygulamas%C4%B1-defect-type-detection-using-faster-r-cnn-1be1e1f59c8c?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be1e1f59c8c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[faster-r-cnn]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 21:47:40 GMT</pubDate>
            <atom:updated>2020-06-19T08:20:45.929Z</atom:updated>
            <content:encoded><![CDATA[<p>Bilgisayarlı görü(computer vision), Konvolüsyonel Sinir Ağları (Convolution Neural Network-CNN )modellerinin de ortaya çıkması ile son yıllarda büyük bir ivme kazanmıştır. En önemli örneklerinden birisi ise sürücüsüz araçlar ve bunun sonucu olarak da nesne tespitidir.</p><p>Bugün <strong>Faster R-CNN</strong> algoritmasını kullanarak metal levhalar üzerindeki hata tiplerini tespit edip bu hataların sınıflandırılmasına ilişkin bir modelin kurulumunu gerçekleştireceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGQLYgsNYa8bQlz8.png" /><figcaption>kaynak: <a href="https://www.mdpi.com/1424-8220/20/6/1562/htm">https://www.mdpi.com/1424-8220/20/6/1562/htm</a></figcaption></figure><p>Görüntülerdeki detayları yakalamak istediğimizde Konvolüsyonel Sinir Ağlarını kullanmamız gerekmektedir. Başlamadan önce CNN’ in tanımından ve öneminden bahsedelim.</p><p>Konvolüsyonel Sinir Ağları çok katmanlı algılayıcıların (Multi Layer Perceptron-MLP) bir türüdür. Görüntü sınıflandırma ve nesne tanıma gibi görevler için kullanılan ileri yönlü bir sinir ağı olan CNN algoritması, hayvanların görme merkezinden esinlenilerek ortaya atılmıştır. Öncelikle alt özelliklere bakar. Örneğin bir insana ait resim üzerinde göz, kulak, ağız vs. özellikleri tespit ederek bu görüntünün insana ait bir yüz resmi olduğunu belirler.</p><p>CNN, görüntüyü çeşitli katmanlardan geçirerek özellikleri tespit eder ve ham pikselleri anlayabileceğimiz formatlara dönüştürür. Her pikselin 0 ile 255 arasında bir değer aldığı düşünüldüğünde, veri kümesinde ki her bir değer 0 ile 255 arasında bir değer alabilir. Tüm resimleri düzleştirip modele vermek resimdeki birçok özelliğin kaybolmasına neden olacaktır. Bunun yerine görüntünün tümüne sıralı bir şekilde filtre uygulanarak bir özellik haritası (feature map) çıkartılır. CNN, bir veya daha fazla konvolüsyonel katman, alt örnekleme (subsampling) katmanı ve bunun ardından standart çok katmanlı bir sinir ağı gibi bir veya daha fazla tamamen bağlı katmandan oluşur. Aşağıda CNN modeline ait genel mimariyi görmekteyiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*x9FpltmFXIjLgb4l.jpg" /><figcaption>kaynak: <a href="https://www.javatpoint.com/pytorch-convolutional-neural-network">https://www.javatpoint.com/pytorch-convolutional-neural-network</a></figcaption></figure><p>Bugün bu katmanların ne işe yaradığından ve nasıl çalıştıklarından bahsetmeyeceğiz. Ağa bir görüntü aktarıyoruz, konvolüsyon katmanlarından ve bazı işlemlerden(pooling) geçiyor. Daha sonra düzleştirilerek bir yapay sinir ağına giriyor ve sınıflandırılıyor. Peki bu tekniği bir görüntüdeki çeşitli nesneleri tespit etmek için kullanabilir miyiz? <strong>CNN kullanarak genel bir nesne algılama problemini nasıl çözebileceğimizi inceleyelim.</strong></p><p>İlk olarak bir görüntüyü(input) ele alırız. Daha sonra bu görüntüyü çeşitli bölgelere ayırırız. Her bir bölgeyi ayrı bir görüntü olarak düşünürüz. Bu bölgeleri tek tek CNN’ den geçiririz ve sınıflandırırız. Algılanan nesneleri orijinal resim üzerinde görebilmek için tüm bölgeleri birleştiririz. Ancak bu yaklaşımı kullandığımızda bazı problemlerle karşılaşabiliriz. Örneğin, görüntüde ki nesneler farklı en/boy oranına ve ya farklı konumlara sahip olabilir. Ayrıca bazı durumlarda nesne görüntünün büyük bir kısmını kaplarken, diğer bazı durumlarda ise küçük bir alanı kaplayabilir. Bu faktörler göz önüne alındığında çok fazla bölgeye ayırma ihtiyacı doğacak ve bunun sonucu olarak da hesaplama süresi artacaktır. Bu problemi çözmek için bölge tabanlı CNN (<strong>region-based CNN</strong>) modelini kullanabiliriz. Uygulamaya geçmeden önce bölge tabanlı modellere(<strong>R-CNN, Fast R-CNN, Faster R-CNN</strong>) kısaca göz atalım.</p><p><strong>1- R-CNN (Region-based Convolution Neural Network)</strong></p><p>R-CNN sezgisel olarak da yapabileceğimiz bir mantıkla çalışır. Çok sayıda bölge seçmek yerine, önerdiği bazı kutu şeklinde ki görüntü parçalarını belirler ve herhangi bir nesneye karşılık gelip gelmediğini kontrol eder. R-CNN bunu yapmak için seçici arama (selective search ) algoritmasını kullanır. Daha sonra ilgilenilen bu bölgeler konvolüsyon katmanına göre şekillenir ve her bölge bu katmana aktarılır. Son olarak da sınıfları belirlemek için doğrusal SVM(Support Vector Machine) algoritması kullanılır. Sınırlayıcı kutuları belirlemek için ise regresyon modelinden yararlanılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*i912EqHp2Doql7iS.jpg" /><figcaption>kaynak: <a href="https://www.geeksforgeeks.org/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-ml/">https://www.geeksforgeeks.org/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-ml/</a></figcaption></figure><p>Bir resim üzerinde yaklaşık 2000 bölge belirlenir ve bu bölgelerin hepsi bu işlemlerden geçerler. Her bir resim için tahmin yapmak 40–50 saniye sürer. Bu sebepten model eğitimi, büyük boyuttaki veri kümeleri için çok fazla zaman alır ve maliyetlidir.</p><p><strong>2- Fast R-CNN</strong></p><p>R-CNN modelinin aksine, görüntü ilk olarak konvolüsyon katmanına aktarılır ve daha sonra önerilen bölgeler belirlenir. Bu sayede tek bir özellik haritası oluşturulacağı için disk alanında fazla yer kaplamaz. Görüntüler bir yapay sinir ağına girecekleri(<strong>Fully Connected layer</strong>) için aynı boyutlarda olmaları gerekmektedir. Bu yüzden seçilen bölgeleri “RoI pooling” katmanından geçirmek zorundayız. Sonrasında ise SVM’ den daha hızlı ve doğru tahminler yaptığı için yapay sinir ağları kullanılır. Çıktı katmanında ise aktivasyon fonksiyonu “softmax” olarak belirlenir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5LFLJhB2tUEekeVg.png" /><figcaption>kaynak: <a href="https://www.geeksforgeeks.org/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-ml/">https://www.geeksforgeeks.org/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-ml/</a></figcaption></figure><p>Nesnelerin algılanması her bir görüntü için 2 saniye sürer. Ancak gerçek hayattaki büyük boyuttaki veri kümeleri düşünüldüğünde bu modelde pek hızlı gözükmüyor.</p><p><strong>3-) Faster R-CNN</strong></p><p>Fast R-CNN modelinin aksine, Faster R-CNN modeli önerilen bölgeleri oluştururken “Region Proposal Network” isminde bir algoritma kullanır. Bu algoritma bir “sliding window” oluşturur ve konvolüsyon katmanında oluşturulan özellik haritası üzerinde gezer. Buna filtre benzetmesi yapsak yanlış olmaz sanırım. Mantığı ise şudur; her bölgede bir nesnenin olduğunu varsayar ve bölgelere tarafsız puanlar atar. Bunun için bitişik piksellere, renk, yoğunluk vs. kriterlere bakar. Daha sonra “ReLU” aktivasyon fonksiyonu kullanılarak yeni bir özellik haritası çıkartılır. Geri kalan adımlar Fast R-CNN ile benzerdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*YA7JU5xagXsZy1Kc.png" /><figcaption>kaynak: <a href="https://www.geeksforgeeks.org/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-ml/">https://www.geeksforgeeks.org/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-ml/</a></figcaption></figure><p>Faster R-CNN ile bu algoritma sayesinde tahmin süresini yaklaşık 0,2 saniyeye kadar çekmiş oluruz.</p><p>Şimdi uygulamaya geçebiliriz. Bu uygulama için yukarıda belirtiğimiz gibi Faster R-CNN modelini kullanacağız. Hadi başlayalım.</p><h4><strong>Metal Levhalar Üzerindeki Hata Tiplerinin Tespiti</strong></h4><p>Biz bu projeyi “Anaconda Prompt” üzerinden “Virtual Environment” oluşturarak gerçekleştirdik. Öncelikle Anaconda’ nın bilgisayarımızda kurulu olması gerekmektedir.</p><p>Bu çalışmada Tensorflow v1.15 (CPU) kullandık. Buna uygun python sürümlerine <a href="https://www.tensorflow.org/install/source#tested_build_configurations">buradan</a> bakabilirsiniz. Tensorflow GPU kullanmak isteyenler CUDA ve cuDNN indirmeleri gerekmektedir. Ekran kartınıza uygun versiyonları öğrenmek için <a href="https://developer.nvidia.com/cuda-gpus">buraya</a> göz atabilirsiniz.</p><p>1. İlk olarak <a href="https://github.com/tensorflow/models">https://github.com/tensorflow/models</a> adresindeki dosyayı .zip formatında indirelim.(TensorFlow Object Detection API repository)</p><p>2. C:/ dizininde “tensorflow1” isimli bir dosya açın ve indirdiğimiz “models_master.zip” dosyasını buraya çıkartalım ve ismini “models” olarak değiştirelim.</p><p>3. Bu <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md.">linkten</a> “faster_rcnn_ inception_ v2_coco” eğitilmiş modelini indirelim. Bu dosyayı C:\tensorflow1\models\research\object_detection klasörüne çıkartalım.</p><p>4. Github repomdaki “object_detection.zip” adlı dosyayı indirin ve ..\object_detection klasörü içerisine çıkartalım.</p><p>5. Bu işlemleri yaptıktan sonra şimdi “Virtual Environment” oluşturalım. Anaconda Prompt’ a aşağıdaki komutu yazalım ve bunu aktif hale getirelim.</p><pre>C:\&gt;conda create -n tensorflow1 pip python=3.7<br>C:\&gt;conda activate tensorflow1</pre><p>6. Kullanacağımız kütüphaneleri sırası ile indirelim. Tüm kütüphanelerin düzgün yüklendiğinden emin olun.</p><pre>(tensorflow1) C:\&gt;pip install --ignore-installed --upgrade tensorflow==1.15<br>(tensorflow1) C:\&gt;conda install -c anaconda protobuf<br>(tensorflow1) C:\&gt;pip install pillow lxml cython jupyter matplotlib pandas opencv-python</pre><p>7 . Pythonpath’ i belirtmemiz gerekiyor. “Virtual Environment” i aktif hale getirdiğimizde bu komutuda her zaman çalıştırmanız gerekiyor.</p><pre>(tensorflow1) C:\&gt;set PYTHONPATH=C:\tensorflow1\models;C:\tensorflow1\models\research;C:\tensorflow1\models\research\slim</pre><p>8. tf_slim’ i kullanacağımız için bunu da yüklemeliyiz.</p><pre>(tensorflow1) C:\&gt;pip install --upgrade tf_slim</pre><p>9. Şimdi protobufları derlememiz gerekiyor. İlk önce komut satırında aşağıdaki komutu çalıştırın ve dizini ayarlayın. Daha sonra diğer komutu çalıştıralım.</p><pre>(tensorflow1)C:\&gt;cd C:\tensorflow1\models\research<br>protoc --python_out=. .\object_detection\protos\anchor_generator.proto .\object_detection\protos\argmax_matcher.proto .\object_detection\protos\bipartite_matcher.proto .\object_detection\protos\box_coder.proto .\object_detection\protos\box_predictor.proto .\object_detection\protos\eval.proto .\object_detection\protos\faster_rcnn.proto .\object_detection\protos\faster_rcnn_box_coder.proto .\object_detection\protos\grid_anchor_generator.proto .\object_detection\protos\hyperparams.proto .\object_detection\protos\image_resizer.proto .\object_detection\protos\input_reader.proto .\object_detection\protos\losses.proto .\object_detection\protos\matcher.proto .\object_detection\protos\mean_stddev_box_coder.proto .\object_detection\protos\model.proto .\object_detection\protos\optimizer.proto .\object_detection\protos\pipeline.proto .\object_detection\protos\post_processing.proto .\object_detection\protos\preprocessor.proto .\object_detection\protos\region_similarity_calculator.proto .\object_detection\protos\square_box_coder.proto .\object_detection\protos\ssd.proto .\object_detection\protos\ssd_anchor_generator.proto .\object_detection\protos\string_int_label_map.proto .\object_detection\protos\train.proto .\object_detection\protos\keypoint_box_coder.proto</pre><p>10. Devamında kurulum dosyalarını çalıştıralım.</p><pre>(tensorflow1) C:\tensorflow1\models\research&gt;python setup.py build<br>(tensorflow1) C:\tensorflow1\models\research&gt;python setup.py install</pre><p>11. Şimdi verileri Labelimg programı ile etiketleyelim. İlk önce aşağıdaki komutu çalıştıralım ve daha sonra command prompt a “labelimg” yazalım.</p><pre>(tensorflow1) C:\&gt;pip install labelimg<br>(tensorflow1) C:\&gt;labelimg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoDtxLWDmiMSUselQ41TRw.png" /></figure><p>12. Fotoğrafları bu şekilde hem eğitim hemde test kümesi için etiketleyelim. Xml dosyaları ile birlikte fotoğrafları C:\tensorflow1\models\research\object_detection\imagesdizininde train ve test dosyaları oluşturarak buraya atalım.</p><p>Xml dosyalarını .csv formatına dönüştürmek için aşağıdaki komutu çalıştıralım.</p><pre>(tensorflow1) C:\tensorflow1\models\research\object_detection&gt;python xml_to_csv.py</pre><p>13. Bundan sonra “object_detection” klasörü içerisinde ki “generate_tfrecord.py” isimli dosyayı bir text editörü ile açalım. Sınıfları kendi verimize göre düzenleyelim.</p><pre>def class_text_to_int(row_label):<br>    if row_label == &#39;DefectTypeA&#39;:<br>        return 1<br>    elif row_label == &#39;DefectTypeB&#39;:<br>        return 2<br>    elif row_label == &#39;DefectTypeC&#39;:<br>        return 3<br>    else:<br>        None</pre><p>14. “Record” dosyalarını oluşturmak için aşağıdaki komutları çalıştıralım. Öncesinde dizini şu şekilde ayarlayalım: C:\tensorflow1\models\research\object_detection</p><pre>python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record</pre><pre>python generate_tfrecord.py --csv_input=images\test_labels.csv --image_dir=images\test --output_path=test.record</pre><p>15. ..\object_detection\training dosyası içerisindeki “labelmap.pptxt” dosyasını bir editör yardımı ile açalım ve kendi sınıflarımıza göre düzenleme yapalım.</p><pre>item {<br>  id: 1<br>  name: &#39;DefectTypeA&#39;<br>}<br>item {<br>  id: 2<br>  name: &#39;DefectTypeB&#39;<br>}<br>item {<br>  id: 3<br>  name: &#39;DefectTypeC&#39;}</pre><p>16. Faster_rcnn_inception_v2.. klasörü içerisinde ki “pipeline.config” dosyasını ve ..\object_detection\samples\configs dosya konumunda ki “faster_rcnn_inception_v2_pets.config” dosyasını ..\object_detection\training dosyası içerisine kopyalayalım.</p><p>17. Daha sonra “faster_rcnn_inception_v2_pets.config” dosyasını bir text editörü ile açalım. Bazı düzenlemeler yapmalıyız.</p><p>#(9. satır) num_classes değerini 3 olarak değiştirelim.</p><p>#(110. satır) faster_rcnn_v2_coco modeliniz nerede ise dosya yolunu doğru bir şekilde ayarlayın. fine_tune_checkpoint : &quot;C:/tensorflow1/models/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt&quot;</p><p>#(126 ve 128. satır) input_path : &quot;C:/tensorflow1/models/research/object_detection/train.record&quot;<br> label_map_path: &quot;C:/tensorflow1/models/research/object_detection/training/labelmap.pbtxt&quot; Bu şekilde görünmelidir.</p><p>#(132. satır) Test kümemizde kaç adet fotoğraf varsa belirtiniz.(num_examples)</p><p>#(140 ve 142. satır) input_path : &quot;C:/tensorflow1/models/research/object_detection/test.record&quot;<br> label_map_path: &quot;C:/tensorflow1/models/research/object_detection/training/labelmap.pbtxt&quot; Bu şekilde gözükmelidir ve ya sizin dosya konumlarınıza göre değişebilir.</p><p>18. “inference_graph” dosyası içerisindeki her şeyi ve “training” dosyası içerisindeki kontrol noktalarını silelim. Daha sonra dizini ..\object_detection olacak şekilde ayarlayıp aşağıdaki komutu çalıştıralım ve modelimizi eğitmeye başlayalım.</p><pre>python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*CvAOc6hfRetT4SVuAUvYdA.png" /></figure><p>Kayıp değeri kalıcı bir şekilde 0.05 in altına düştüğünde “anaconda prompt” u kapatabiliriz.</p><p>19. “inference_graph” dosyası oluşturalım. XXXX yazan yere son kontrol noktasına ait değeri girelim. ..\object_detection\training dosyasına bakabilirsiniz.</p><pre>python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph</pre><p>20. Modeli test etmek için komut satırına “idle” yazalım. Açılan pencerede sol üst köşeden “Object_detection_image.py” dosyasını seçelim. “num_classes” değişkenine sınıf sayımızı girelim ve test etmek istediğimiz resmin dosya yolunu aşağıda belirtelim. F5 ile çalıştırabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*9fsgk5rTJE9f6zTChSbZ-g.png" /></figure><p>Şimdi sonuçları görelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*jVHyrC7URHjeMrXYlQmErg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*8lCxMGDlfaVgB4hooXa3RA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*THPRR3YynOtxXLxKCDHT0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*cvyCMK1DxybBY2q8Y0_lDg.png" /></figure><p>GitHub linki: <a href="https://github.com/muhammetbektas/Defect-Type-Detection-using-Faster-R-CNN">https://github.com/muhammetbektas/Defect-Type-Detection-using-Faster-R-CNN</a></p><p>Yararlandığım kaynaklar;</p><ul><li><a href="https://www.analyticsvidhya.com/blog/2018/10/a-step-by-step-introduction-to-the-basic-object-detection-algorithms-part-1/">A Step-by-Step Introduction to the Basic Object Detection Algorithms (Part 1)</a></li><li><a href="https://readthedocs.org/projects/tensorflow-object-detection-api-tutorial/">TensorFlow Object Detection API Tutorial</a></li><li><a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10">GitHub - EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10: How to train a TensorFlow Object Detection Classifier for multiple object detection on Windows</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be1e1f59c8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A comprehensive Guide to Scikit-learn Part 1: Overview of the Package]]></title>
            <link>https://medium.com/bootrain-blog/a-comprehensive-guide-to-scikit-learn-part-1-overview-of-the-package-b766f1da50da?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b766f1da50da</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 07:31:01 GMT</pubDate>
            <atom:updated>2020-06-02T07:52:27.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Scikit-learn is the most popular machine learning package in the data science community. Written in Python programming language, scikit-learn provides quite effective and easy to use tools for data processing to implementing machine learning models. Besides its huge adoption in the machine learning word, it continues to inspire packages like Keras and others with its now industry standard APIs. If you’re a data science enthusiast, there’s no better tool to learn first for machine learning tasks. In a series of articles, we’ll examine most commonly used functionalities and submodules of scikit-learn so that you can benefit from this series as a reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*uwoTIFgENqV1fS712lQWwg.png" /><figcaption>Source: <a href="https://keras.io/why_keras/">https://keras.io/why_keras/</a></figcaption></figure><p>As a first article of this series, we devote this article to a wholistic overview of the scikit-learn library so that you can get a bird-eye view of what it provides and for what purposes you can use it. In the later articles, we’ll dig deeper into these functionalities.</p><h4><strong>Installing scikit-learn:</strong></h4><p>Throughout this series, we prefer to use the following setup:</p><p>We’ll be writing our code in Python 3 (preferably higher than version 3.6). We are going to use Jupyter Notebook as our choice of IDE. After you’ve completed the installations of these, you can install scikit-learn by running the following command from your terminal (or command prompt):</p><pre>pip install -U scikit-learn</pre><p>If you want to use conda as your package manager, then you can install it as:</p><pre>conda install scikit-learn</pre><p>Alternatively, you can install the scikit-learn package directly from your Jupiter Notebook by putting an exclamation mark (!) in front of the commands above. That is like:</p><pre>!pip install -U scikit-learn</pre><p>For more details, you can look at <a href="https://scikit-learn.org/stable/install.html">the documentation of scikit-learn</a>.</p><h4><strong>Simplicity of the Scikit-learn API design:</strong></h4><p>The single most important reason why scikit-learn is the most popular machine learning package out there is its <strong>simplicity</strong>. No matter you’re using a linear regression, random forest or support vector machine; you’re always calling the same functions and methods. Moreover, you can build end-to-end machine learning pipelines with a couple of codes. This simplicity of the design and the ease of use inspired many other packages like <strong>Keras</strong> and paved the way for many enthusiasts to jump into the machine learning space.</p><p>Here, we’d like to talk about a couple of apis such that you can do many of the machine learning tasks by using these. We’re talking about three basic interfaces: <strong>estimator</strong>, <strong>predictor</strong> and <strong>transformer</strong>.</p><ul><li>The <strong>estimator interface</strong> represents a machine learning model that needs to be trained on a set of data. Training a model is a central issue in any machine learning pipeline and hence we need to use this a lot. In scikit-learn, any model can be trained easily with the <strong>fit()</strong> method of the estimator interface. Yes, all the models regardless of regression or classification problem; supervised or unsupervised task. This is where scikit-learn’s design shines in.</li><li>Similar to the estimator interface, there’s another one which is called the <strong>predictor interface</strong>. It expands the concept of an estimator by adding a <strong>predict()</strong> method and it represents a trained model. Once we have a trained model, most often than not we want to get predictions out of it and here it suffices to use the <strong>predict()</strong> method! The graph below demonstrates a machine learning pipeline where fit and predict methods come into play. Note that, instead of calling <strong>fit()</strong> and <strong>predict() </strong>separately, one can also use <strong>fit_predict()</strong> method which first train a model and then get the predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*z6INhZv54HmlqTsc-ZM10g.png" /></figure><ul><li>The next interface we want to bring to your attention is the <strong>transformer interface. </strong>A crucial work when working with data is to transform the variables. Whether it refers to scaling a variable or vectorizing a sentence, the transformer interface enables us to do all the transformations by calling the <strong>transform() </strong>method. Usually, we use this method after the <strong>fit()</strong> method. This is because operations that are used to transform variables are also treated as estimators. Hence, calling <strong>fit()</strong> method returns an estimator trained on a data and applying <strong>transform()</strong> on a data using this estimator transforms the data. Instead of calling fit and transform methods separately, one can also use the <strong>fit_transform() </strong>method as a short-cut. The combined fit_transform method usually works more efficiently with respect to the computation time. The figure below illustrates the usage of transform in a machine learning pipeline setting:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*OBa9Z9VZ7HlfOfHSfIirjw.png" /></figure><h4><strong>Submodules of Scikit-learn:</strong></h4><p>Now that we saw the basic interfaces of scikit-learn, we can now talk about the modules it contains. In the next articles of this series, we’ll give you hands-on examples of how you can use these modules.</p><p>These modules are organized in a way that each module serves only the functionality of its purpose. This clear design of submodules makes understanding and using the library easy and as we’ve touched upon before, the architectural design of the library is what makes it so popular among the machine learning community.</p><p>From now on, we’ll discuss the submodules and what kind of classes and functions each one provides. We’ll complete this article with this discussion. Starting from the next article, we’ll examine each module one by one using by demonstrating with code examples.</p><p><strong>1-) Datasets : sklearn.datasets</strong></p><p>With this module scikit-learn provides various cleaned and built-in datasets so that you can jump start playing with machine learning models right away. These datasets are among the most well-known datasets which you can easily load them with a few lines of codes. The datasets offer complete descriptions of the data itself such as iris, boston house prices, breast_cancer etc. Moreover, this module also provides a dataset fetcher that can be used to load real world datasets that are large in size. Before starting to use a toy dataset(for example boston house price dataset), we should import it like this;</p><pre>from sklearn.datasets import load_boston</pre><p>When using a real world datasets, a fetcher for the dataset is built into Scikit-learn. For example “mnist_784” dataset, we should use fetch_openml() function.</p><pre>from sklearn.datasets import fetch_openml<br>mnist = fetch_openml(&#39;mnist_784&#39;, version=1, cache=True)</pre><p><strong>2-) Preprocessing : sklearn.preprocessing</strong></p><p>Before starting to train our machine learning models and make predictions, we usually need to do some preprocessing on our raw data. Among some commonly used preprocessing tasks come OneHotEncoder, StandardScaler, MinMaxScaler, etc. These are respectively for encoding of the categorical features into a one-hot numeric array, standardization of the features and scaling each feature to a given range. Many other preprocessing methods are built-in this module.</p><p>We can import this module as follows:</p><pre>from sklearn import preprocessing</pre><p><strong>3-) Impute : sklearn.impute</strong></p><p>Missing values are common in real world datasets and can be filled easily by using the Pandas library. This module of the scikit-learn also provides some methods to fill in the missing values. For example, <strong>SimpleImputer</strong> imputes the incomplete columns using statistical values of those columns, <strong>KNNImputer</strong> uses KNN to impute the missing values. For more on the imputation methods scikit-learn provides, you can look at <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.KNNImputer.html#sklearn.impute.KNNImputer">the documentation.</a></p><p>This module can be imported as shown below:</p><pre>from sklearn import impute</pre><p><strong>4-) Feature Selection : sklearn.feature_selection</strong></p><p>Feature selection is very crucial in the success of the machine learning models. Scikit-learn provides several feature selection algorithms in this module. For example, one of the feature selectors that is available in this module is <strong>RFE(</strong>Recursive Feature Elimination<strong>)</strong>. It is essentially a backward selection process of the predictors. This technique starts with building a model on the whole dataset of predictors and computes a score of importance for each predictor. Then the least important predictor(s) are removed, the model is re-built, and scores of importance are again calculated.</p><p>We can import this module as the following:</p><pre>from sklearn import feature_selection</pre><p><strong>5-) Linear Models : sklearn.linear_model</strong></p><p>Linear models are the fundamental machine learning algorithms that is heavily used in supervised learning tasks. This module contains a family of linear methods such that the target value is expected to be a linear combination of the features. Among the models in this module, <strong>LinearRegression</strong> is the most common algorithm for regression tasks. <strong>Ridge</strong>, <strong>Lasso</strong> and <strong>ElasticNet</strong> are models with regularization to reduce overfitting.</p><p>The module can be imported as follows:</p><pre>from sklearn import linear_model</pre><p><strong>6-) Ensemble Methods : sklearn.ensemble</strong></p><p>Ensemble methods are advanced techniques which are often used to solve complex problems in machine learning using stacking, bagging or boosting methods. These methods allow different models to be trained on the same dataset. Each model makes its own prediction and a meta-model consists of a combination of these estimates. Among the models this module provides, it comes bagging methods like Random Forests, boosting methods like AdaBoost and Gradient Boosting and stacking methods like VotingClassifier.</p><p>We can import this module as follows:</p><pre>from sklearn import ensemble</pre><p><strong>7-) Clustering : sklearn.cluster</strong></p><p>Clustering is a very common unsupervised learning problem. This module provides several clustering algorithms like <strong>KMeans</strong>, <strong>AgglomerativeClustering</strong>, <strong>DBSCAN</strong>, <strong>MeanShift</strong> and many more.</p><p>The module can be imported as the following:</p><pre>from sklearn import cluster</pre><p><strong>8-) Matrix Decomposition : sklearn.decomposition</strong></p><p>Dimensionality reduction is something we resort to occasionally. This module of scikit-learn provides us several dimension reduction methods. Principal Components Analysis (PCA) is probably the most popular one. Other methods like SparcePCA are also available in this module.</p><p>We can import this module as follows:</p><pre>from sklearn import decomposition</pre><p><strong>9-) Manifold Learning : sklearn.manifold</strong></p><p>Manifold learning is a type of non-linear dimensionality reduction process. This module provides us many useful algorithms that are helpful in tasks like visualization of the high dimensional data. There are various manifold learning methods available in this module such as <strong>T-SNE</strong>, <strong>Isomap</strong> etc.</p><p>We can import this module as follows:</p><pre>from sklearn import manifold</pre><p><strong>10-) Metrics : sklearn.metrics</strong></p><p>Before starting to train our models and make predictions, we always consider which performance measure should best suit for our task at hand. Scikit-learn provides access to a variety of these metrics. Accuracy, precision, recall, mean squared errors are among the many metrics that are available in this module.</p><p>We can import this module as the following:</p><pre>from sklearn import metrics</pre><p><strong>11-) Pipeline : sklearn.pipeline</strong></p><p>Machine learning is an applied science and we often repeat some subtasks in a machine learning workflow such as preprocessing, training model, etc. Scikit-learn offers a pipeline utility to help automate these workflows. <strong>pipeline.Pipeline()</strong> and <strong>pipeline.make_pipeline()</strong> functions in this module can be used for creating a pipeline.</p><p>We can import this module as follows:</p><pre>from sklearn import pipeline</pre><p><strong>12-) Model Selection : sklearn.model_selection</strong></p><p>The selection process for the best machine learning models is largely an iterative process where data scientists search for the best model and the best hyper-parameters. Scikit-learn offers us many useful utilities that are helpful in both training, testing and model selection phases. In this module, there exists utilities like <strong>KFold</strong>, <strong>train_test_split(), GridSearchCV</strong> and <strong>RandomizedSearchCV</strong>. From splitting our datasets to searching for hyper-parameters, with its offerings, this module is one of the best friends of a data scientist.</p><p>We can import this module as the following:</p><pre>from sklearn import model_selection</pre><h4>Concluding remarks</h4><p>We’re done with our introduction to scikit-learn. Starting from the next article, we’ll dig deep into the details of this fascinating library. One of the mission of <a href="http://www.bootrain.com/">Bootrain</a> is to provide accessible contents for everyone who’d like to jump into data science. So, stay tuned and please follow us in other platforms as well.</p><p>LinkedIn: <a href="https://www.linkedin.com/company/bootrain">https://www.linkedin.com/company/bootrain</a></p><p>Twitter: <a href="https://twitter.com/BootrainSchool">https://twitter.com/BootrainSchool</a></p><p>Web: <a href="https://www.bootrain.com/">www.bootrain.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b766f1da50da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bootrain-blog/a-comprehensive-guide-to-scikit-learn-part-1-overview-of-the-package-b766f1da50da">A comprehensive Guide to Scikit-learn Part 1: Overview of the Package</a> was originally published in <a href="https://medium.com/bootrain-blog">Bootrain Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kümeleme Algoritmaları ile Müşteri Segmentasyonu]]></title>
            <link>https://medium.com/@mbektas/k%C3%BCmeleme-algoritmalar%C4%B1-ile-m%C3%BC%C5%9Fteri-segmentasyonu-498d63c56204?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/498d63c56204</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Sun, 17 May 2020 16:35:52 GMT</pubDate>
            <atom:updated>2020-05-19T09:46:35.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Gözetimli öğrenmenin aksine, gözetimsiz öğrenme sadece bağımsız değişkenlere sahiptir yani bağımlı değişken yoktur. Kısaca, veri etiketsizdir. Bu yüzden gözetimsiz öğrenme problemlerinde hedef değişken olmadığı için modelimizin doğruluğunu test etmemiz ve nerede durmamız gerektiğini belirlememiz de zor. Yine de bu modelleri basitçe test edebiliriz. Kümeleme yaparken hedeflediğimiz ve ya makul olan sonuçları seçebiliriz.</p><p>Aslında bu tip problemler gözetimli öğrenmeye girdi oluşturmak için kullanılırlar. Bunlar boyut indirgeme ve kümele problemleri olarak ikiye ayrılır. Gözetimsiz öğrenmenin amacı, veriler hakkında daha fazla bilgi edinmek için verilerin altındaki yapıyı veya dağılımı modellemektir. Bugün, bir kümeleme problemini ele alacağız. Kümeleme algoritmalarını kullanarak müşterileri gruplandırmaya çalışacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WPRSp4BDn__-CAt4.png" /></figure><p>Müşteri segmentasyonu, hitap edilen kitleyi ihtiyaçlarına ve davranışlarına göre farklılaştırarak modellemektir. Günümüz dünyasının getirdiği yoğun veri akışı ile müşteriyi doğru tanımak müşteri segmentasyonu için önemlidir. Ayrıca firmalar artan maliyetler nedeniyle doğru yaklaşımlarla doğru hedef kitlelere ulaşmalı ve müşteriyi daha iyi tanımalıdır.</p><p>Müşteri segmentasyonu için Kaggle’da bulunan “<a href="https://www.kaggle.com/arjunbhasin2013/ccdata">Credit Card Dataset</a>” isimli veri kümesini inceleyeceğiz. Müşterilere ait “purchases frequency, purchases installment frequency, balance” gibi pek çok bilgi bulunmakta. Burada kredi kartı kullanıcılarının tutumlarına göre onları gruplara ayırmayı deneyeceğiz.</p><p>İlk olarak verimizde ki kayıp değerleri doldurma, standartlaştırma gibi ön işlemleri yaparak başladık ve fazla sayıda aykırı değer tespit ettik. Kümele yaparken aykırı değerleri atmak pek iyi bir tercih olmayabilir çünkü; bu bilgi kaybına sebep olabilir. Şöyle ki, bu değerler farklı bir kümeye ait olabilir ve bunları atmak ya da “winsorize” etmek var olan bir grubu görmemize engel olabilir. Bu yüzden aykırı değerlere dokunmadık. Şimdi algoritmaları uygulamaya başlayabiliriz. Bunları kullanmak için “sklearn.cluster” modülündeki algoritmaları çağıracağız.</p><ol><li><strong>K-Means</strong></li></ol><p>“K-Means” en çok kullanılan kümele algoritmalarından birisidir. Burada ki temel amaç k kümelerinin merkezlerini oluşturan en iyi “centroid” noktalarını atamaktır. Algoritma bu noktaları rastgele seçer. “K-Means” kayıp fonksiyonunu(inertia) minimize eden k değerlerini bulmayı amaçlamaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*g6ufGxkUxZId1FF2Sts3bA.png" /></figure><p>“Silhouette Score” temel gerçekliğe sahip olmadığımız durumlarda en çok kullandığımız ölçüm metriklerden birisidir. Bir veri noktası için silüet katsayısı (bi−ai)/max(bi,ai) dir. Bir veri noktası ile kümedeki diğer tüm veri noktaları arasındaki ortalama mesafe (ai), bu veri noktasına en yakın kümede ki diğer tüm veri noktalarına olan ortalama uzaklık (bi) dir. “Davies Bouldin Score” ise yine kümeler arası ortalama benzerliği ölçmek için kullanılır. Bu oran için düşük değerler tercih edilir ve minumum skor değeri 0 dır.</p><p>“Elbow method” yardımı ile ve aynı zamanda “Silhouette” ve “Davis Bouldin” performans skorlarına da bakarak küme sayısını 7 olarak belirledik. Şimdi kümeleri görselleştirelim ama öncesinde çok fazla “feature” olduğu için boyut azaltmaya gitmemiz gerekiyor. Bu nedenle “PCA” uyguladık.</p><pre>pca = PCA(n_components=3).fit_transform(df_norm)<br>fig = plt.figure(figsize=(12, 7), dpi=80, facecolor=&#39;w&#39;, edgecolor=&#39;k&#39;)<br>ax = plt.axes(projection=&quot;3d&quot;)<br>ax.scatter3D(pca.T[0],pca.T[1],pca.T[2],c=kmeans_labels,cmap=&#39;Spectral&#39;)<br><br>xLabel = ax.set_xlabel(&#39;X&#39;)<br>yLabel = ax.set_ylabel(&#39;Y&#39;)<br>zLabel = ax.set_zlabel(&#39;Z&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*ClArwtUU2wgAxfe8.png" /></figure><p>“K-Means” pek iyi bir performans göstermedi gibi görünüyor. Ancak diğer algoritmalara da bakalım.</p><p><strong>2. MiniBatch K-Means</strong></p><p>Bildiğiniz gibi “MiniBatch K-Means” , “K-Means” e göre daha hızlı çalışır ve bazende küçük farklılıklar ile kümele yapabilir. Küme sayısını yukarıda kullandığımız performans skorlarına göre 6 olarak belirledik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*MIYlgOMG40m4Qxfq.png" /></figure><p><strong>3. Hierarchical Clustering</strong></p><p>Hiyerarşik kümeleme, veri içinde ağaç benzeri küme hiyerarşisi oluşturmayı amaçlayan bir kümeleme tekniğidir. Biz burada Yığınsal (Agglomerative) kümelenme yaklaşımını kullanacağız. Kümelerin ağaç benzeri hiyerarşik temsiline “dendrogram” denir. Küme sayısını “dendogram” yardımı ile belirleyebiliriz.</p><pre>plt.figure(figsize=(10, 7))  <br>plt.title(&quot;Dendrograms&quot;)  <br>dend = shc.dendrogram(shc.linkage(df_norm, method=&#39;ward&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*6oFF7rzWyFw1iHBg.png" /></figure><p>Kümeler arasındaki benzerliği ölçmek için kullandığımız ölçüm teknikleri (euclidean, manhattan, cosine) dışında, benzerlikleri hesaplarken kümelerin temsili öğelerini nasıl seçeceğimize karar vermemiz gerekir. Bu amaçla “linkage” parametresini de ayarlamalıyız. Küme sayısını önceden belirtmemize gerek yoktur. Burada duracağı noktayı belirliyoruz.</p><pre>hcluster = AgglomerativeClustering(n_clusters=3, affinity=&#39;euclidean&#39;, linkage=&#39;ward&#39;)<br>hcp=hcluster.fit_predict(df_norm)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*nZ3LIpfjFNRDKHoL.png" /></figure><p><strong>4. DBSCAN</strong></p><p>Adından da anlaşıldığı üzere yoğunluk temelli mekansal bir algoritmadır. “K-means” ve hiyerarşik kümeleme algoritmaları dairesel kümeleri bulmakta gayet iyidir. Ancak ayrımı belirgin olmayan ya da halka için de halka gibi dışbükey olmayan şekilli kümeleri belirleme konusunda pek başarılı değillerdir. Küme sayısını önceden belirtmemize gerek yoktur. Ancak iki parametreyi ayarlamamız gerekir. Bunlar komşuların aranacağı yarıçap(eps) ve küme oluşturmak için gereken en az nokta(min_samples) sayısıdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*qs46Z5uRaDi_ddrKU7NK4g.png" /></figure><p>“DBSCAN” bu veri kümesi için pek uygun bir yöntem değil. Burada “eps” 0.4 ve “min_samples” 4 olarak belirledik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*W26BA4xogDntCpPeccW6qw.png" /></figure><p><strong>5. GMM</strong></p><p>Gauss Karışım Modelleri (GMM), verilerin birden fazla<strong> </strong>normal dağılımının karışımıyla oluşturulduğunu varsayarak veri üretme süreçleri bulmayı amaçlamaktadır. Verideki kümelerin her biri için normal dağılımlar arar. Veri kümesi içerindeki normal dağılım sayına göre küme sayısını belirler. Burada belirlememiz gereken parametrelerden birisi de dağılımların kovaryansıdır.</p><pre>parameters=[&#39;full&#39;,&#39;tied&#39;,&#39;diag&#39;,&#39;spherical&#39;]<br>n_clusters=np.arange(1,21)<br>results_=pd.DataFrame(columns=[&#39;Covariance Type&#39;,&#39;Number of Cluster&#39;,&#39;Silhouette Score&#39;,&#39;Davies Bouldin Score&#39;])<br>for i in parameters:<br>    for j in n_clusters:<br>    gmm_cluster=GaussianMixture(n_components=j,covariance_type=i,<br>    random_state=123)<br>    clusters=gmm_cluster.fit_predict(df_norm)<br>    if len(np.unique(clusters))&gt;=2:<br>       results_=results_.append({&quot;Covariance Type&quot;:i,&#39;Number of<br>       Cluster&#39;:j,&quot;Silhouette Score&quot;:metrics.silhouette_score<br>       (df_norm,clusters),&#39;Davies Bouldin Score&#39;<br>       :metrics.davies_bouldin_score(df_norm,clusters)}<br>       ,ignore_index=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*qeF3slvbuvOn59Kl.png" /></figure><p>Kovaryans tipini “spherical” ve küme sayısını 5 olarak belirledik.</p><pre>gmm_cluster=GaussianMixture(n_components=5,covariance_type=&quot;spherical&quot;,random_state=123)<br>gmm_cluster.fit(df_norm)<br>gmm_labels = gmm_cluster.predict(df_norm)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*lwVBVjUN-Du10gZ5.png" /></figure><p><strong>6. MeanShift</strong></p><p>“MeanShift” temel olarak noktaları verilerin en yüksek yoğunluğa sahip olduğu yöne, yani küme merkezine doğru kaydırarak kümelere veri noktalarını yinelemeli olarak atar. Öncesinden küme sayısını belirtmemize gerek yoktur.</p><pre>est_bandwidth = estimate_bandwidth(df_norm,quantile=.1,n_samples=10000)<br>mean_shift = MeanShift(bandwidth= est_bandwidth, bin_seeding=True).fit(df_norm)<br>labels_unique=np.unique(mean_shift.labels_)<br>n_clusters_=len(labels_unique)<br>print(&quot;Number of estimated clusters : %d&quot; % n_clusters_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*5NwIoeW_pSzn59uj.png" /></figure><p><strong>Sonuçların Karşılaştırılması</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*IaAh743adD-lV9Dw.png" /></figure><p>Bir çok algoritma denedik ve en iyi performans değerleri “K-Means” e ait. Verilerimizi kümelemek için bu algoritmayı kullanacağız. Böylece 7 farklı müşteri profine sahip olduğumuzu varsayıyoruz. Şimdi müşterileri davranışlarına göre gruplandıralım. Müşterileri tanımlarken önemli olduğunu düşündüğüm sütunları belirledim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0Fc2j418hxxUwnR2YSIQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*9w4VrpkedaNJDSsNw_uQxg.png" /></figure><p>Cluster 0<strong> </strong>: En fazla alışveriş yapan ve aynı zaman taksitle ödemeyi tercih eden grup. En yüksek kredi limitine sahipler ve uzun dönem müşterileridir.</p><p>Cluster 1 : Çok az sıklıkla alışveriş yaparlar. Hesaplarında az miktarda para bulundururlar ve kredi limitleri düşüktür.</p><p>Cluster 2 : En fazla müşterinin olduğu gruptur. Aynı zamanda da kredi kartlarını en az kullanan gruptur. Genellikle aktif olmayan ve uzun dönem müşterileridir.</p><p>Cluster 3 : Taksitle ödeme eğilimi ve alışveriş yapma sıklığı yüksektir. Yine bu grup içinde uzun dönem müşteri diyebiliriz. Kredi limitleri ortalamanın altındadır.</p><p>Cluster 4 : Hesaplarında en fazla para bulunduran gruptur. Ancak alışveriş sıklığı çok düşüktür. Nakit ödeme eğilimindedirler. Para harcamayı pek sevmezler.</p><p>Cluster 5 : En fazla alışveriş yapan diğer bir gruptur ve en fazla taksitle ödeme eğilimi olan gruptur. Kredi limitleri ortalamanın çok altındadır.</p><p>Cluster 6 : En az sayıda müşterinin bulunduğu gruptur. Alışveriş sıklıkları ortalamanın altındadır. Kısa dönem müşterisidirler.</p><p>Daha fazla ayrıntı için GitHub hesabımı ziyaret edebilirsiniz.</p><p><a href="https://github.com/muhammetbektas/Unsupervised-Learning/blob/master/Segmentation_of_Credit_Card_Users.ipynb">https://github.com/muhammetbektas/Unsupervised-Learning/blob/master/Segmentation_of_Credit_Card_Users.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498d63c56204" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Segmentation with Clustering Algorithms in Python]]></title>
            <link>https://medium.com/@mbektas/customer-segmentation-with-clustering-algorithms-in-python-be2e021035a?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/be2e021035a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Sat, 16 May 2020 09:04:05 GMT</pubDate>
            <atom:updated>2020-05-18T20:18:10.692Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlike Supervised Learning, Unsupervised Learning has only independent variables and no corresponding target variable. Shortly, the data is unlabeled. The aim of unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3ivZYW7OUjnfKtDJKvW5g.png" /></figure><p>We are going to examine a dataset that is about credit card users for segmentation. There is no any feature about label of customers. That is to say, we don’t have information about customer’s characteristics. We are going to try clustering clients with machine learning algorithms. Segmentation of customers has a pretty significant position for companies in new marketing diciplines. Firms must reach to the right target audiences with right approaches because of increasing costs.</p><p>First of all, we have started with data preprocessing such as filling the missing values ,standardization etc. Let’s start the application of the most used clustering algorithms.</p><p><strong>1.K-Means Algorithm</strong></p><p>K-Means is probably the most famous algorithm for clustering. To begin, we have drawn or plot a line according to inertia(sum of squared distances of samples to their closest cluster center) scores of number of cluster to select number of groups and also according to Silhouette and Davies Boulding scores.</p><pre><strong>for</strong> i <strong>in</strong> range(5,11):                kmeans_labels=KMeans(n_clusters=i,random_state=123).fit_predict(df_norm)     <br>print(&quot;Silhouette score for <strong>{}</strong> clusters k-means : <strong>{} </strong>&quot;.format(i,metrics.silhouette_score(df_norm,kmeans_labels, metric=&#39;euclidean&#39;).round(3)))<br>print(&#39;Davies Bouldin Score:&#39;+str(metrics.davies_bouldin_score(df_norm,kmeans_labels).round(3)))</pre><p>After all, when we evaluate Elbow technique, Silhouette and Davies Bouldin scores. The optimal number of clusters is 7 according to K-Means Algorithm. So We have determined 7 as the k values of the K-means model. And now is the time to look at the scatter3d plot to see performance of the models. I think it is insufficient, furthermore…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*MBV2nNlR_luLygOEnhyjvg.png" /></figure><p><strong>2. MiniBatch K-Means</strong></p><p>As you all know, the MiniBatch K-Means is faster than K-Means. However, sometimes it gives a slight different result and after n-cluster is determined 6 cluster according to the metrics above. You can see the scattered plot below.</p><pre>fig = plt.figure(figsize=(12, 7), dpi=80, facecolor=&#39;w&#39;, edgecolor=&#39;k&#39;)<br>ax = plt.axes(projection=&quot;3d&quot;)<br>ax.scatter3D(pca.T[0],pca.T[1],pca.T[2],c=minikm_labels,cmap=&#39;Spectral&#39;)<br>xLabel = ax.set_xlabel(&#39;X&#39;)<br>yLabel = ax.set_ylabel(&#39;Y&#39;)<br>zLabel = ax.set_zlabel(&#39;Z&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*yHS5KwuIo0Bj_ewonoewtA.png" /></figure><p><strong>3. Hierarchical Clustering</strong></p><p>Hierarchical clustering is a clustering technique that aims to create a tree like clustering hierarchy within the data. On this model, to determine the n_clusters, we can able to use a dendogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*fB1e2Os7ZiTTrp_GTp4ZAw.png" /></figure><p>The x-axis contains the samples and y-axis represents the distance between these samples. There are three clusters according to the dendogram. As you seen according to the scatter diagram below.</p><pre>hcluster = AgglomerativeClustering(n_clusters=3, affinity=&#39;euclidean&#39;, linkage=&#39;ward&#39;)<br>hcp=hcluster.fit_predict(df_norm)<br>print(&#39;Silhouette Score for Hieararchial Clustering:&#39;+str(metrics.silhouette_score(df_norm,hcp,metric=&#39;euclidean&#39;)))<br>print(&#39;Davies Bouldin Score:&#39;+str(metrics.davies_bouldin_score(df_norm,hcp)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*aVr2HcsTkNiI6J5hqWXVNQ.png" /></figure><p><strong>4. DBSCAN</strong></p><p>DBSCAN, as the name implies, is a density-based clustering algorithm. Density refers to the proximity of data points in a cluster and it is good for data which contains clusters of a similar density. Firstly, we should choose two parameters, a positive number epsilon and a natural number minPoints. Than we built the model.</p><pre>results=pd.DataFrame(columns=[&#39;Eps&#39;,&#39;Min_Samples&#39;,&#39;Number of Cluster&#39;,&#39;Silhouette Score&#39;])<br>for i in range(1,12):<br>    for j in range(1,12):<br>    dbscan_cluster = DBSCAN(eps=i*0.5, min_samples=j)<br>    clusters=dbscan_cluster.fit_predict(df_norm)<br>    if len(np.unique(clusters))&gt;=2:<br>       results=results.append({&#39;Eps&#39;:i*0.5,&#39;Min_Samples&#39;:j,&#39;Numberof  Cluster&#39;:len(np.unique(clusters)),&#39;SilhouetteScore&#39;:metrics.silhouette_score(df_norm,clusters),&#39;Davies Bouldin Score&#39;:metrics.davies_bouldin_score(df_norm,clusters)},ignore_index=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*W9fE_4bjpsrrpQnRT2hxXA.png" /></figure><p>We have determined 5 cluster. It seems that DBSCAN is not an appropriate method for this dataset.</p><p><strong>5. GMM Algorithm</strong></p><p>Gaussian Mixture Models (GMMs) assume there are a number of Gaussian distributions, and each of them represents a cluster. Therefore a Gaussian Mixture Model tends to group together the data points that belong to a single distribution.</p><p>Firstly, we should determine the n_clusters. The optimal number of clusters is the value that minimizes the Akaike information criterion (AIC) or the Bayesian information criterion (BIC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*AkgRX2vb4p4u7DjxrdVldA.png" /></figure><p>In the present case, when the number of clusters increases, the values ​​of AIC and BIC scores decreases. Which doesn’t give us a suitable solution.</p><p>Let’s look at the performance metrics according to changing parameters and also we are going to calculate the Davies Bouldin score.</p><pre>parameters=[&#39;full&#39;,&#39;tied&#39;,&#39;diag&#39;,&#39;spherical&#39;]<br>n_clusters=np.arange(1,21)<br>results_=pd.DataFrame(columns=[&#39;Covariance Type&#39;,&#39;Number of<br>Cluster&#39;,&#39;Silhouette Score&#39;,&#39;Davies Bouldin Score&#39;])<br>for i in parameters:<br>    for j in n_clusters:       gmm_cluster=GaussianMixture(n_components=j,covariance_type=i,random_state=123)<br>clusters=gmm_cluster.fit_predict(df_norm)<br>if len(np.unique(clusters))&gt;=2:<br>results_=results_.append({&quot;Covariance Type&quot;:i,&#39;Number of Cluster&#39;:j,&quot;Silhouette Score&quot;:metrics.silhouette_score(df_norm,clusters),&#39;Davies Bouldin Score&#39;:metrics.davies_bouldin_score(df_norm,clusters)},ignore_index=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*dJcCQJo13FjCHEYriSK1SQ.png" /></figure><p>We have selected covariance type and number of clusters that are ‘spherical’ and 5 respectively. The parameters have given the Silhouette Score of 0.207.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*oZLrLN2l4C2EhyBJh5gOZg.png" /></figure><p><strong>6. MeanShift</strong></p><p>MeanShift algorithm is another powerful clustering algorithm used in unsupervised learning. Unlike K-means clustering, it doesn’t require any assumptions; hence it is a non-parametric algorithm.</p><pre>est_bandwidth = estimate_bandwidth(df_norm,quantile=.1,n_samples=10000)<br>mean_shift = MeanShift(bandwidth= est_bandwidth, bin_seeding=True).fit(df_norm)<br>labels_unique=np.unique(mean_shift.labels_)<br>n_clusters_=len(labels_unique)<br>print(&quot;Number of estimated clusters : %d&quot; % n_clusters_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*Ct1Szhbeg-UIg12N-tOYWw.png" /></figure><p><strong>Comparision of Results</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*K5bEswh6hhuT0IfvmO_F_A.png" /></figure><p>Finally, We have tried six algorithm. K-Means has the best Silhouette and Davies Bouldin score. For this reason, K-Means Algorithm is more suitable for customer segmentation. Thus we have 7 customer types. Let’s try to understand behaviours or labels of customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAFLyzaNKf0lmv4rLOFSRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*9w4VrpkedaNJDSsNw_uQxg.png" /></figure><p>We have choosen some columns that are significant to identify the clusters.</p><p>Cluster 0<strong> </strong>: The highest purchase frequency which tend to pay in installment, that is higher credit limit and long duration customers.</p><p>Cluster 1 : Pretty low balance and purchase frequency. They rarely use credit card and also they have lower credit limit.</p><p>Cluster 2 : This group is having the highest amount of customers and lowest usage of cards. Inactive customers, also long duration customers.</p><p>Cluster 3 : High tendency of payment installment, higher purchase frequency and their tenure time is above avarage.</p><p>Cluster 4 : The highest balance amount but purchase frequency is not that good. Tend to cash in advance, higher credit limit than others. They don’t like spending money.</p><p>Cluster 5 : Second highest purchase frequency and also higher tendency payment in installment. They are long duration customers.</p><p>Cluster 6 : The least quantity of customer is in this group which are below avarage of purchase frequency and a shortly duration customers.</p><p><strong>Summary</strong></p><p>Firstly, we have started with data preprocessing. Than, we applied clustering algorithms. After comparing these clustering models than, we decided to use K-Means as the model. Than, we divided the data into seven clusters, because seven clusters can be easily used to determine the behaviours of customers. However, each of the clusters have their own characteristics.</p><p>Thank you for reading. You can visit my GitHub account.</p><p><a href="https://github.com/muhammetbektas/Unsupervised-Learning/blob/master/Segmentation_of_Credit_Card_Users.ipynb">https://github.com/muhammetbektas/Unsupervised-Learning/blob/master/Segmentation_of_Credit_Card_Users_in_Python.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2e021035a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Makine Öğrenmesi ile Müşteri Kaybı Analizi]]></title>
            <link>https://medium.com/@mbektas/makine-%C3%B6%C4%9Frenmesi-ile-m%C3%BC%C5%9Fteri-kayb%C4%B1-analizi-a8f047e64708?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f047e64708</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 15:11:45 GMT</pubDate>
            <atom:updated>2020-04-03T19:20:35.499Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Lojistik Regresyon ve K-NN Algoritmasını Kullanarak Müşterilerin Sınıflandırılması</blockquote><p>Makine öğrenmesi tekniklerinden gözetimli öğrenme (supervised learning) ikiye ayrılır. Bunlar regresyon ve sınıflandırmadır. Regresyon’ da amaç hedef değişkenin alacağı değeri tahmin etmek iken, sınıflandırmada ki temel amaç ise gözlemin sınıf etiketini (class label) tahmin etmek, daha önceden belirlenmiş sınıf etiketlerine uygun olarak, gözlemin yer alacağı sınıfı belirlemektir. Sınıflandırma iki seçenek arasından olabileceği gibi ikiden fazla seçenek arasından da olabilir. Bu çalışmada lojistik regresyon ve “k-Nearest Neighbours” algoritmasını kullanarak bir sınıflandırma problemini çözeceğiz. Bir telekom firmasındaki müşterileri ayrılma ihtimallerine göre sınıflandıracağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*S0ldr5ClUKFEBvVXW3XMLQ.png" /></figure><p>Müşteri kaybı en basit tanımıyla “rekabet nedeniyle müşterilerin firmayı tercih etmekten vazgeçmeleri” anlamına gelmektedir. Müşteri kaybı kavramı, banka ve telekomünikasyon firmaları gibi hizmet işletmelerinin, müşterilerinin sadakatlerindeki değişimlerin ve bu değişimlerin sonucunda müşterinin firmayı tercihten vazgeçmelerinin artmasıyla daha fazla gündeme gelmiştir. Müşteri kaybının yüksek olmasında, firmaların birbirinden çok farklı hizmetler ve çok çeşitli kampanyalar oluşturarak rakip firmada tatminsizlik yaşayan müşteriyi cezbetme potansiyelinin yüksek olması çok etkilidir.</p><ol><li>VERİ KÜMESİNE GENEL BİR BAKIŞ</li></ol><p>Veri kümesi 7043 satır ve 21 sütundan oluşmaktadır. Hedef değişkenimiz “Churn” sütunudur. Diğer sütunlar müşterilerin kayıtlı olduğu “Device Protection”, “Online Security” gibi ve ya kontrat uzunluğu, müşterinin firmadan ne kadar zamandır hizmet aldığı ve ücretlendirmeler vs. gibi çok sayıda bilgi bulunmaktadır. Veri kümesine <a href="https://www.kaggle.com/blastchar/telco-customer-churn">buradan</a> ulaşabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*pa0DanTWQPuQGtFHWFqBHA.png" /></figure><p>1.2 Değişkenler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*sUhcs87-HHziWPeYEIrXjA.png" /></figure><p>2. VERİ TEMİZLEME</p><p>Veri kümemizde boş değer gözükmemektedir. Ancak “TotalCharges” sütunu “int” tipinde olması gerekirken burada “object” tipinde bulunmaktadır. Dönüşümünü yapıp ortaya çıkan boş değerleri dolduracağız.</p><pre># Although,TotalCharges should be numerical data type,but it is object type here. Let&#39;s convert.<br>telco.TotalCharges=pd.to_numeric(telco.TotalCharges,errors=&#39;coerce&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*VvjvH_QAh3cz3WzbpDuwmQ.png" /></figure><p>Dönüşümü yaptıktan sonra veri kümemizde 11 tane “null” değer ortaya çıktı. Şimdi bu değerleri dolduralım ve kullanmadığımız “customerID” sütununu kaldıralım.</p><pre># Also,we can replace null values with zero and  drop the customerID column.<br>telco=telco.fillna(0)<br>telco=telco.drop([&#39;customerID&#39;],axis=1)</pre><p>3. KEŞİFSEL VERİ ANALİZİ</p><p>Buradaki amacımız hedef değişkenimizi (Churn) etkileyen değişkenlerin, hedef değişkenimiz ile olan ilişkilerini anlamaya çalışmaktır. Veri kümemizde 1869 adet ayrılan müşteri bulunmaktadır. Bu ise ayrılma oranı olarak yaklaşık olarak %26 ya tekabül etmektedir. Hadi incelemeye başlayalım.</p><p>İlk olarak cinsiyet değişkeni olan “Gender” sütununu inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*C7DA-LGe11yijwZuqdg6tw.png" /></figure><p>Cinsiyet, ayrılma ihtimalini tahmin etmek için iyi bir değişken değil. Cinsiyete göre dağılımlar neredeyse aynı sayıdadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*p8JChEVhb1QhsKW3U67Vog.png" /></figure><p>Daha sonra “Partner” değişkenine bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*XtsbIYzuCu55SdX0D4ND6w.png" /></figure><p>Müşterinin evli olup olmaması ayrılma ihtimali üzerinde kısmen de olsa bir etkiye sahiptir.</p><p>Daha sonra “Phone Service — Streaming TV — MultipleLines” gibi değişkenleri inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*cztV0_jOOhxkRbXx1jmHCg.png" /></figure><p>“PhoneService” ve “ MultipleLines” değişkenleri için bu hizmetleri alıp almamasının, müşterinin ayrılma ihtimali üzerine bir etkisi görünmemektedir.</p><p>“ StreamingTv” için ise durum, internet servisi olmayanlar için ayrılma oranı düşüktür.</p><p>Sırada “OnlineSecurity” ve “TechSupport” değişkenleri var.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*SNeUxA3LIjtrJfdu7xm_-g.png" /></figure><p>Bu iki servise kayıt olmayanlar ayrılma eğilimine daha çok sahiptir.</p><p>“OnlineSecurity” ve “TechSupport” için ayrılma oranı bu servise kayıt olmayanlar için %42, olanlar için ise yaklaşık %15 dir.</p><p>Şimdi de “Tenure” değişkenine bakalım. Bu değişken müşterilerin firmadan ne kadar zamandır hizmet aldığını ifade eder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*j_eSyMkt3HBPac0AAA8iog.png" /></figure><p>Ayrılmayan müşteriler ortalama 20 ay daha fazla firmadan hizmet almaktadır.</p><p>Daha sonra “MonthlyCharges” değişkenine bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*XmgUz8N3ux0_8wh_cQ3uCw.png" /></figure><pre>print(&#39;Average Monthly Fee of Churned&#39;)<br>print(round(telco[telco.Churn==&#39;Yes&#39;][&#39;MonthlyCharges&#39;].mean(),2),&#39;\nAverage Monthly Fee of Not Churned&#39;)<br>print(round(telco[telco.Churn==&#39;No&#39;][&#39;MonthlyCharges&#39;].mean(),2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*ePgICLozLpdzEv1Up81ysA.png" /></figure><p>Ayrılan müşteriler ayrılmayanlara göre %20 oranında daha fazla ücret ödemektedir.</p><p>Şimdi bu “SeniorCitizen-Tenure-MonthlyCharges” üç değişkeni inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*X1LH4hN5mhCQ1H5jeOaEMw.png" /></figure><p>Yaşlılar tüm müşterilerim %16 sını oluşturmaktadır. Yaşlı insanlarda ayrılma oranı %42 iken , yaşlı olmayan kesimde bu oran %23 tür.</p><p>Sırada “Contract-Internet Service” bu iki değişken var.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*qjB7gmPl8xFYF6Ib8Jlhvg.png" /></figure><p>Kısa süreli kontrat yapanlarda ayrılma oranı oldukça yüksektir. Fiber hizmeti aydan aya kontrat yapan bir müşterinin ayrılması daha muhtemel gözükmektedir. Uzun dönem kontrat yapanlarda ise ayrılma oranı düşüktür.</p><p>4. MODELLERİN KURULUMU</p><p>Veri bilimci olarak en iyi tahmini yapan modeli oluşturmaya çalışmalısınız. 2. bölümde verimizi temizlemiştik. Artık temizlediğimiz, kullanmak istediğimiz özellikleri seçtiğimiz verimiz hazır. Ancak şemanın temel noktası olan model nasıl olacak? Şimdi bu modeli nasıl oluşturacağımıza bakalım.</p><p>Belirli makine öğrenimi algoritmaları kullanılarak bir veri üzerinde eğitilmiş nesneye model diyoruz. Modeli oluştururken kullandığımız veri kümesini ise eğitim veri kümesi (training set) olarak adlandırıyoruz. Bu veri kümesi sınıflandırılmış verilere sahip olacaktır. Sınıflandırma algoritması eğitilirken bu veri kümesinin özelliklerine ve sınıflandırmalara göre ortaya bir model koyacaktır.</p><p>İlk olarak kategorik değişkenlere “One-Hot Encoder” yöntemini kullarak 1 ve 0 değerleri atayalım.</p><pre>telco.Churn=telco.Churn.replace({&quot;Yes&quot;:1, &quot;No&quot;:0})<br>telco2=pd.concat([telco,pd.get_dummies(telco[categorical])],axis=1).drop(telco[categorical],axis=1)</pre><p>Daha sonra verimizde sınıf dengesizliği olup olmadığını kontrol edelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*-mqqY7mDuadZg-GXPGWeGg.png" /></figure><p>Verimizin dengesiz olduğunu söyleyebiliriz. Sınıf dengesizliği durumunda daha az veriye sahip sınıfın verisini tekrar yerine koyma yöntemi ile yeniden örneklem seçerek veriyi dengeli hale getirebiliriz.</p><p>Şimdi “GridSearCV” yöntemini de kullanarak lojistik regresyon ile sınıflandırma yapalım.</p><pre>from sklearn.model_selection import GridSearchCV<br>grid_cv = GridSearchCV(estimator=logistic,<br>                       param_grid = parameters,<br>                       cv = 10)<br>grid_cv.fit(X, y)<br>print(&quot;The best parameters : &quot;, grid_cv.best_params_)<br>print(&quot;The best score         : &quot;, grid_cv.best_score_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*wSDohd-eFN4KTkD-FsqoYg.png" /></figure><p>Lojistik regresyon yöntemini kullanarak 4 farklı model kurduk. İlk modelimiz örneklem artışı yapmadan kurduğumuz modelimizdir.</p><p>2. modelimizi ise daha az veriye sahip sınıfa ait verileri kopyalarak sayısını artırmak suretiyle oluşturduk. Bunun için “scikit-learn” kütüphanesinin utils modülünde yer alan resample fonksiyonunu kullandık.</p><p>3. modelimizi ise sentetik örneklem üretme tekniklerinden “SMOTE” algoritmasına dayanarak oluşturduk. “SMOTE” bir örneklem artırma algoritması. Daha önceki örneklem artırma metodunda az olan verinin birebir kopyasını oluşturuyorduk. “SMOTE” ise bazı değişkenleri değiştirerek yeni veriler üretmektedir.</p><p>4. modelimizi ise yine sentetik örneklem üretme tekniklerinden “ADASYN” algoritmasına dayanarak oluşturduk. “ADASYN” aslında “SMOTE” algoritmasının geliştirilmiş halidir. “SMOTE” ile sentetik örnek, veri ile en yakın komşusu arasındaki doğru üzerinde oluşturulurken, “ADASYN” ile üretilen örnekler bu doğrunun çok yakınında üretilmekte ve böylece daha gerçekçi olması sağlanmaktadır.</p><p>Aşağıda modele ait performans değerlerini görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*NGuh2X7WMiknqBO69NBGPg.png" /></figure><p>5. modelimizi ise “K-Nearest Neighbour” algoritmasına dayanarak oluşturduk. En yakın komşu k-NN algoritması tartışmasız en kolay makine öğrenimi algoritmasıdır. Modeli oluşturmak için sadece bir eğitim veri kümesi yeterlidir. Model tahmin yeni bir veri noktası için tahmin yapacağız zaman, bu yeni verinin, eğitim kümesi içerisindeki en yakın komşu yada komşularını bulur ver bu komşuların sınıfına göre bir sınıflandırma yapar. “GridSearchCV” yöntemini de kullanarak modelimizi oluşturduk.</p><pre>from sklearn.model_selection import GridSearchCV<br>from sklearn.model_selection import cross_val_score<br>Knn=KNeighborsClassifier()<br>k_range = list(range(1,25))<br>parameter = dict(n_neighbors=k_range)<br>grid = GridSearchCV(Knn, parameter, cv=10, scoring=&#39;roc_auc&#39;)<br>Grds = grid.fit(X,y)<br>print(&#39;The best parameters:&#39;, Grds.best_estimator_)<br>print(&#39;The best score:&#39;, Grds.best_score_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*I4O9TwOPK5qfkp2QNkPhWg.png" /></figure><pre>Grds=Grds.best_estimator_.fit(X_train, y_train)<br># predictions for test set<br>y_preds = Grds.predict(X_test)<br>y_probs=Grds.predict_proba(X_test)[:,1]<br>metric(y_test,y_preds)<br>print(&quot;AUC Score      : {}&quot;.format(roc_auc_score(y_test,y_probs)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*nBDemWUdphd7KyUYH0ajzQ.png" /></figure><p>5. DEĞERLENDİRME</p><p>“Accuracy Score” değeri sınıf dengesizliği bulunan veri kümeleri için geçerli bir performans ölçüm metriği değildir. Hedef veri kümesinin dağılımı dengeli olduğu zaman doğruluk değerini kullanabiliriz. Bu veri kümesi için bu metriği kullanmak doğru olmaz.</p><p>Modellerimizin performansını ölçerken “F1 Score” değerlerine bakmak da oldukça önemlidir. Hassasiyet ve duyarlılık değerlerinin ikisine birden bakma çok pratik olmayacağından, iki metriği de içeren “F1 Score” u kullanmaktayız. “F1 Score” aynı zamanda simetrik dağılıma sahip olmayan veri kümeleri kullanılırken model performansını ölçmede etkilidir.</p><p>Sınıflandırma problemlerinde “ROC” eğrisine güvenebiliriz. Özellikle de sınıf dengesizliği olan veri kümelerinde en önemli performans ölçüm araçlarından biridir. “ROC” eğrisi ikili sınıflandırma için tasarlanmış bir araçtır. Yatay eksende yanlış pozitif oranı , dikey eksende ise doğru pozitif oranı yer almaktadır. Eğrinin altında kalan alana “AUC” (Area Under Curve) adı verilmektedir ve bu değer modelin bir özeti olarak düşünülebilir.</p><p>Şunu söyleyebiliriz ki, “AUC Score” lara baktığımızda sınıflandırma için en iyi tahmin yapan model “ADASYN” algoritması kullanarak oluşturulan regresyon modelidir.</p><p>Zaman ayırdığınız için teşekkürler.</p><p>Çok daha fazla detaya bakmak ve kod satırlarını incelemek isterseniz GitHub hesabımı ziyaret edebilirsiniz.</p><p><a href="https://github.com/muhammetbektas/Classification-Projects/blob/master/Classification_Project%20(4).ipynb">https://github.com/muhammetbektas/Classification-Projects/blob/master/Classification_Project%20(4).ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f047e64708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aykırı Değerler’in Tespiti ve Bu Değerler ile Mücadele Yöntemleri]]></title>
            <link>https://medium.com/@mbektas/ayk%C4%B1r%C4%B1-de%C4%9Ferlerin-tespiti-ve-bu-de%C4%9Ferler-ile-m%C3%BCcadele-y%C3%B6ntemleri-4f0cf76737d1?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f0cf76737d1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 14:29:39 GMT</pubDate>
            <atom:updated>2020-04-03T19:25:39.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Aykırı Değerlerin Tespiti ve Bu Değerler ile Mücadele Yöntemleri</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*iC9FwKwzDSv2jgJc" /></figure><p>Bir veri bilimi projesi üzerinde çalışırken araştırdığımız şey nedir? Keşifsel veri analizi aşamasında en önemli bölüm hangisidir? Bu aşamada yapılmadığı takdirde ilerleyen aşamalarda makine öğrenme modellerini etkileyebilecek belirli bazı şeyler vardır. Bunlardan birisi aykırı değerlerin tespitidir. Verinin tanımlayıcı ölçülerini yanıltırlar. Şimdi, ilk olarak aykırı değerlerin tespitinden başlayalım.</p><p>Bu çalışmamızda “kaggle” da bulunan “video game sales” veri kümesini kullanacağız.</p><p>1. Aykırı Değerlerin Görselleştirilmesi</p><p>Verilerdeki aykırı değerleri görselleştirmemize yardımcı olan bazı yararlı grafikler vardır. En çok bilinen grafik ise kutu grafiğidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Rpacv0d3Bx_yhtR1BEd_7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*csac2e9bwOrI7GGoc_WU4Q.png" /></figure><p>Görselleştirme için kullanılan bir başka grafik ise histogramdır. Yukarıda gördüğünüz grafikler “Python” ın “seaborn” kütüphanesi kullanılarak çizdirilmiştir. “NA_Sales” sütununda çok fazla aykırı değer bulunmaktadır. Kutu grafinde, max. nokta üzerinde bulunan noktalar aykırı değerleri göstermektedir.</p><p>İlk olarak histogram grafiğine baktığımızda “dirsek” oluşumunu görebilmekteyiz. Başka bir deyişle, parabolik bir azalma yakaladığımızı söylüyoruz. Böyle durumlarda, “ok” un sağ tarafını kesebiliriz. Bu değerleri aykırı değerler olarak kabul edebiliriz.</p><pre>ax[&#39;whiskers&#39;][1].get_ydata()<br>array([0.8725, 1.68  ])</pre><p>Y ekseni üzerinde ki bu değerler üst bıyığa ait başlangıç ve bitiş noktalarıdır. İkinci değer kutu grafiğinin maksimum noktasıdır. Aşağıda maksimum noktadan sonraki değerlerin dağılımını detaylı bir şekilde görebilmekteyiz. Bir noktadan sonra seyreklikler başlamaktadır.</p><pre>df.NA_Sales.hist(range = (1.68,5))<br>plt.xlabel(&#39;NA_Sales&#39;,color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*55acn7s5FuvBjjA4pFTbJg.png" /></figure><p>İkinci olarak, eğer histoğramda bir azalma göremezsek ve dirsek oluşumunu yakalayamazsak, aykırı değerlerin tespitinde aşağıda görüldüğü üzere üç sigma kuralını kullanırız.</p><pre>m=df.NA_Sales.mean()<br>std=df.NA_Sales.std()<br>plt.hist(df.NA_Sales)<br>plt.axvline(x=m+3*std,color=&#39;red&#39;)<br>plt.axvline(x=m-3*std,color=&#39;red&#39;)<br>plt.xlabel(&#39;NA_Sales&#39;,color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*9oW-IGnbkktG9FmXQKI6Vg.png" /></figure><p>Kırmızı çizgilerin sağındaki ve solundaki değerleri, aykırı değerler olarak değerlendiririz. Bu kırmızı çizgiler üç sigma kuralına göre çizdirilmiştir.</p><p>2. Aykırı Değerlerin Tespitinde Kullanılan İstatistiksel Yöntemler</p><p>2.1. Z-score</p><p>Bir değişkende aykırı değerleri saptama yöntemlerinden birisi “z-score” dur. Z-score ilk önce verileri ölçeklendirir, böylece ortalaması 0 ve standart sapması 1 olur ve daha sonra bir değerin ortalamanın ne kadar uzağında olduğunu ölçer. Bununla birlikte, bir değerin aykırı olduğunu söylemek için, z-score için bir eşik belirlememiz gerekir, bu sayede bu eşiğin üzerindeki skorların aykırı olduğu söylenir. Çoğu durumda 3 veya -3 sigma eşiği kullanılır. Z-score değeri sırasıyla 3 veya -3&#39;ten büyük veya küçükse, bu veri noktası aykırı değer olarak belirlenecektir.</p><pre>from scipy.stats import zscorez_scores = zscore(df[&quot;NA_Sales&quot;])<br>for threshold in range(1,4):<br>    print(&quot;Threshold value: {}&quot;.format(threshold))<br>    print(&quot;Number of outliers: {}&quot;.format(len((np.where(z_scores &gt; threshold)[0]))))<br>    print(&#39;-----------&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*IEe15oORMvdPfugV-yzfkw.png" /></figure><p>Görüldüğü üzere eşik değeri artarken, aykırı değerler azalmaktadır.</p><p>2.2. Tukey’s Yöntemi</p><p>Bu yöntem Çeyrekler Arası Aralık (ÇAA) yöntemi olarak da bilinir. Daha önce gösterdiğimiz gibi, ÇAA birinci ve üçüncü çeyrekler arasındaki aralıktır. Bu yöntem ÇAA’ nın 1.5 katı dışında olan tüm değerleri aykırı değerler olarak değerlendirir. Ancak, aralığı değiştirebiliriz ve 1.5 yerine başka bir eşik değeri ayarlayabiliriz.</p><pre>q75, q25 = np.percentile(df.NA_Sales, [75 ,25])<br>IQR = q75 - q25<br>threshold_values=pd.DataFrame(columns={&#39;threshold&#39;,&#39;outliers_number&#39;})<br>for threshold in np.arange(1,4,0.5):<br>    min_value = q25 - (IQR*threshold)<br>    max_value = q75 + (IQR*threshold)<br>    outliers_number = len((np.where((df.NA_Sales &gt; max_value)| (df.NA_Sales &lt; min_value))[0]))<br>    threshold_values = threshold_values.append({&#39;threshold&#39;: threshold,<br>                                                &#39;outliers_number&#39;: outliers_number},ignore_index=True)<br>threshold_values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*7ajFqJcmj0l6dXuzYUgkZA.png" /></figure><p>3. Aykırı Değerlerin Düzeltilmesi</p><p>Aykırı değerleri tespit ettikten sonra, analizimizin güvenilirliğini etkilememeleri için bunları ele almamız gerekir.</p><p>-Aykırı değerleri veri kümemizden çıkarabiliriz.</p><p>-Aykırı değerlere yeni değerler atayarak sınırlayabiliriz.</p><p>-Onları analizimiz için zararsız bir değere dönüştürürüz.</p><p>3.1. Aykırı Değerlerin Sınırlandırılması</p><p>Aykırı değerlerin temel sorunu büyüklükleridir. Aykırı değerleri sınırlandırabilirsek, analizimiz üzerindeki etkileri sınırlı olacaktır. Aykırı değerleri sınırlandırmanın yaygın bir yoluna “winsorization” denir.</p><pre>from scipy.stats.mstats import winsorize<br>winsorize_NA_Sales = winsorize(df.NA_Sales,(0,0.1))<br>plt.boxplot(winsorize_NA_Sales)<br>plt.xlabel(&#39;Winsorize_NA_Sales&#39;,color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*EjPLgExorOydu40dj_D_-g.png" /></figure><p>“Winsorization” u uygularken alt ve üst limitleri kendimiz belirleyebiliriz. Herhangi bir pratik yöntemi yoktur. Değerleri çok fazla kırpmak iyi değildir, fazla bilgi kaybına sebep olabilir. “Winsorization” ı % 5 civarında tutmalıyız çünkü bu oranı çok arttırırsak bazı yan etkilere neden olabilir ve bu bizi yanlış sonuçlara götürebilir. Ama belirli bir limit de bulunmamaktadır. Biz burada üst sınırdan %10 oranında keserek değerleri maksimum noktaya sınırladık.</p><pre>plt.hist(winsorize_NA_Sales)<br>plt.axvline(x=winsorize_NA_Sales.mean()+3*winsorize_NA_Sales.std(),color=&#39;red&#39;)<br>plt.axvline(x=winsorize_NA_Sales.mean()-3*winsorize_NA_Sales.std(),color=&#39;red&#39;)<br>plt.xlabel(&#39;Winsorize_NA_Sales&#39;,color=&#39;b&#39;)<br>plt.tight_layout<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*b39Lc2gzNQ1VvVHuMyRb3A.png" /></figure><p>Yukarıda gördüğünüz üzere artık grafiğimizde aykırı değerler bulunmamaktadır.</p><p>3.2. Aykırı Değerleri Dönüştürme</p><p>Aykırı değerlerle başa çıkmanın başka bir yaygın yolu da değerlerin dönüşümüdür. Dönüşüm, yalnızca aykırı değerlerde değil, aynı zamanda normal olmayan veya normale yakın olmayan dağılımlarda da bize yardımcı olur.</p><pre>plt.hist(np.log(df.NA_Sales+0.1))<br>plt.axvline(x=np.log(df.NA_Sales+0.1).mean()+3*np.log(df.NA_Sales+0.1).std(),color=&#39;red&#39;)<br>plt.axvline(x=np.log(df.NA_Sales+0.1).mean()-3*np.log(df.NA_Sales+0.1).std(),color=&#39;red&#39;)<br>plt.xlabel(&#39;Log_NA_Sales&#39;,color=&#39;b&#39;)<br>plt.tight_layout<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*jSEuEIcqdUHnCWLV7L920Q.png" /></figure><p>Gördüğümüz gibi, “np.log” dönüşümü yaptığımız “NA_Sales” değişkeni, normal bir dağılıma daha yakın bir şekilde dağıldı ve bu, gelecekte bazı istatistiksel teknikleri uygulamada bize yardımcı olacak.</p><p>4. Sonuç<br>Bu çalışma boyunca, veri analizi aşamasında, bazı olağan dışı verilerle, yani aykırı değerlerle nasıl karşılaşılabileceğini gördük. Bu aykırı değerleri tespit etmek ve kaldırmak için kullanılabilecek teknikleri öğrendik.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f0cf76737d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outliers is that Unpreferable Values]]></title>
            <link>https://medium.com/@mbektas/outliers-is-that-unpreferable-values-5b1911741491?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b1911741491</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 12:23:58 GMT</pubDate>
            <atom:updated>2020-03-03T14:04:41.064Z</atom:updated>
            <content:encoded><![CDATA[<h3>Outliers are that Unpreferable Values</h3><p>How to detect and struggle with the Outliers ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*Yf5U1F4FFeV34vL5" /></figure><p>While working on a Data Science project, what is it, that you look for? What is the most important part of the EDA phase? There are certain things which, if are not done in the EDA phase, can affect further statistical/Machine Learning modelling. One of them is detecting “Outliers”. They misguide description metrics of data. Now, the first step is detection of the outliers. Let’s start.</p><p>We are going to use “video game sales” dataset on kaggle for this study.</p><ol><li>Visualization of the Outliers</li></ol><p>There are some useful plots that help us visualization outliers in the data. One of the most known visualization plot for outliers is the box plot about this topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*XZhoWgX3UgCZalNKK1aAPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*csac2e9bwOrI7GGoc_WU4Q.png" /></figure><p>Another useful visualization plot is histogram. The boxplot and histogram you have seen above were made through “Seaborn”. Seaborn is a significant visualization library of Python. There are lots of outliers at NA_Sales( Sales in North America) column. You can see outliers above max. point on box plot.</p><p>First, when we look at the histogram, we can see the formation of an “elbow”. Right? In other words, i mean that a parabolic decrease is seen. In such circumstances, we can trim right side of the histogram. The values on right of the arrow are potentially outliers.</p><pre>ax[&#39;whiskers&#39;][1].get_ydata()<br>array([0.8725, 1.68  ])</pre><p>These values on y-axis belong to the upper whisker. The second value on y-axis is max. point of the boxplot. As you can see below, we can see after the max. point in detail and there are rarities in values after one point.</p><pre>df.NA_Sales.hist(range = (1.68,5))<br>plt.xlabel(&#39;NA_Sales&#39;,color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*dbPhDev_OWl0tA1F9-7tug.png" /></figure><p>Second, If we can not see the decrease in the histogram, we use three-sigma rule. As you can see below.</p><pre>m=df.NA_Sales.mean()<br>std=df.NA_Sales.std()<br>plt.hist(df.NA_Sales)<br>plt.axvline(x=m+3*std,color=&#39;red&#39;)<br>plt.axvline(x=m-3*std,color=&#39;red&#39;)<br>plt.xlabel(&#39;NA_Sales&#39;,color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*6OeeqbnIc2-qXUoGH06cUw.png" /></figure><p>The values on the left and right of the redlines are potentially outliers. The redlines have drawn according to three-sigma limits.</p><p>2. Statistical Methods in Detection of the Outliers</p><p>2.1. Z-score</p><p>Z-score is finding the distribution of data where mean is 0 and standard deviation is 1 i.e. normal distribution. While calculating the z-score, we re-scale and center the data and look for data points which are too far from zero. However, to say that a value is outlier, we need to set a threshold for the z-score so that the scores above this threshold are said to be outlier. In most of the cases a threshold of 3 or -3 is used. If the z-score value is greater than or less than 3 or -3 respectively, that data point will be identified as outlier.</p><pre>from scipy.stats import zscore</pre><pre>z_scores = zscore(df[&quot;NA_Sales&quot;])<br>for threshold in range(1,4):<br>    print(&quot;Threshold value: {}&quot;.format(threshold))<br>    print(&quot;Number of outliers: {}&quot;.format(len((np.where(z_scores &gt; threshold)[0]))))<br>    print(&#39;-----------&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*JWJDeUJtZtR9t9AE-Gf4GQ.png" /></figure><p>As we can see, as the threshold of z-scores increase and the outliers decrease.</p><p>2.2. Tukey’s Method</p><p>The interquartile range (IQR), also called the midspread or middle 50%, or technically H-spread, is a measure of statistical dispersion, being equal to the difference between 75th and 25th percentiles, or between upper and lower quartiles, IQR = Q3 − Q1.This method evaluates all values ​​other than 1.5 times of the IQR as outliers. However, we can change the range and set another threshold value instead of 1.5.</p><pre>q75, q25 = np.percentile(df.NA_Sales, [75 ,25])<br>IQR = q75 - q25<br>threshold_values=pd.DataFrame(columns={&#39;threshold&#39;,&#39;outliers_number&#39;})<br>for threshold in np.arange(1,4,0.5):<br>    min_value = q25 - (IQR*threshold)<br>    max_value = q75 + (IQR*threshold)<br>    outliers_number = len((np.where((df.NA_Sales &gt; max_value)| (df.NA_Sales &lt; min_value))[0]))<br>    threshold_values = threshold_values.append({&#39;threshold&#39;: threshold,<br>                                                &#39;outliers_number&#39;: outliers_number},ignore_index=True)<br>threshold_values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*C8ZNR8bensFLCiJfjXExIw.png" /></figure><p>3. How to Correct the Outliers</p><p>After detecting outliers, we need to get rid of them so that they do not affect the reliability of our analysis.</p><p>-We can extract the outliers from our dataset.</p><p>-We can limit the outliers by assigning new values.</p><p>-We can tranformation them into harmless values for our analysis.</p><p>3.1. Limitation of the Outliers</p><p>The main problem of outliers is their size. If we can limit outliers, the effects on our analysis will be limited. A common way to limit outliers is called “winsorization”.</p><pre>from scipy.stats.mstats import winsorize<br>winsorize_NA_Sales = winsorize(df.NA_Sales,(0,0.1))<br>plt.boxplot(winsorize_NA_Sales)<br>plt.xlabel(&#39;Winsorize_NA_Sales&#39;,color=&#39;b&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*PyW-tNbkxYMmtIN7DoddNQ.png" /></figure><p>When we apply the winsorization,we can arrange the upper and lower limits. For the limits doesn’t have any practical formula. We should keep the winsorization only about 5% because it might cause some side effects if we increase that ratio too much. Cutting too much information may not be the best idea but there is no obvious limit for this. We have kept the winsorization %10.</p><pre>plt.hist(winsorize_NA_Sales)<br>plt.axvline(x=winsorize_NA_Sales.mean()+3*winsorize_NA_Sales.std(),color=&#39;red&#39;)<br>plt.axvline(x=winsorize_NA_Sales.mean()-3*winsorize_NA_Sales.std(),color=&#39;red&#39;)<br>plt.xlabel(&#39;Winsorize_NA_Sales&#39;,color=&#39;b&#39;)<br>plt.tight_layout<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*fI8vL4ZNDk-3_N_cf1ttNw.png" /></figure><p>As you can see above, the box chart and histogram has not outliers no longer!</p><p>3.2. Transforming of the Outliers</p><p>Another common way to deal with outliers is transformation of the variable. The transformation helps us not only in outliers, but also in abnormal or near-normal distributions.</p><pre>plt.hist(np.log(df.NA_Sales+0.1))<br>plt.axvline(x=np.log(df.NA_Sales+0.1).mean()+3*np.log(df.NA_Sales+0.1).std(),color=&#39;red&#39;)<br>plt.axvline(x=np.log(df.NA_Sales+0.1).mean()-3*np.log(df.NA_Sales+0.1).std(),color=&#39;red&#39;)<br>plt.xlabel(&#39;Log_NA_Sales&#39;,color=&#39;b&#39;)<br>plt.tight_layout<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*14GtzmqA6sXcnsy-Kx5laQ.png" /></figure><p>As we can see, the log transformation variable has been distributed closer to a normal distribution, and this will help us to implement some statistical techniques in the future.</p><p>4. Conclusion</p><p>Throughout this study we saw how in data analysis phase one can encounter with some unusual data i.e outlier. We learned about techniques which can be used to detect and remove those outliers.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b1911741491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EV ALETLERİ İÇİN ELEKTRİK TÜKETİM TAHMİNİ]]></title>
            <link>https://medium.com/@mbektas/ev-aletleri%CC%87-i%CC%87%C3%A7i%CC%87n-elektri%CC%87k-t%C3%BCketi%CC%87m-tahmi%CC%87ni%CC%87-205ddcaf4298?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/205ddcaf4298</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ordinary-least-square]]></category>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 12:25:15 GMT</pubDate>
            <atom:updated>2022-07-27T11:52:04.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ev Aletlerinde ki Elektrik Tüketiminin Tahmin Edilmesi</h3><h4>Lineer Regresyon ile Evimizde Bulunan Cihazların Elektrik Tüketimlerinin Tahmin Edilmesi</h4><p>Veri bilimi projeleri birbirini takip eden aşamalardan oluşmaktadır. Bunlardan ilki ve en önemli adımı keşifsel veri analizi kısmıdır. İkinci adım ise makine öğrenmesi modellerinin kurulmasıdır. Lineer regresyon, bir veya daha fazla gözlenen özellikler ile hedef değişken arasındaki ilişkiyi modeller. Modelimizi, hedef değişkeni anlamlı şekilde etkileyen özelliklerle beslememiz modelin tahmin performansını etkileyecektir. Bu yüzden veri analizi kısmı önemlidir. Elimizdeki verilere dayanarak, bizi istediğimiz sonuca ulaştıracak bir model türetmeye çalışacağız. Ayrıca “Python ile Keşifsel Veri Analizi” isimli yazıya <a href="https://medium.com/@mbektas/python-i%CC%87le-ke%C5%9Fifsel-veri-analizi-d8a636102954">buradan</a> ulaşabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*r0iad88YkC-I70iljv-qJg.png" /></figure><p>Küresel belirsizliğin yaşandığı bu zamanlarda, özellikle gelişmekte olan ülkelerde hem ekonomik hem sosyal ilerlemeyi desteklemek ve daha kaliteli bir yaşam kalitesi oluşturmak için enerjiye olan ihtiyaç giderek artmaktadır. Ancak günümüzde özellikle gelişmekte olan ülkelerde kesintilerin olduğu pek çok yer vardır. Bu kesintiler, en başta ev aletleri tarafından tüketilen aşırı yük nedeniyle oluşmaktadır. Bu projede evde bulunan sensörler aracılığıyla toplanan parametreler ile evdeki cihazlara ait elektrik kullanımını analiz edeceğiz. Model oluşturmada kullanacağımız veri kümesi 4.5 ay boyunca 10 dk da bir toplanan verilerden oluşmaktadır.</p><p>Sıcaklık, nem, basıç gibi faktörleri kullanarak bir eve ait cihazların tükettiği enerjiyi tahmin edeceğiz. Bunu başarmak için lineer regresyon algoritmalarını kullanarak denetimli bir öğrenme modeli geliştirmemiz gerekmektedir.</p><p>2. VERİ KÜMESİNE GENEL BİR BAKIŞ</p><p>2.1. Veri Kümesi<br>Kullanılan veri kümesi açık kaynak bir veri kümesidir. <a href="https://archive.ics.uci.edu/ml/datasets/Appliances+energy+predictionn">Buradan</a> ulaşabilirsiniz. Veri kümemiz 29 sütün ve 19735 satırdan oluşmaktadır. “ Appliances” sütunu bizim hedef değişkenimizdir ve 10 dk da bir hesaplanan elektrik tüketimini belirtmektedir. Diğer sıcaklık, nem gibi değerler ise evde bulunan oturma odası, banyo, mutfak gibi alanlara ait ölçüm değerlerini içermektedir. Tüm bağımsız değişkenler “float64” tipinde ve süreklidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ReRGDAxTQRZGhECIj2OADg.png" /></figure><p>2.2. Değişkenler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Mwwe3UIg4gf18jazcbmsQw.png" /></figure><p>3. VERİ TEMİZLEME</p><p>Veri kümemizde kayıp değerler bulunmamaktadır. Ancak “lights” sütununda çok fazla sıfır değeri bulunduğu için bu sütunu kaldırabiliriz ve hedef değişken olarak sadece “Appliances” sütununu kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*a_cr0HELjd8DdrwE369LNg.png" /></figure><p>Daha sonra “date” sütununu Pandas’ ın “to_datetime” fonksiyonunu kullanarak veri tipini değiştirdik ve veri kümemizi ay, gün, saat bazında gruplandırdık. Burada “Appliances” sütununun toplamını diğer sütunların ise ortalamasını alarak grupladık.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*sciTgtunT3RazWquJNI9hA.png" /></figure><p>4.1. Sıcaklık Dönüşümü</p><p>Veri kümemizde bazı sıcaklık değerlerinde negatif değerler bulunmaktadır. Negatif değerlerin bulunması “np.log” dönüşümü yaparken problem olacağı için bundan kurtulmak adına tüm sıcaklık değerleri negatif olmayan “Kelvin” e dönüştürülmüştür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*iAhKndH5N3indKzlmhjngg.png" /></figure><p>4.2. Aykırı Değerleri Atma</p><p>Bazen, verileri üreten süreçler aykırı değerler olarak kabul edilebilecek aşırı ve nadir değerler üretir. Bu durumda, anormal veriler bir ölçüm hatasından değil, çok veri üretme işleminden kaynaklanmaktadır. “SciPy” ın “winsorize” fonksiyonu hakkında daha fazla bilgiye <a href="https://en.wikipedia.org/wiki/Winsorizing">şuradan</a> ulaşabilirsiniz. Aşağıda bazı değişkenlere ait “boxplot” lar bulunmaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*DF-VxyB5c3DT-QUNfhHiyA.png" /></figure><p>Aykırı değerlerlerden kurtulmanın yaygın yöntemlerinden olan “winsorization” ı kullanacağız. Bu aşamada çok fazla veri kaybetmemek için sütünlar tek tek “winsorize” edilmiştir. Bunun geri dönüşümünü modelimizi oluştururken göreceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*N-UnKYnWYfN0nfREFPPJag.png" /></figure><p>“Winsorization” işlemi sonucu hiçbir aykırı değer kalmamıştır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Kn1kX7g537mrcsdL-8xdmA.png" /></figure><p>5. KEŞİFSEL VERİ ANALİZİ</p><p>Veri kümemizi günlere ve saatlere göre gruplayabiliriz. Bu şekilde zaman serisi varyasyonlarını inceleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*k6FMNO5iog7jlkYAwS8Klw.png" /></figure><p>Yukarıdaki grafik gün bazında ortalama ne kadar enerji harcandığını göstermektedir. Ayın ortaları en fazla tüketimin olduğu zamanlardır. Şimdi de saatlik bazda inceleyelim. Akşam saatlerinde, işten eve gelindiği zamanlarda elektrik tüketimi artacaktır. Aşağıda bunu görebiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*PRsBqSINynHNo4fofc1fbg.png" /></figure><p>Bu yüzden modelimizi oluştururken gün, saat gibi parametreleri dikkate alarak oluşturmalıyız.</p><p>Şimdi de bağımsız değişkenlerin hedef değişken ile arasındaki korelasyon değerlerine bakalım. Aşağıda görüldüğü gibi güçlü ilişkiler yakalayamadık. Aykırı değerleri sınırlandırarak daha lineer ilişkiler bulunabilir. Bu yüzden “np.log” ve “winsorize” dönüşümlerini deneyeceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ddJFrJfVjaiuuqoakMYAYw.png" /></figure><p>6. REGRESYON MODELLERİNİN KURULUMU</p><p>Doğrusal(lineer) regresyon, bir veya daha fazla gözlenen özellik ile hedef değişken arasındaki ilişkiyi modeller. Elimizdeki verilere dayanarak, bizi istediğimiz sonuca ulaştıracak bir fonksiyon türetmeye çalışırız. Bu fonksiyon, özellik değerlerini arayabileceğimiz ve tahmin edilen hedef değerleri bulabileceğimiz bir çizgi oluşturur.</p><p>Regresyon görevleri, bir algoritmaya ihtiyacınız olduğunda sonuçta sürekli sayısal değerleri verir. Bu tür çıktıları üretmenin birçok yolu vardır, ancak en basit ve en çok kullanılan yöntem doğrusal regresyon modelidir. Bu projede, lineer bir regresyon modelinin nasıl formüle edileceğini araştırıp, Sıradan En Küçük Kareler/Squares Ordinary Least (OLS) yöntemini kullanarak modelimizi oluşturacağız. Hadi gelin ilk modelimizin inşasına başlayalım.</p><p><strong>1-) </strong>“Kelvin” dönüşümü yaptığımız veri kümemizin aykırı değerlerden kurtarılmış(winsorized) halini kullanacağız. Burada y değişkenini hedef değişken yapalım, x değişkenine de özellikleri atayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*-RG6F2vFI7rLtQv6XgxekA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*AiaeH19Jmi0HwA74FGoUyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*om3z-ZypXXu0lhs1S6qMzA.png" /></figure><p>Modelimizi kurduk. “R-squared” değeri muhtemelen doğrusal regresyon modelinde uyumun iyi olması için en yaygın ölçüdür. Bu, modeldeki açıklayıcı değişkenler tarafından hedef değişkeninde ne kadar varyans olduğunu açıklayan 0 ile 1 arasında bir orandır. “R-squared” performansının doğası gereği yanlı bir tahminidir. Modele daha açıklayıcı değişkenlerin eklenmesi, daha yüksek “R-squared” değerleri almamız anlamına gelir. Sesler veya rastgele veriler gibi alakasız değişkenleri bile içerir. Bu sorunu hafifletmek için genellikle “R-squared” yerine “Adj. R-squared” denilen bir ölçüm kullanırız.</p><p>Yukarıda regresyon özeti tablosunda, enerji tahmini modelimizde “Adj. R-squared” değerimiz 0.28 olduğunu görüyoruz. Bu, modelimizin varyansı %28&#39;lik bir oranla açıkladığı, %62’yi ise açıklamadan bıraktığı anlamına gelir. Bu oran oldukça düşük bir orandır. Bir modelin eğitim performansı düşükse, biz buna “underfitting” diyoruz. Yukarıda görüldüğü üzere “Adj. R-squared” çok düşüktür. Şimdi tahminleri alma zamanı! “Statsmodels” deki ‘predict()’ fonksiyonunu çağırıp tahminler yapalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*wykv28EZ2jAcUU7H-rAMIg.png" /></figure><p>Modelin tahmin performansı grafikte görüldüğü üzere çok düşüktür. Nispeten düşük değerleri daha iyi tahmin etmiştir. Görselleştirmeler kullanmak, modellerin performansını anlamamıza yardımcı olur. Ancak, modellerimizi değerlendirmek için daha doğru yollar bulmamız gerekiyor. Yukarıda, tahminlerin ne kadar iyi olduğunu değerlendirmek için bazı metrikler de yazdırdık. Hata değerlerinin tümü için daha düşük değerler istenir. Değer ne kadar düşükse, modelin performansı o kadar iyi olur. Bir başka modelimizi deneyelim.</p><p><strong>2-) </strong>Bu modelimizde ise veri kümemize “np.log” dönüşümü yaptık ve “MinMaxScaler” kullanarak değerlerimizi (0,1) arasında ölçeklendirdik. Bu şekilde modelimizi kurduğumuzda;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*9OjedoMC8DTB6kh7qHknrw.png" /></figure><p>“Adj. R-squared” in 0.32 olduğunu gördük. Çok az bir değişim oldu. Hala istediğimiz düzeyde değil. Modelimizin eğitim performansı düşüktür. Buna “underfitting” denmektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*6TFFN6g8aiGO1a5IQ4ZvUA.png" /></figure><p>Grafikte, modelimizin yine hedefin daha düşük değerlerini daha yüksek değerlerden daha iyi tahmin ettiğini görüyoruz. RMSE değerleri azaldı. Farklı yöntemler denemeye devam edelim.</p><p><strong>3-) </strong>Bu modelimizde “winsorize” ettiğimiz veri kümemizi kullandık. İlk olarak “np.log” dönüşümü uyguladık. Daha sonra yine verilerimizi (0,1) aralığında ölçeklendirdik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*z91IFDMXbcjMT8YUcLn0yw.png" /></figure><p>“Adj. R-squared” önemli ölçüde artmıştır. Modelimiz varyansın %93’ lük kısmını açıklayabilmektedir. Çok yüksek “R-squared” değeri, “overfitting” in bir işareti olabilir. Eğer modelimiz veriler için çok karmaşıksa, o zaman eğitim kümesine “overfit” edebilir ve test kümesinde kötü bir iş çıkarabilir. “Overfitting” olduğunu tespit etmek için “R-squared” üzerinde anlaşılmış bir eşik yoktur. Bunun yerine, test ve eğitim verisindeki performans arasında bir karşılaştırma yapılmasını gerekir. Eğer modelimiz test kümesinde eğitim kümesine göre anlamlı derecede daha kötü bir performans sergiliyorsa, o zaman “overfitting” den şüphelenmeliyiz. Modelimizin test kümesine ait “R-squared” değeri aşağıdadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*idiZvhvcvAFt0e71dL-YmQ.png" /></figure><p>Görüldüğü üzere test kümesinin “R-squared” değeri neredeyse eğitim kümesiyle aynıdır. Hatta fazladır. “Overfitting” den şüphelenmeye gerek yoktur. Grafiğe baktığımızda tahminler daha çok çizgiye yakındır. Önemli ölçüde tahmin performansı artmıştır. İyi bir model oluşturmak istiyorsak eğitim ve test kümeleri için RMSE değeri birbirine çok yakın olmalıdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*ZkSBbKo5jD2b3BdW5vNqwg.png" /></figure><p><strong>4-) </strong>Bu<strong> </strong>modelimizde “Polynomial Features” yöntemini kullanarak modelimizi oluşturacağız. Aslında bu yöntem hedef değişken ile bağımsız değişkenler arasında ki ilişki doğrusal olmadığı zamanlarda tercih edilir. Aynı zamanda orjinal özellikleri yüksek dereceli parametrelere dönüştürür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*3v6kFTqtNyzL3UjlK7HujA.png" /></figure><p>Oldukça iyi bir “Adj. R-squared” değeri elde ettik. “Polynomial Features” ile oluşturduğumuz son modelimizden tatmin edici bir tahmin performansı elde ettik. Test kümesine ait “Adj. R-squared” değerleride aşağıdadır. Bire bir tahmin etseydik tüm değerler kırmızı çizgi üzerinde olurdu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*WEdaoxdNls_escmMItRD8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*KN4FG4lQBIPQMck5hCrFWg.png" /></figure><p>6.1.Değerlendirme</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*MHhRTRaSd1uYoiOa_lke-w.png" /></figure><p>Elde edilen sonuçlara bakıldığında “Polynomial Features” metodu tüm metriklerde diğer tüm yöntemlere göre daha iyidir.</p><p>7. SONUÇ</p><p>Makine öğrenmesi, gözetimli, gözetimsiz, pekiştirmeli öğrenme olarak 3 temel gruba ayrılır. Biz burada gözetimli öğrenme türlerinden regresyon modellerinin kurulumunu inceledik. Aslında bu çalışma bize makine öğrenmesi modellerini kurmadan önce analiz kısmının önemini bir daha hatırlattı. Regresyon modellerimizi kurarken yinelemeli bir süreç izlenmeli ve tekrardan başa dönerek tahmin performansını arttıracak değişiklikler yapılmalıdır.</p><p>Daha fazla ayrıntı için GitHub hesabımı ziyaret edebilirsiniz:</p><p><a href="https://github.com/muhammetbektas/Regression-Models/blob/master/AppliancesEnergyPrediction_Regression.ipynb">https://github.com/muhammetbektas/Regression-Models/blob/master/AppliancesEnergyPrediction_Regression.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205ddcaf4298" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python İle Keşifsel Veri Analizi:]]></title>
            <link>https://medium.com/@mbektas/python-i%CC%87le-ke%C5%9Fifsel-veri-analizi-d8a636102954?source=rss-be6295ca36c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8a636102954</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Muhammet Bektaş]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 09:20:41 GMT</pubDate>
            <atom:updated>2020-06-09T20:04:32.641Z</atom:updated>
            <content:encoded><![CDATA[<h4>ARABA FİYATLARINI ETKİLEYEN MUHTEMEL ÖZELLİKLER</h4><p>Veri, olgular üzerinde yapılan gözlemlerin sonucu ve bu anlamda bilginin üretildiği hammaddedir. Veri analizi ise ham verilerden bilgi ve öngörüler elde etmemizi sağlar. Bu nedenle verilerden yararlı bilgileri keşfetmemizde ve problemleri çözüme kavuşturmada hatta geleceği ve bilinmeyeni tahmin etmemizde yardımcı olarak veri analizi önemli bir rol oynamaktadır. Bu yazımızda gerçek, hayata dair bir problemi ele alacağız ve ‘python’ dilini kullanarak temel bilgiler elde edeceğiz. Hadi başlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*5cnNEIur7HZtbmcd1y4PWw.png" /></figure><p>1.PROBLEM</p><p>Varsayalım ki arabanızı satmak istiyorsunuz ve ya bir araba satın almak istiyorsunuz. Buradaki problem, arabanız için ne kadar fiyat belirleme konusunda fikir sahibi olmamanız. Aynı zamanda makul bir fiyat belirlemek istiyorsunuz ki birisi otomobilinizi satın alsın.</p><p>Veri bilimci olarak problemin çözümü için çeşitli sorular sormalıyız. Hangi özellikler arabamızın fiyatını etkiler? Renk? Marka? Veya beygir gücü arabamızın fiyatını etkiler mi? Bu sorulara cevap verebilmek için ‘carprice’ isimli veri kümemizi inceleyelim.</p><p>2. VERİYİ ANLAMA</p><p>Kullanılan veri kümesi açık kaynak bir veri kümesidir. <a href="https://www.kaggle.com/jenisam/logistic-regression-carsprice">Buradan</a> ulaşabilirsiniz.</p><p>Veri kümemiz 205 satır ve 25 sütun içermektedir. İlk özelliğimiz olan “symboling’’ arabanın sigorta risk seviyesine karşılık gelir. +3 değeri otomobilin riskli olduğunu, -3 değeri ise muhtemelen oldukça güvenli olduğunu söylemektedir. Diğer özellikler kolayca anlaşılabilir.</p><p>25. özellik “price” bizim hedef değişkenimizdir. Yani bu veri setini kullanarak tahmin etmek istediğimiz değerdir.</p><p>Not: Bu veri seti 1985 yılına aittir. Bu yüzden araba marka ve özelliklerine ait fiyat değerleri günümüze kıyasla düşüktür. Ancak bu yazının amacının verileri anlamak ve analiz etmek olduğunu unutmayınız.</p><p>4. VERİ SETİNE GENEL BİR BAKIŞ</p><p>4.1. Veri Türleri</p><p>İlk olarak kullanacağımız kütüphaneleri aktif hale getirelim ve veri setimizi Jupyter Notebook ortamına aktaralım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*M4ywdPifQjiwBTPQOYAmfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*q3l2NjFd5592URQX0UQXiA.png" /></figure><p>4.2. Veri Kümemize ait Temel Bilgiler</p><p>dataframe.head(n) komutu veri kümemizde ki ilk n satırı gösterir. Veri kümesinin genel bilgisini elde etmek için, ‘Pandas’ kütüphanesinin ‘info( )’ metodunu kullanabiliriz. Bu fonksiyon, satır ve sütun sayısını ve ayrıca her sütunun veri türünü döndürür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*tshELW59sN7kZb9ik8Hqhw.png" /></figure><p>Herhangi bir analiz yapmadan önce verileri açıkça anlamak gerekir. Veri çeşitli türlere sahiptir. ‘Object’, ‘float’, ‘int’, ‘DataTime’ gibi. Veri türlerini kontrol etmeliyiz. Çünkü sayısal değer içermesini beklediğimiz “price” sütununa ‘object ‘veri tipinin atanması tuhaf olacaktır.</p><p>4.3. Veri Dağılımı</p><p>Her bir sütundaki verilerin dağılımı hakkından bilgi edinmek için her bir sütunun istatistiksel özetini kontrol etmeliyiz. İstatistiksel ölçümler, aşırı anlamlı değerler ve büyük sapmalar gibi olabilecek herhangi bir matematiksel sorunu söyleyebilir. ‘describe( )’ metodu ‘NaN’ değerleri hariç veri dağıtımının merkezi eğilimini, dağılımını ve şeklini özetleyen tanımlayıcı istatistikler üretir. Sayısal değişkenler için ‘<em>count’, ‘mean’, ‘quartiles’</em> gibi bazı istatistikleri döndürür.</p><p>Bu istatistiklere ve bunların analizlerine, veri araştırmasında yaygın bir uygulama olan <strong>tanımlayıcı istatistikler</strong> denir. Varsayılan olarak sonuçları yalnızca sayısal değişkenler için verir, metinler için döndürmez. Onları da görmek istiyorsak, tüm değişkenleri bir arada görmek için yönteme ‘include=&#39;all&#39;’ parametresini ya da sadece metin değişkenlerini görmek için ‘include=[&#39;O&#39;]’ parametresini ekleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*aUux5D1VewdILnDSdrbbuA.png" /></figure><p>5. VERİ TEMİZLEME</p><p>5.1. Kayıp Değerler</p><p>Veri kümemizde kayıp değerler bulunmamaktadır. Aşağıda sütunlara ait kayıp değerlerin sayısını ve sütun içerisindeki yüzdelerini ‘Pandas’ ın concat( ) metodunu kullanarak aynı tablo üzerinde görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*y4C7libyUbYeJJrC2BVbYA.png" /></figure><p>5.2. Aşırı Değerler İle Mücadele</p><p>Verilerin açıklama ölçütlerini başka tarafa çekerler. Örnek olarak, bir değişkenin merkezi eğilimini düşünün. Ortalama en yaygın kullanılan merkezi eğilim istatistiklerinden biridir. Bununla birlikte, aykırı değerlerden muzdariptir. Bazı makine öğrenme modelleri aşırı değerlere duyarlıdır. Dolayısıyla, doğru tahminler alabilmek için bu değerleri veri kümemizden çıkarmamız gerekir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*POkFHzTODcpY1FqAqy9JUA.png" /></figure><p>Aykırı değerleri sınırlandırmanın yaygın bir yoluna ‘<strong>winsorization’</strong> denir. ‘Winsorize’ etmede fikir, uç noktaların değerlerini belirli bir yüzdelik değere ayarlamaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*Ojj0hmT6joGzCFaaWH7zZQ.png" /></figure><p>Gördüğünüz gibi kutu grafiği artık aykırı değer içermemektedir.</p><p>5.4. Kategorik Değişkenleri Nicel Değişkenlere Dönüştürme</p><p>Çoğu model yalnızca sayısal veriler üzerinde çalışacağından, metin değerli kategorik verilerimizi sayısal bir değere dönüştürmemiz gerekir. Bu amaç için iki yöntem kullanılmaktadır. Bunlar ‘Label Encoder’ ve ‘One Hot Encoder’ dır. Biz burada kategorik değişkenlerin az olması ve sütun sayısının fazla olmamasından dolayı ‘One Hot Encoder’ yöntemini kullanacağız. ‘One Hot’ kodlamada, X seviyeli kategorik bir değişkenden bilgi edinmek için, her biri 1 veya 0 kodlanan X-1 adet sayısal özellik yaratırız. Her kategori için 0 veya 1 alan sonuç değişkenleri ‘<strong>dummy’ </strong>veya<strong> gösterge</strong> değişkenler olarak bilinir. ‘One-hot’ kodlamayı kategorik bir değişkene uygulamak için ‘Pandas’ ın ‘get_dummies()’ metodunu kullanabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*NrhAskFs53lUO6_Nc2PeQw.png" /></figure><p>Aşağıda örneğin “fueltype” kategorik değişkenine ait ‘one-hot’ kodlama uygulanarak her kategori için 1,0 değerleri atanmıştır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*dDbT-1vFEAvYiI0eePpHvA.png" /></figure><p>6. KEŞİFSEL VERİ ANALİZİ (EDA)</p><p>Adından da anlaşılacağı gibi, ‘EDA(Exploratory Data Analysis)’, verilerde gizlenmiş olan bilgilere ulaşmak için verileri keşfetme sürecidir. Araştırma, yeni şeyler keşfetmek için yapıldığından, yeni ilişkiler ve kalıplar keşfetmek için verileri araştırırız veya varsayımlarımızın verilerde haklı olup olmadığını gözlemleriz. Beklendiği gibi, bir veri bilimcisinin en yakın arkadaşı en çok bildiği veridir. Ancak, verileri bilmek hızlı bir başarı değildir ve verileri dinlemek için yeterince zaman harcamamız gerekir. ‘EDA’, verilerin kendisi için konuşmasına izin verme sürecidir.Burada cevap bulmamız gereken soru “Araba fiyatı üzerinde en fazla etkiye sahip olan özellikler hangileridir?” sorusudur.</p><p>6.1. Sürekli ve Kategorik Bir Çiftin İki Değişkenli Analizi</p><p>Sürekli ve kategorik bir değişken çifti analiz ettiğimizde, kategorik değerin her bir değeri için genellikle sürekli değişkenin bazı ölçümlerine bakarız. Kategoriler arasında farklı değerler gözlemlersek, bu kategorik değişkenin sürekli değişkenle ilgili bazı önemli bilgilere sahip olduğunu gösterir. Aşağıda, “cylindernumber” değişkenindeki her değer için ortalama fiyat miktarını gösteren bir çubuk grafiği çiziyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*MZ0hDaco1sQFwDcrmVn5VA.png" /></figure><p>Silindir numaralarına göre arabaların ortalama fiyatlarına baktığımızda en pahalı araçların 8 silindirli araçlar olduğu görmekteyiz. Ancak ortalama her zaman gerçeği yansıtmaz. Bu yüzden istatistiksel olarak doğrulatmak için t-test yapalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*cx8v4g5JnyHIsZNdG_Vquw.png" /></figure><p>Farklılıkların istatistiksel olarak anlamlı olup olmadığını öğrenmek için t-test yaptık. Bunu anlamak için p-değeri 0.05 ten küçük olanları ekrana yazdırdık. Burada da gördük ki sekiz silindirli araçlar ile diğer araçlar arasındaki bu fark istatistiksel olarak anlamlıdır. Tek değer bulunan kategorik özellikler ile t-test uygulanamamaktadır. P-değeri NaN olarak hesaplanmaktadır. Bu yüzden sekiz ve on iki silindirli araçlar karşılaştırılamamıştır. Şimdi de diğer bir kategorik değişkenimiz olan “carbody” için sütun grafiği çizdirelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*V-vHuN73GtwGsefXGVxKGg.png" /></figure><p>Ancak ortalama her zaman gerçeği yansıtmaz. Bu yüzden istatistiksel olarak doğrulatmak için t-test yapalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*747LrjTbSMdS3fHrwLa8pw.png" /></figure><p>Burada p değerleri 0.05 den küçük olanları yani aralarında anlamlı bir fark olanları tabloda görüyoruz. ‘Hatchback’ arabaların ‘sedan’, ‘hardtop’ ve ‘convertible’ tipindeki araçlara göre daha pahalı olduğunu doğruladık. Diğer araçlar ile arasında anlamlı bir fark yoktur. Yani mesela ‘hatchback’ araçların ‘wagon’ tipindeki araçlara göre pahalı olduğunu söyleyemeyiz.</p><p>6.2. İki Sürekli Değişkenin İki Değişkenli Analizi</p><p>İki sürekli değişken arasındaki ilişkiye bakmanın en bilgilendirici yollarından biri dağılım grafiklerini çizmektir (‘scattergram’ olarak da bilinir). Örneğin, ilk değişkenin değerinin genellikle ikincisinin değeri arttığı zaman arttığını görürsek, bu, bu iki değişken arasında pozitif bir ilişki olduğunu gösterir. Hedef değişkenimizi “price” olarak belirleyip diğer sürekli değişkenler ile korelasyonunu inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*eSnSTU4Qeh02zfe5GmRvrA.png" /></figure><p>Grafikleri incelediğimizde ‘carlengt&amp;price’ dağılım grafiği üstel dağılımı andırmaktadır. Belirli aralıklarda aralarında pozitif (lineer) ilişki vardır. Pozitif korelasyonun en belirgin olduğu dağılım grafiği ise ‘enginesize&amp;price’ grafiğidir. İkinci olarak da ‘curbweight&amp;price’ arasında görülmektedir. Bu değişkenlere ‘np.log( )’ dönüşümü yapılarak daha lineer ilişkiler yakalanabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*hSY_4xGFR6y9EnX0pRFoNA.png" /></figure><p>Log dönüşümü ile ilişkiler daha doğrusal hale geldi. Şimdi de korelasyon matrisine bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*g3nky_chbd3NWMa3jXrTWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*kRWmMn80SRVX0teXpM0cNg.png" /></figure><p>Yukarıda değişkenlerin “price” ile olan hem negatif hem de pozitif korelasyonlarını görebilmekteyiz.</p><p>7. ÖZELLİK MÜHENDİSLİĞİ</p><p>Verilerimizi temizlediğimize ve onları incelediğimize göre, bir sonraki adım hedef değişkeni açıklamada faydalı olacağını düşündüğümüz özellikleri belirlemektir. Bu adıma <strong>özellik mühendisliği</strong> denir.</p><p>‘Horsepower/enginesize’ oranı bize maksimum gücü vermektedir. O halde bu yeni değişkenimizin fiyat üzerindeki etkisini araştıralım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*CyKDJh82E1oM4XUxvBjDOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*VhaS-arC_6cXF2ZZr69BGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*IegyZD_j11tUnY5Myw1iHg.png" /></figure><p>Ancak korelasyon matrisine baktığımızda “maxpower” değişkenimizin fiyat üzerindeki etkisi çok azdır.</p><p>8. TEMEL BİLEŞEN ANALİZİ (PCA)</p><p>‘PCA’, değişkenlerdeki bilgilerin çoğunu temsil eden daha küçük bir bileşen grubuna indirgemeye çalışan bir karmaşıklık azaltma tekniğidir. Kavramsal düzeyde ‘PCA’, varyansı paylaşan değişken kümelerini tanımlar ve bu varyansı temsil edecek bir bileşen yaratır.</p><p>Veri kümemizi ait varyansı üç bileşen tarafından temsil edecek şekilde boyut azaltma işlemi yapalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*xO7gJ2YuhJ1PtNN676zQ0A.png" /></figure><p>İlk temel bileşen varyansın %63.8 ini açıklamaktadır. Bu oran iyi bir sonuçtur. Bu problemde değişken sayımız az olduğu için bu yöntemi kullanmadık. Sadece nasıl yapıldığından bahsetmek amacıyla gösterilmiştir.</p><p>9. SONUÇLAR</p><p>Analizimiz bitti. Verileri, sınıflandırılmış değişkenleri, çizilen grafikleri anladık. Bazı testler yaptık ve hedef değişkenlerimiz üzerinde etkili olan özellikler elde etmeye çalıştık. Elde ettiğim bazı sonuçlar şöyle;</p><p>· ‘Horsepower’, ‘enginesize’ ve ‘curbweight’ fiyat için oldukça iyi bir tahmin aracı olduğunu söyleyebiliriz.</p><p>· Kategorik değişkenlerimizi incelediğimizde, ‘rwd’ (drivewheel), ‘gas’ (fueltype), ‘hatchback’ (carbody) ve ‘eight’ (cylindernumber) için fiyat diğerlerinden daha yüksektir.</p><p>· ‘Peakrpm’ ile fiyat arasında bir ilişki tespit edemedik.</p><p>· Son olarak, python içinde ‘PCA’ modülünü kullanarak, ilk temel bileşenin varyansın en fazla % 63.8&#39;ini temsil ettiğini bulduk.</p><p>Sonuç olarak, bu aşamadan sonra makine öğrenimi modellerinin inşasına geçmemiz gerekmektedir. Modelimizi, hedef değişkeni anlamlı şekilde etkileyen özelliklerle beslememiz modelin tahmin performansını etkileyecektir.</p><p>Daha fazla ayrıntı için lütfen GitHub hesabımı ziyaret edin:</p><p><a href="https://github.com/muhammetbektas/Temel-Veri-Analizi/blob/master/The%20Most%20Probable%20Signals%20Of%20Automobile%20Price.ipynb">https://github.com/muhammetbektas/Temel-Veri-Analizi/blob/master/The%20Most%20Probable%20Signals%20Of%20Automobile%20Price.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8a636102954" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>