<?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 Hakan Ateşli on Medium]]></title>
        <description><![CDATA[Stories by Hakan Ateşli on Medium]]></description>
        <link>https://medium.com/@hakanateslii?source=rss-bc6cb6ba9a57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s1kVyLvkgOuEq2RpEE-0Pw@2x.jpeg</url>
            <title>Stories by Hakan Ateşli on Medium</title>
            <link>https://medium.com/@hakanateslii?source=rss-bc6cb6ba9a57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:15:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hakanateslii/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[Feature Store]]></title>
            <link>https://hakanateslii.medium.com/feature-store-c183468b4df4?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/c183468b4df4</guid>
            <category><![CDATA[feature-store]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 13:26:06 GMT</pubDate>
            <atom:updated>2025-09-08T13:26:06.852Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Feature Store Nedir?</strong></h4><p>Feature storelara geçmeden önce açıklık getirilmesi gereken ilk şey tabiki feature olacaktır. Makine öğrenmesi modelleri büyük bir çoğunlukla ham veriyi girdi olarak alamazlar. Ham veriler bir ön işlemeden geçirilmek zorundadır. Bu sürece feature engineering diyoruz ve bu sürecin sonunda oluşan çıktıya feature adını veriyoruz. Teknik olarak feature Makine Öğrenmesi modelininin girdisidir denilebilir.</p><p>Veri bilimi ekiplerinin genel bir problemi ise feature engineering süreçlerinde ekiplerin birbirlerinden habersiz bir şekilde aynı featureları çıkarmak için uğraşmasıdır. Bu ise hem ekipler için hemde şirket için oldukça büyük bir zaman ve maliyet kaybına sebep olmaktadır. Genel olarak notebooklar üzerinden yürüyen bu süreçler de elde edilen featureları yönetmekte imkansız hale gelmektedir.</p><p>Feature Store ise tam da bu noktada ortaya çıkmış bir konsepttir. Feature Store, Makine öğrenmesi modellerinde kullanılmak üzere oluşturulan feature gruplarını depolayıp yönettiğiniz merkezi bir konumdur. Veri bilimcilerin arayüz veya API yardımıyla feature storedaki featureları keşfetmesine, bu featurelara erişip modellerini eğitmesine, yeni featurelar eklemesine yardımcı olmaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJ-5OKKcb9V8DM6xgS4ITg.png" /><figcaption><a href="https://www.tecton.ai/blog/what-is-a-feature-store/">https://www.tecton.ai/blog/what-is-a-feature-store/</a></figcaption></figure><p>Feature Store’ların faydalarından bazıları:</p><ul><li>Tekrarlayan ve gereksiz işleri ortadan kaldırarak verimliliğini artırmak</li><li>Kurum içerisinde standartlaşmış bir feature yönetimi sağlamak</li><li>Eğitim ve tahminleme için tutarlı feature sağlamak</li></ul><h4><strong>Feature Store Componentleri</strong></h4><p>Yeni bir konsept olmasına rağmen piyasada birçok açık kaynak veya ticari feature store ürünü bulunmaktadır. Her birinin farklı özellikleri olmakla birlikte genellikle 5 componentten oluşurlar. Bunlar şu şekildedir: Transform, storage, serving, monitoring, registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2viaODIYwxEYgjYz9rijFA.png" /><figcaption><a href="https://www.tecton.ai/blog/what-is-a-feature-store/">https://www.tecton.ai/blog/what-is-a-feature-store/</a></figcaption></figure><p><strong><em>Monitoring: </em></strong>ML modelleri başta iyi sonuç verse de zaman geçtikçe doğruluğu ve güvenilirliği sorgulanabilir. Bağımlı ve bağımsız değişkenlerin istatistiksel özellikleri zamanla değişebilir. Bu sebeple modeller sürekli izlenmelidir. Bu component modelleri izleyebilmek için bizlere veri doğruluğu ve verilerin istatistiksel olarak değişimlerini bizlere sunabilir. Ayrıca veri depolama (kapasite, güncellik) ve veri servis etme(gecikme, aktarım hızı) componentlerine ait temel ölçümleri bizlere sunar.</p><p><strong><em>Transformation:</em></strong> Yazının başında da bahsettiğim gibi ml modelleri genellikle ham veriyi girdi olarak alamazlar. Ham verilerin bazı dönüşümler geçirmesi gerekmektedir. Bunların yönetme ve düzenleme işlerini ise transformation katmanında gerçekleştiriyoruz. Ham verinin ml modeline girdi olabilecek hale gelmesi için birkaç farklı trasform şekli vardır.</p><ul><li>Stream Transform: Gerçek zamanlı veriler için dönüştürme</li><li>Batch Transform: Toplu veriler için dönüştürme</li><li>On-demand Transform: İhtiyaç duyulan veriler için dönüştürme</li></ul><p><strong><em>Storage: </em></strong>Feature store temelde makine öğrenmesi özelliklerinden oluşan bir veri ambarına benzetilebilir. Fakat hem çevrimiçi hemde çevrimdışı özellikleri içermesinden kaynaklı ikili bir veritabanı gibi görünmesi mimari açıdan veri ambarından farklılaşmasını sağlıyor. Feature storelar yukarıda da bahsettiğimiz üzere veritabanı değildir. Bu sebeple storage katmanında çevrimiçi veriler için Snowflake, Hive, Redshift vb. , çevrimdışı tarafta MongoDB, CassadraDB, ElastichSearch vb. veritabanlarını kullanmaktadır.</p><p><strong><em>Serving: </em></strong>Feature storelar hem model eğitimi için batch serving hem de model tahminlemesi için real-time serving gerçekleştirebilmektedir. Bu component için önemli olan model eğitimi için sağladığı veriler ile model tahminlemesi için sağladığı veriler arasındaki tutarlılığıdır. Ayrıca çevrimiçi verileri servis ederken düşük gecikmeli olacak şekilde yüksek performanslı bir API sağlamalıdır.</p><p><strong><em>Registry:</em></strong> Feature storeda tutulan featureların metadatasının bulunduğu bölümdür. Farklı ekiplerdeki veri bilimcilerin feature storeda bulunan featureları keşfetmesine ve geliştirmesine olanak sağlamak için ortak bir katalog olarak kullanılır.</p><h4><strong>Mevcut Feature Storelar ve Farkları</strong></h4><p><strong>1- </strong><a href="https://feast.dev/"><strong>Feast</strong></a></p><p>Feast, Gojek ve Google Cloud tarafında ortaklaşa geliştirilen ve Microsoft gibi bir çok firma tarafından da benimsenen, rakibi olarak düşünebileceğimiz Tecton’unda desteklediği açık kaynak kodlu feature storedur. Açık kaynaklı olması ticari ürünlerden çok daha kısıtlı özellikler sunmasınıda beraberinde getirmektedir. Fakat feature store yapısına giriş için iyi bir ürün olduğu söylenebilir.</p><p>Feast, storage, serving ve registry componentlerini içermektedir.</p><ul><li>Postgres, Redis, Kafka, BigQuery, DynamoDB veritabanlarıyla çalışabilmektedir.</li><li>Python dilini desteklemektedir.</li><li>Kubernetes, GCP ve AWS ortamlarında kullanılabilmektedir.</li><li>Google Cloud Storage, Amazon S3 ve Azure Blob desteklemektedir.</li><li>Kubeflow ve Amazon EMR platformlarıyla entegre olabilmektedir.</li></ul><p><strong>2- </strong><a href="https://www.tecton.ai/"><strong>Tecton</strong></a></p><p>Tecton, Uber’de Michelangelo ürününü ortaya çıkaran mühendisler tarafından 2019 yılında ilk ticari feature store olarak piyasaya sunuldu. Snowflakes ve Databricks gibi sektörün öncü şirketlerinden yatırımlar aldı.</p><p>Tecton, Feature store’a ait bütün componentlere sahiptir.</p><ul><li>Amazon S3, RDS, KINESIS, kafka, Delta Lake, Snowflake veritabanlarıyla çalışabilmektedir.</li><li>Python ve PySpark dillerini desteklemektedir.</li><li>AWS ortamında kullanılabilmektedir.</li><li>Databricks ve Amazon EMR platformlarıyla entegre olabilmektedir.</li><li>Feature Görselleştirme ve WEB UI gibi özellikler sunmaktadır.</li><li>Yetki yönetimi özelliği bulunmaktadır.</li></ul><p><strong>3- </strong><a href="https://www.hopsworks.ai/"><strong>Hopsworks</strong></a></p><p>Hopsworks, Python merkezli Özellik Mağazası ve MLOps yeteneklerine sahip ML için bir veri platformudur. Hopsworks modüler bir platformdur. Hopsworks, en fazla veri kaynağına bağlanan feature store ürünüdür.</p><p>Hopsworks, Feature store’a ait bütün componentlere sahiptir.</p><ul><li>Bigquery, Hadoop, MongoDB, RonDB, HopsFS, S3, Kafka, ElasticSearch veritabanlarıyla çalışabilmektedir.</li><li>Python, PySpark, Spark dillerini desteklemektedir.</li><li>AWS, Azure, GCP ve on-premises ortamlarında kullanılabilmektedir.</li><li>Airflow, kubeflow, Azure ML, Databricks platformlarıyla entegre olabilmektedir.</li><li>Feature Görselleştirme ve WEB UI gibi özellikler sunmaktadır.</li><li>Yetki yönetimi özelliği bulunmaktadır.</li></ul><p><strong>4-</strong><a href="https://aws.amazon.com/tr/sagemaker/feature-store/"><strong> Amazon SageMaker Feature Store</strong></a></p><p>Amazonun SageMaker Feature Store, Amazon SageMaker ürünün bir özelliği olarak sunulur. SageMaker, Amazon’un uçtan uca yönetilen bir makine öğrenmesi platformudur.</p><p>Amazon SageMaker Feature Store, storage, transformation, serving ve registry componentlerini içermektedir.</p><ul><li>Amazon’a ait veritabanlarıyla çalışabilmektedir.</li><li>Python dilini desteklemektedir.</li><li>AWS ortamında kullanılabilmektedir.</li><li>WEB UI özellikliği sunmaktadır.</li><li>Yetki yönetimi özelliği bulunmaktadır.</li></ul><p><strong>5- </strong><a href="https://cloud.google.com/vertex-ai/docs/featurestore/overview"><strong>Vertex AI Feature Store</strong></a></p><p>Vertex AI Feature Store, Vertex AI ürünün bir özelliği olarak sunulur. Vertex aI, Google’ın uçtan uca yönetilen önceden eğitilmiş ve özel araçlarla ML modellerini daha hızlı oluşturulan, dağıtılan ve ölçeklendirilen yapay zeka platformudur.</p><ul><li>Bigquery veritabanıyla çalışabilmektedir.</li><li>Python dilini desteklemektedir.</li><li>GCP ortamında kullanılabilmektedir.</li><li>WEB UI özellikliği sunmaktadır.</li><li>Yetki yönetimi özelliği bulunmaktadır.</li></ul><h4><strong>Kaynakça</strong></h4><ul><li><a href="https://www.featurestore.org/what-is-a-feature-store">https://www.featurestore.org/what-is-a-feature-store</a></li><li><a href="https://www.hopsworks.ai/post/how-to-build-your-own-feature-store">https://www.hopsworks.ai/post/how-to-build-your-own-feature-store</a></li><li><a href="https://www.moderndatastack.xyz/category/feature-store">https://www.moderndatastack.xyz/category/feature-store</a></li><li><a href="https://www.tecton.ai/blog/what-is-a-feature-store/">https://www.tecton.ai/blog/what-is-a-feature-store/</a></li><li><a href="https://www.moderndatastack.xyz/companies/feature-store">https://www.moderndatastack.xyz/companies/feature-store</a></li><li><a href="https://www.featurestorecomparison.com/">https://www.featurestorecomparison.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c183468b4df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explainable AI With SHAP]]></title>
            <link>https://medium.com/hepsiburada-data-science/explainable-ai-with-shap-6f629dfa6eef?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f629dfa6eef</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[shapley-values]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[shap]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 14:12:36 GMT</pubDate>
            <atom:updated>2023-12-22T14:12:36.433Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Complexity to Clarity: Exploring AI Transparency with SHAP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE-7rEkMH60S3PPIog9Alw.png" /></figure><p>In this article, we will discuss the concept of Explainable Artificial Intelligence (XAI), a topic gaining prominence alongside the growing utilization of artificial intelligence. Additionally, we will explore the SHAP library, an approach that tries to help data scientists to be able to explain AI algorithms.</p><h3>What is XAI?</h3><p>Machine learning systems are similar to a black box for end-users. Decision-makers face difficulty in trusting systems where they not only do not know the basis for the current outcomes but also lack insight into how the system will produce results in the future.</p><p>What decision-makers desire is this: understanding how the model makes decisions and being able to grasp the patterns the model captures in the data. Taking these captured patterns as insight and incorporating them into business decisions will enhance reliability, transparency, and yield maximum returns.</p><p>Moreover, with the tightening of regulations, both in Türkiye and Europe, are making explainability a rising trend in the near term across various industries.</p><h4>Why we need it?</h4><p>One of the fundamental goals of Explainable AI (XAI) is to enhance artificial intelligence-human interaction. As known, the difficulty in explaining how AI reaches decisions causes many people without technical knowledge to hesitate to accept AI. XAI aims to transform the black box into a glass box, revealing how the engine under the hood operates for everyone to see. This way, non-technical individuals can use artificial intelligence not as a daunting tool but as a system with insight and recommendation capabilities, fostering synergy between the capabilities of artificial intelligence and human creativity.</p><p>If we were to give an example of what can arise from human-artificial intelligence interaction, it would be as follows:</p><p>Imagine you’re a member of the customer satisfaction team, and you want to take action for customers who are churning. You’ve trained a customer churn model and, upon examining the model’s feature importance, you’ve noticed that data related to canceled orders is crucial in a customer’s decision to churn. Once you observe this, you can initiate a targeted communication strategy for potentially churning customers, offering extra coupons for canceled orders to increase satisfaction and prevent churn.</p><p><em>The acceptance, proliferation, and widespread adoption of a system are directly proportional to the trust in that system.</em></p><ul><li>Increasing trust and reliability</li><li>Encouraging collaboration between humans and artificial intelligence</li><li>Reducing bias and discrimination</li><li>Compliance with regulatory requirements</li></ul><p><em>While exploring Explainable AI (XAI) can be beneficial, it is also a matter of being human. We want to know how things work in our subconscious, and the urge to understand that neural networks are ‘our’ creation is incredibly frustrating.</em></p><p><em>Sometimes, it can be frustrating when our tool doesn’t work as we want it to, but that’s a reality. Artificial intelligence is a mirror reflecting the truth.[</em><a href="https://edrone.me/blog/explainable-ai-explained"><em>1</em></a><em>]</em></p><h3>Shapley Values</h3><p>Now that we have explained the concept of Explainable AI (XAI), let’s delve into one of its most widely applied methods — Shapley values. Shapley values are a mathematical formula based on game theory. They were developed to measure the marginal contributions of all factors that could affect a prize in a competition.</p><p>They determine the contribution of each factor to winning the prize by considering the order of all factors in group permutations in the context of an ongoing competition.</p><p>To make it more understandable, let’s consider some examples:</p><ul><li>Calculating how to distribute the prize among members of a group participating in a competition.</li><li>Determining which advertising channel contributes the most to sales in a product marketing campaign.</li><li>Identifying the primary factor causing a customer to leave an application.</li></ul><p>In such examples, we can solve the problem by calculating Shapley values.</p><p>If we delve a bit deeper into the fundamentals and examine Shapley values mathematically, it might become clearer. For this purpose, let’s create a scenario:</p><p>Imagine an e-commerce site with three different sellers selling a product. We are asked to rank these sellers. When ranking them, we need to arrange them from the seller who can sell the product the most to the one who can sell it the least. Let’s say the product sold 10,000 units when sold by these three sellers. The value of 10,000 represents the coalition value of these three sellers. We will calculate the expected marginal contribution of each seller and arrange them based on this value. The expected marginal contribution is the Shapley values.</p><p>To calculate the expected marginal contribution, we need to know the coalition value of each participant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*pnQs6YeCPHbNhS-b8H7e7A.png" /></figure><p>To calculate the expected marginal contribution of Seller A, we have four coalitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*21ZR-sTI_fm-fTLTYYZnzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ry1x2xiaacrmGU0QpziRiA.png" /></figure><p>By adding a probabilistic weight to the marginal contribution with the weights here, we obtain the expected marginal contribution.</p><p>The weights are calculated as follows.</p><p>For example, let’s calculate the probability of the operation Cᵃᵇᶜ — Cᵇᶜ =5000.</p><p><em>P</em>(Cᵃᵇᶜ — Cᵇᶜ)= 1 / 3</p><p>To calculate this probability value, we find all the teams that three users can form. To do this, we find the value of 3!, which is 6.</p><p>Among all these permutations, we need to find situations where Seller A is included after Seller B and Seller C. We do this because we are trying to find the marginal contribution made by Seller A after joining an existing coalition.</p><p>If we visualize this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_LCjroAWbKuHPehzzZGWg.png" /></figure><p>As seen, there are 2 situations in which Seller A is included after Seller B and Seller C in all permutations.</p><p>As a result, <em>P</em>(<em>C</em>−<em>abc</em> — <em>C</em>−<em>bc</em>)= 2/6 = 1/3.</p><p>Before formulating this, we need to make the following definitions:</p><ul><li><em>N</em>! = All coalitions that can be formed with N players (sellers)</li><li>∣<em>S</em>∣ = Number of players in coalition S (excluding the player for whom Shapley Values are calculated)</li><li>∣<em>S</em>∣! = All coalitions that players in S can form before player i joins</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDHS_xapzT2OiMCzZhnDGg.png" /></figure><h3>Shapley Values in Machine Learning</h3><p>Now that we’ve learned how to calculate Shapley values, can’t we calculate the contribution of each feature in a machine learning model to the prediction by calculating the Shapley value of each feature? Partially yes, partially no. But why?</p><p>When computing Shapley values, we calculate the contribution of a feature by determining its marginal contributions to all possible subsets and then taking the weighted average. While this might be feasible for models with a small feature set, as the number of input features in the model increases, the cost of computing this becomes significantly high, and in some cases, nearly impossible. Therefore, explainability methods used in machine learning are developed not to calculate the actual Shapley values but to approximate them with values closest to Shapley values.</p><p>Now, let’s delve a bit deeper into this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esxpItAt09oZaYsOL8dn_A.png" /></figure><p>The formula you see above demonstrates that when we add the Shapley values of each feature to the model’s base (Expected values), we obtain the prediction value as a result.</p><p>So, how do we calculate the Shapley value for each feature? How do we apply the above formula to our machine learning model?</p><p>The formula remains the same, but we need to modify the definitions as follows:</p><p>p: the number of features in the model.</p><p>S: the coalition of each <strong>feature value</strong>.</p><p>Since we want to explain each prediction in machine learning, even though the feature set in each prediction is the same, the values are different. Therefore, we need to find the expected marginal contribution of each feature value to that prediction.</p><p>To find the expected marginal contribution, we also need the value function. While explaining Shapley values, I used the calculated versions of coalition values for better understanding. Now it’s time to learn how each coalition value is calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrrnxd8_nsAk0fzWZx1IGA.png" /></figure><p>When explaining this function, we’re essentially computing the integral of the value function for each coalition S, considering the range of potential values for elements outside the coalition. It will be more understandable to explain this with an example.</p><p>Let’s say we have a house price prediction model. This model is created using linear regression.</p><p>Let’s consider a house with a garden, measuring 400 square meters. We want to find the marginal contribution of having a garden to the price, given that the house has 400 square meters. To do this, we need to calculate the integral over the possible value ranges of the values outside the coalition. This example will clarify the concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAUgxC4C48ptXWCvI25bAg.png" /></figure><p>The five axioms offered by the Shap library are as follows:</p><ul><li><strong>Efficiency:</strong> When we sum up the Shapley values of all features, we obtain the total gain.</li><li><strong>Symmetry:</strong> If two features provide the same contribution to the result in all coalitions they participate in, their Shapley values are the same.</li><li><strong>Dummy:</strong> If a feature does not contribute to the result in any coalition it participates in, its Shapley value will be 0.</li><li><strong>Additivity:</strong> This axiom is only valid for ensemble models. Suppose we have a random forest model that takes the average of the predictions of two decision trees. The average of the Shapley values of the features in these two decision trees is equal to the Shapley values in the random forest model.</li><li><strong>Consistency:</strong> When a feature changes in a model and the prediction changes, the marginal contribution of that feature also changes in the same direction.</li></ul><p>Now, returning to the computation cost we mentioned earlier, calculating coalition values in a two-feature model versus the increasing computation cost as the number of features in the feature set grows shows an exponential increase. This leads us practically to compute approximate Shapley values, which are more feasible in practice.</p><h3>Approximation Method</h3><p><em>So how do we calculate an approximate value instead of the original Shapley value?</em></p><h3>Monte Carlo Random Sampling</h3><p>In the Monte Carlo method, instead of finding each subset coalition, we randomly sample possible subset coalitions and calculate the Shapley value based on them. For example, suppose we have a model with 5 features, and we want to find the coalitions in which the x1 feature value can contribute. To do this, we randomly shuffle the 5 features. We then remove the features that come after x1 in the shuffled order from the coalition. By subtracting x1 from this coalition value, we calculate a marginal contribution. We repeat this process K (Monte Carlo parameter) times. In the end, we can approximately calculate how many possible permutations can result in this contribution for the coalition value. As a result, we obtain an approximate value for the Shapley values.</p><p>However, Monte Carlo is still not a practical application. Therefore, different approximation methods have been developed.</p><h3>KernelSHAP</h3><p>One of these approximation methods is the KernelSHAP method.</p><p>A sufficient number of coalition vectors (simplified features) is created. In this vector, where features with a value of 1 are replaced by their actual values, and features with a value of 0 are replaced by different feature values, the prediction of our model is obtained for this sample. Then, using SHAP Kernel, the weight of each feature is calculated. A linear model is trained using these weight values. The target value of the linear model is the predicted value of our model for that sample. The coefficient values of the linear model correspond to Shapley Values for each feature. In this way, we reach Shapley Values much faster than the Monte Carlo method.</p><p>Tests comparing this method with other approximation approaches show that it provides the most reliable approximate value. You can refer to the SHAP paper for more details.</p><h3>SHAP with Python</h3><p>I will introduce SHAP, the most widely used library for implementing Shapley values in Python.</p><h4>Explainer</h4><p>The Explainer class is created as an interface to apply the approximation methods mentioned above. Approximation methods are implemented by inheriting this class.</p><p>Some of these explainers include:</p><ul><li><strong><em>KernelExplainer:</em></strong> Using the KernelSHAP method mentioned earlier, it is a fast method that uses a special weighted linear regression to calculate the importance of each feature.</li><li><strong><em>TreeExplainer:</em></strong> It provides a fast and accurate method for calculating SHAP values for ensemble tree machine learning models. It supports XGBoost, LightGBM, CatBoost, Pyspark, and most tree-based scikit-learn models.</li><li><strong><em>DeepExplainer:</em></strong> It is a method created to approximately calculate SHAP values for deep learning models using the DeepLIFT algorithm. It supports the TensorFlow and PyTorch libraries.</li></ul><p>By selecting the explainer that best fits your model, you can obtain Shapley values for each feature for each sample. After obtaining Shapley values, we need to use visualization techniques to make sense of these values. To discuss these visualization techniques individually, we will visualize the Shap values obtained from a simple example.</p><p>For this simple example, we will train a model predicting house prices in California, a commonly used dataset. Later, we will use the Explainer function of the SHAP library to calculate how much each input feature contributes to the prediction in this model.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>import xgboost<br>import shap<br>import matplotlib.pyplot as plt<br>shap.initjs()<br><br><br>from sklearn.datasets import fetch_california_housing<br>california_housing = fetch_california_housing()<br><br>data = pd.DataFrame(data=np.c_[california_housing[&#39;data&#39;], california_housing[&#39;target&#39;]],<br>                     columns=california_housing[&#39;feature_names&#39;] + [&#39;target&#39;])<br><br>print(data.head())<br><br>data[&#39;MedInc_Rooms&#39;] = data[&#39;MedInc&#39;] / data[&#39;AveRooms&#39;]<br><br>X = data.drop(&#39;target&#39;, axis=1)<br>y = data[&#39;target&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br><br>xgb_model = xgboost.XGBRegressor(objective =&#39;reg:squarederror&#39;)<br>xgb_model.fit(X_train, y_train)</pre><p>The SHAP library’s Explainer function takes a trained model as input and returns an object. This object returns Shapley values for each sample in the dataset it received as a parameter.</p><p>The computation step of <strong>shap_values</strong> can take a long time, depending on the size of your dataset and the number of features.</p><pre>explainer = shap.TreeExplainer(xgb_model)<br>shap_values = explainer(X_test)</pre><h3>Plots</h3><p>To make these Shapley values more understandable, the SHAP library provides a variety of visualization tools. One of them is a bar plot that shows the average Shapley values for each feature. In this plot, we can see how much each feature contributes to predictions based on the average absolute values, helping us understand the importance of features.</p><pre>shap.summary_plot(shap_values, X_test, plot_type=&quot;bar&quot;, feature_names=X_test.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*a7vKBBTBfzRCgOylq-htRg.png" /></figure><p>The BeeSwarm plot allows us to see how each feature&#39;s distribution influences predictions based on its own data range. In this plot, each point in the row corresponds to a sample. This visualization helps us better understand where the concentration of features is and how their distribution looks.</p><pre>shap.plots.beeswarm(shap_values, X_test, feature_names=X_test.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*IsqIQVel8Gmhoi5-uJvmrA.png" /></figure><p>The ForcePlot is used to visualize the contribution of features on a sample basis. Each bar represents a feature, the length of the bar represents its contribution to the prediction, and the color indicates the direction of the contribution.</p><pre>shap.plots.force(shap_values[2], matplotlib = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IDRzW_NOPevW3FbcXpp9Q.png" /></figure><p>Similar to the ForcePlot, the Waterfall chart also provides a sample-based visualization. In this graph, the vertical axis represents the feature values on a sample basis, while the horizontal axis shows the cumulative contributions of features until reaching the prediction over the expected values.</p><pre>shap.plots.waterfall(shap.Explanation(values=shap_values[0], <br>                                     base_values=explainer.expected_value, <br>                                     data=X_test.iloc[0, :]),<br>                     max_display=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6eAo4vv6IoOQugWIrTA3g.png" /></figure><p>The Violin plot is similar to the BeeSwarm plot, but the key difference is that the Violin plot helps visualize the central tendency, spread, and symmetry of the data distribution. Since both are very similar graphics, the choice depends on personal preferences.</p><pre>feat_names = list(X.columns)<br>shap.plots.violin(shap_values, feature_names=feat_names)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veOuIwy3WXBWwR8vqWgEpg.png" /></figure><p>In the Heatmap graph, the x-axis corresponds to each sample, and the y-axis corresponds to features. We can see how it affects the prediction for each sample, but viewing all predictions at once allows us to understand how the model reacts to different features.</p><pre>shap.plots.heatmap(shap_values, max_display=12)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYSKUhLI6gRSCIAqDoOXZQ.png" /></figure><h4>Conclusion</h4><p>Throughout this blog post, we have explored the powerful and flexible features of the Shap (SHapley Additive exPlanations) library. Shap is a powerful tool that enhances the interpretability of model predictions, offering a valuable asset for data science and machine learning practitioners.</p><ul><li>Shap enhances the reliability of model predictions by making the internal workings of the model more understandable. This improves the ability to question the model’s accuracy and communicate its decisions to others.</li><li>Shap measures the impact of each feature on model predictions, helping us understand which features are more influential. This provides valuable guidance in feature engineering and model optimization processes.</li><li>Shap can help uncover potential biases that may lead to unfairness in model predictions by showing which features are important in the model’s predictions. This is crucial for fair and ethical artificial intelligence applications.</li></ul><p>However, the Shap library also has some limitations:</p><p><strong>Limitations</strong>:</p><ul><li><strong>Computational Power:</strong> Shap can be challenging in terms of computational power when used with large datasets or complex models.</li><li><strong>Complexity of Interactive Plots:</strong> The complexity of interactive plots generated by Shap may initially pose a learning curve for users.</li><li><strong>Model Dependency:</strong> Shap relies on using a derivative version of the model, so it is important for the model to be properly applied and trained.</li><li><strong>Causality:</strong> While the use of Shap can be a powerful tool in revealing internal cause-and-effect relationships within a model, it does not inherently provide insights into causal relationships. While Shap elucidates relationships between features, it underscores the need for additional data and analysis to explain the causal nature of these relationships.</li></ul><p>In conclusion, the Shap library is a powerful tool for data scientists and machine learning practitioners who want to explore, understand, and improve the inner workings of models. However, it is important for users to understand the advantages and limitations of this tool in order to obtain effective and interpretable results.</p><h4>References</h4><ul><li><a href="https://arxiv.org/abs/1705.07874">https://arxiv.org/abs/1705.07874</a></li><li><a href="https://edrone.me/blog/explainable-ai-explained">https://edrone.me/blog/explainable-ai-explained</a></li><li><a href="https://www.forbes.com/sites/elijahclark/2023/08/25/exploring-the-benefits-of-explainable-artificial-intelligence-xai-in-the-realm-of-marketing/?sh=2ca6847b36f2">https://www.forbes.com/sites/elijahclark/2023/08/25/exploring-the-benefits-of-explainable-artificial-intelligence-xai-in-the-realm-of-marketing/?sh=2ca6847b36f2</a></li><li><a href="https://medium.com/empathyco/explainability-and-understanding-in-e-commerce-the-challenge-of-xai-2361b2e161ae">https://medium.com/empathyco/explainability-and-understanding-in-e-commerce-the-challenge-of-xai-2361b2e161ae</a></li><li><a href="https://www.youtube.com/@adataodyssey">https://www.youtube.com/@adataodyssey</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f629dfa6eef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hepsiburada-data-science/explainable-ai-with-shap-6f629dfa6eef">Explainable AI With SHAP</a> was originally published in <a href="https://medium.com/hepsiburada-data-science">Hepsiburada Data Science and Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Data Science Workflows with MLflow: Exploring Use Cases and Best Practices — Part 2]]></title>
            <link>https://medium.com/hepsiburada-data-science/optimizing-data-science-workflows-with-mlflow-exploring-use-cases-and-best-practices-part-2-aad625f0e6e8?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad625f0e6e8</guid>
            <category><![CDATA[model-registry]]></category>
            <category><![CDATA[retraining]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 12:53:37 GMT</pubDate>
            <atom:updated>2023-07-07T12:53:37.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing Data Science Workflows with MLflow: Exploring Use Cases and Best Practices — Part 2</h3><h4>MLflow Model Registry for Auto Re-training in Production</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFvlW_xovcoAN4xn5C9qEA.jpeg" /></figure><h4>Content</h4><p>In the first post of our blog series, I discussed the challenges that data scientists encounter during both the development and deployment phases. I explained what <strong>MLflow</strong> is and how it offers solutions to these challenges. Additionally, I presented two scenarios where <strong>MLflow</strong> can be used, along with code samples, to assist with model selection and hyperparameter tuning during development. To access the first blog post, use this link.</p><p>In this section, I will detail the auto-retraining scenario and how it can be employed when producing models. I will also provide some tips and tricks for using <strong>MLflow</strong>, and conclude our blog series with a final section.</p><h4>Model Registry with MLflow</h4><p>In our second problem, which I previously mentioned, we needed to automatically retrain the model while it was live, version the models, regularly monitor them, and create a rollback scenario in case of problems in the live environment to quickly return to previous versions.</p><p>Logging our <strong>MLflow</strong> experiments made our job much easier. We were able to analyze all experiments from a single point. Now it was time to deploy the model that emerged as a result of these experiments. To meet this need, we decided to use <strong>MLflow’s Model</strong> <strong>and Model Registry</strong> components as a solution.</p><p><strong>Storage Format with MLflow Model</strong></p><p><strong>MLflow Model</strong> is a powerful tool for logging models with <strong>MLflow</strong>, providing a standardized file format that enables easy access to the model and its dependencies for future use. With this format, you can easily track the performance of your models over time, allowing you to make informed decisions about how to optimize them.</p><pre># MLflow Model Format<br>model/<br>├── MLmodel<br>├── model.pkl<br>├── conda.yaml<br>├── python_env.yaml<br>└── requirements.txt</pre><p><strong>Auto re-training in production with MLflow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*1QLWQDA8bMRWs4e-u1cVVA.png" /><figcaption><a href="https://building.nubank.com.br/automatic-retraining-for-machine-learning-models/">Re-training Flow</a></figcaption></figure><p>When machine learning models are deployed in a live environment, their success rate typically decreases over time. Although the reasons for this decline can vary, our focus today is on the solution: periodic model retraining. Automating this process saves time and reduces errors for data scientists.</p><p>Several scheduling tools are available for automating the retraining process, including Airflow, Prefect, and Cron Job. We create our flow through Airflow and schedule it to run monthly. On the first day of each month, the flow is triggered and runs the code block created for retraining.</p><p>When the code block runs, it retrains our model with the new training dataset and the previously determined parameters. It logs this training under the “churn_prediction_prod” experiment. If the newly trained model meets the specified metric thresholds, it replaces the live model.</p><pre>### IMPORT NECESSARY LIBRARIES ###<br><br># Define the training function<br>def train(X, y, k=5):<br>    # Set the environment variables for authentication and tracking URI<br>    os.environ[&quot;GOOGLE_APPLICATION_CREDENTIALS&quot;] = &quot;GOOGLE_APPLICATION_CREDENTIALS_PATH&quot;<br>    mlflow.set_tracking_uri(&quot;MLFLOW_TRACKING_URI&quot;)<br>    # Set the experiment name<br>    mlflow.set_experiment(&quot;churn_prediction_prod&quot;)<br>    # Define the cross-validation splitter<br>    skf = StratifiedKFold(n_splits=k, shuffle=True, random_state=13)<br>    # Initialize an empty list to store f1-score for each fold<br>    f1 = []<br>    # Start a new MLflow run<br>    with mlflow.start_run() as run:<br>        # Set the tags for the run<br>        mlflow.set_tags({&quot;Data Scientist&quot;: &quot;Data Scientist Name&quot;, <br>                         &quot;Run Reason&quot;: &quot;Re-training&quot;, <br>                         &quot;Model&quot;: &quot;XGBoost&quot;})<br>        <br>        # Set the model parameters<br>        params = {<br>            &quot;objective&quot;: &quot;binary:logistic&quot;<br>        }<br>        # Log the model parameters to the run<br>        mlflow.log_params(params)<br>        # Iterate over the folds<br>        for fold, (train_index, test_index) in enumerate(skf.split(X, y)):<br>            x_train_fold, x_test_fold = X[train_index], X[test_index]<br>            y_train_fold, y_test_fold = y[train_index], y[test_index]<br><br>            # Initialize the XGBoost model with the given parameters<br>            model = xgb.XGBClassifier(**params)<br><br>            # Fit the model on the training data<br>            model.fit(x_train_fold, y_train_fold)<br><br>            # Predict the labels on the test data<br>            y_pred_fold = model.predict(x_test_fold)<br><br>            # Compute the confusion matrix and plot it using Seaborn<br>            cm = confusion_matrix(y_test_fold, y_pred_fold, labels=model.classes_)<br>            plt.figure(figsize = (10,7))<br>            f = sns.heatmap(cm, annot=True, fmt=&#39;d&#39;)<br>            plt.savefig(f&quot;data/output/confusion-matrix-fold-{fold}.png&quot;)<br>            mlflow.log_artifact(f&quot;data/output/confusion-matrix-fold-{fold}.png&quot;)<br>            <br>            # Compute and log the evaluation metrics<br>            cr = classification_report(y_test_fold, y_pred_fold, output_dict=True)<br>            recall_0 = cr[&#39;0&#39;][&#39;recall&#39;]<br>            f1_score_0 = cr[&#39;0&#39;][&#39;f1-score&#39;]<br>            recall_1 = cr[&#39;1&#39;][&#39;recall&#39;]<br>            f1_score_1 = cr[&#39;1&#39;][&#39;f1-score&#39;]<br>            acc = accuracy_score(y_test_fold, y_pred_fold)<br>            precision = precision_score(y_test_fold, y_pred_fold, average=&#39;micro&#39;)<br>            mlflow.log_metric(&quot;accuracy_score&quot;, acc)<br>            mlflow.log_metric(&quot;precision&quot;, precision)<br>            mlflow.log_metric(&quot;recall_0&quot;, recall_0)<br>            mlflow.log_metric(&quot;f1_score_0&quot;, f1_score_0)<br>            mlflow.log_metric(&quot;recall_1&quot;, recall_1)<br>            mlflow.log_metric(&quot;f1_score_1&quot;, f1_score_1)<br><br>            # Append the f1-score to the list<br>            f1.append(f1_score(y_test_fold, y_pred_fold))<br>            mlflow.log_metric(&quot;val_f1_fold&quot;, f1_score(y_test_fold, y_pred_fold))<br>        <br>        mlflow.log_metric(&quot;val_f1_score&quot;, np.mean(f1))<br><br>        # Fit the model to the training data<br>        model = xgb.XGBClassifier()<br>        model.fit(X, y)<br>        mlflow.xgboost.log_model(model, &quot;model&quot;)<br><br># Define function to copy blob from one location to another<br>def copy_blob(bucket_name: str, blob_name: str, new_blob_name: str):<br>    storage_client = storage.Client()<br>    source_bucket = storage_client.bucket(bucket_name)<br>    source_blob = source_bucket.blob(blob_name)<br>    destination_bucket = storage_client.bucket(bucket_name)<br>    new_blob = source_bucket.copy_blob(<br>        source_blob, destination_bucket, new_blob_name)<br><br># Define function to retrieve the run ID of the best-performing experiment that meets a threshold for F1 score<br>def get_best_and_last_experiment_run_id(experiment_name: str, treshold: float):<br>    experiment = mlflow.set_experiment(experiment_name)<br>    query = f&quot;metrics.val_f1_score &gt; {treshold}&quot;<br>    df = mlflow.search_runs(experiment.experiment_id, filter_string=query, run_view_type=mlflow.entities.ViewType.ACTIVE_ONLY)<br>    last_run = df[df[&quot;start_time&quot;] == df[&quot;start_time&quot;].max()]<br>    return last_run[&quot;run_id&quot;][0]<br><br># Define function to registers a model in the MLflow model registry and transitions it to a specified stage<br>def save_model_to_registry(run_id: str, new_stage: str = &quot;Production&quot;):<br>    from mlflow.tracking import MlflowClient<br>    # Create an MlflowClient object to interact with the MLflow tracking server<br>    client = MlflowClient(tracking_uri=MLFLOW_TRACKING_URI)<br>    # Set the MLflow tracking URI to the one defined in the environment variable<br>    mlflow.set_tracking_uri(&quot;MLFLOW_TRACKING_URI&quot;)<br>    # Create the model URI based on the run ID and register the model with MLflow<br>    model_uri = f&quot;runs:/{run_id}/model&quot;<br>    model_details = mlflow.register_model(model_uri=model_uri, name=&quot;churn_prediction&quot;)<br>    <br>    # Transition the registered model&#39;s version to the new stage (e.g. Production)<br>    # and archive existing versions if necessary<br>    client.transition_model_version_stage(<br>        name=model_details.name,<br>        version=model_details.version,<br>        stage=new_stage,<br>        archive_existing_versions=True<br>    )<br>    <br># Define function to retrain the model based on new data<br>def retrain_model(features: pd.DataFrame, labels: pd.DataFrame):<br>    # Prepare data for training<br>    X = features.sort_values(by=[&quot;id&quot;]).drop(columns=[&quot;id&quot;]).to_numpy()<br>    y = (<br>        labels[[&quot;id&quot;, &quot;label&quot;]]<br>        .sort_values(by=[&quot;id&quot;])<br>        .drop(columns=[&quot;id&quot;])<br>        .astype(int)<br>        .to_numpy()<br>    )<br><br>    # Train model<br>    train(X, y, 3)<br><br>    # Retrieve the run ID of the best-performing experiment that meets a threshold for F1 score<br>    best_run_id = get_best_and_last_experiment_run_id(&quot;churn_prediction_prod&quot;, 0.8)<br><br>    # Copy the trained model to a new location<br>    bucket_name = &#39;BUCKET_NAME&#39;<br>    blob_name = f&quot;churn_prediction/prod/mlflow/{best_run_id}/artifacts/model/model.xgb&quot;<br>    new_blob_name = &quot;churn_prediction/prod/models/churn_model.xgb&quot;<br>    copy_blob(bucket_name, blob_name, new_blob_name)<br>    save_model_to_registry(best_run_id,&quot;Production&quot;)<br><br># Define main function to retrieve feature and label data and retrain the model<br>if __name__ == &quot;__main__&quot;:<br>    features = get_features()<br>    labels = get_labels()<br>    retrain_model(features, labels)</pre><p>We use the <strong>MLflow Model Registry</strong> to version and track the model. This includes which run the live model was trained on, along with the parameters and metrics used. We also archive past models and use them as a rollback scenario in case of errors in the live model.</p><p>After training the model with new data in the re-training flow, we copy the most successful and up-to-date run model that has passed certain thresholds to the GCS folder where the live model is located. There are various reasons why we use the model from the <strong>MLflow</strong> artifact.</p><p>Once we send the model to the <strong>MLflow Model Registry</strong> to version it, we label the live model as “Production” and update the current model as “Archive”. By doing so, we update the model and make it easier to follow up by versioning past and current models.</p><h4>Tips And Tricks For MLflow</h4><ol><li><strong><em>Get your experiment design straight:</em></strong><em> </em>Before you start playing with machine learning, ask yourself what you want to find out, what you’re guessing, and how you’ll measure success. This will help you design experiments that are useful and interesting.</li><li><strong><em>Git with the program:</em></strong> Use a version control system like Git to keep track of your code changes. That way, you can see what’s been done, work with others, and go back to earlier versions if something goes wrong.</li><li><strong><em>Keep track of everything:</em></strong> Use MLflow Tracking to keep a record of all the stuff that matters for each experiment. This way, you can see how your models are doing over time and compare different runs.</li></ol><h4>Conclusion</h4><p>Alright, so here’s the deal MLflow is a total powerhouse when it comes to managing machine learning workflows in production environments. It’s got a ton of cool features, like experiment tracking, model packaging, and deploying models to production. To really make the most out of <strong>MLflow</strong>, though, you’ve gotta follow some best practices. You know, stuff like version controlling your code, logging all relevant metrics and parameters, and automating your workflows. By doing all that, you can build and deploy some seriously solid and reproducible machine learning pipelines. And hey, if you’re working with a team, the <strong>MLflow Model Registry</strong> is perfect for managing and versioning all of your machine learning models. Plus, the <strong>MLflow Tracking API</strong> and Explainability library make it super easy to keep tabs on your model’s performance and interpretability. So yeah, with all of these tools and best practices, organizations can seriously crank up their machine learning development cycles, increase collaboration, and keep their machine learning models in production looking top-notch.</p><h4><strong>References</strong></h4><ul><li><a href="https://mlflow.org/">https://mlflow.org/</a></li><li><a href="https://github.com/hyperopt/hyperopt">https://github.com/hyperopt/hyperopt</a></li><li><a href="https://xgboost.readthedocs.io/en/stable/">https://xgboost.readthedocs.io/en/stable/</a></li><li><a href="https://lightgbm.readthedocs.io/en/v3.3.2/">https://lightgbm.readthedocs.io/en/v3.3.2/</a></li><li><a href="https://cloud.google.com/storage/docs/copying-renaming-moving-objects">https://cloud.google.com/storage/docs/copying-renaming-moving-objects</a></li></ul><p><em>If you want to see more article, click the </em><a href="https://medium.com/hepsiburada-data-science"><em>link</em></a><em> to see our other articles.</em></p><p><em>If you like what we do, click the </em><a href="https://www.linkedin.com/company/hepsiburada/"><em>link</em></a><em> to see the opportunities.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0IC-fwfIVBlNWWamf5Hmg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad625f0e6e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hepsiburada-data-science/optimizing-data-science-workflows-with-mlflow-exploring-use-cases-and-best-practices-part-2-aad625f0e6e8">Optimizing Data Science Workflows with MLflow: Exploring Use Cases and Best Practices — Part 2</a> was originally published in <a href="https://medium.com/hepsiburada-data-science">Hepsiburada Data Science and Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Data Science Workflows with MLflow: Exploring Use Cases and Best Practices — Part 1]]></title>
            <link>https://medium.com/hepsiburada-data-science/mlflow-in-production-at-hepsiburada-8dbd10f1e7af?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dbd10f1e7af</guid>
            <category><![CDATA[experiment-tracking]]></category>
            <category><![CDATA[model-registry]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 13:08:17 GMT</pubDate>
            <atom:updated>2023-06-21T13:08:17.854Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing Data Science Workflows with MLflow: Exploring Use Cases and Best Practices — Part 1</h3><h4>MLflow Tracking for Model Selection and Hyperparameter Tuning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*Xq385dWU0Nd305g6MOKwDQ.png" /></figure><h4>Content</h4><p>In this blog post, I will discuss some of the challenges that data scientists face in the machine learning workflow and how <strong>MLflow</strong> offers solutions to these problems. The article will be divided into two parts.</p><ul><li>In the first part, I will demonstrate how the <strong>MLflow</strong> monitoring component is used in the model selection and hyperparameter tuning stages, and provide code block examples for these scenarios.</li><li>In the second part, I will demonstrate how to use the <strong>MLflow Model Registry</strong> component in the automatic retraining phase. I will cover how to version the models and monitor the parameters in production. To support these concepts, I will include a code block similar to the one in the first section.</li></ul><h3>What is our problem and what do we need?</h3><p>As data scientists, we often use the trial-and-error method during the model development phase to find the most successful model. We try different datasets, models, model parameters, and similar variables by trial and error. However, it is difficult to determine which variable affects the model’s success and how much during these trials. Creating separate notebooks for each experiment is an option, but it is not very useful and not maintainable with the increasing number of experiments, features and different models.</p><p>Furthermore, in large projects, it is common for multiple data scientists to work simultaneously. During the model development phase, this creates inefficiencies as both data scientists try to develop the same parameters and models. They must see which models and parameters the other data scientist has tried and design their experiments accordingly.</p><p>Another challenge arises when we need to retrain the model while it is in production and track its results. It is also important to version the models and have a rollback plan.</p><p>To address these problems, we identified two key needs:</p><ul><li>The ability to track the models, parameters, and metrics trained by both data scientists from a single point, and easily select the most successful model and parameters.</li><li>The ability to track the results of the model during automatic retraining in production, to version the trained models and create rollback scenarios and monitor the metrics and parameters for deployment and rollback scenarios.</li></ul><p>To address these problems, we typically rely on two concepts: <strong>Experiment Tracking</strong> and <strong>Model Registry</strong>.</p><h4><strong>What is MLflow?</strong></h4><p>According to its official documentation, <strong>MLflow</strong> is an open-source platform that helps manage the end-to-end Machine Learning lifecycle. It consists of four components:</p><p><strong>MLflow Tracking</strong></p><ul><li>Logs model metadata (source code location, dependencies, etc.), parameters, metrics, and artifacts during model training.</li><li>Used to compare the results of different trainings.</li></ul><p><strong>MLflow Projects</strong></p><ul><li>Enables sharing of machine learning code with other data scientists, making it reusable when going into production (think of it like Docker compose).</li></ul><p><strong>MLflow Models</strong></p><ul><li>Establishes a usable standard for deploying the machine learning model in different service environments.</li></ul><p><strong>MLflow Model Registry</strong></p><ul><li>Allows managing the origin of the trained model (MLflow Experiment and run), the version of the model, staging, production, archive, and annotations.</li></ul><p>For our purposes, we will be using <strong>Tracking</strong>,<strong> Model </strong>and<strong> Model Registry</strong> components. In the following sections, we will detail how we use these components according to our needs.</p><h4>How runs and artifacts are recorded?</h4><p>There are various methods for deploying <strong>MLflow</strong>, including Local, On-prem, and Cloud. To meet our needs, <strong>MLflow</strong> must be structured in a way that is accessible by two data scientists on a remote server. Therefore, we have made <strong>MLflow</strong> available using the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgAiSK91ABtEJRFhVqsQyg.png" /><figcaption><a href="https://mlflow.org/docs/latest/tracking.html#scenario-5-mlflow-tracking-server-enabled-with-proxied-artifact-storage-access">Scenario.5</a></figcaption></figure><p>Instead of using an on-prem server, we have launched <strong>MLflow on Google Kubernetes Engine</strong> as a remote server. We are using <strong>SQLlite</strong> as the Backend Store, which stores runs, metrics, parameters, and tags, requiring minimal storage space. However, artifacts such as models and images can take up GB in some cases, so we decided to store them on <strong>Google Cloud Storage</strong> to avoid dealing with continuous capacity increases.</p><h4>Experiment Tracking with MLflow</h4><p>We are collaborating on an experiment using <strong>MLflow</strong>. To distinguish between different environments, we have created three experiments for development, release and production:</p><pre>🧠<br><strong><em>Template:</em></strong> <em>project_name_environment</em><br><strong><em>Example:</em></strong> <em>churn_prediction_dev</em></pre><p>Currently, we are in the development phase and are logging model trainings under the development experiment. When creating the experiment, we also provide the artifact location as a parameter. We store artifacts for different environments in separate directories as follows:</p><pre>🧠<br><strong><em>Template:</em></strong> <em>gs://bucket_name/project_name/environment/mlflow/</em><br><strong><em>Example:</em></strong> <em>gs://gcp_bucket/churn_prediction/dev/mlflow/</em></pre><p>You can create experiments in <strong>MLflow</strong> using Python with the following code:</p><pre>mlflow.create_experiment(&quot;churn_prediction_dev&quot;, artifact_location=&quot;gs://gcp_bucket/churn_prediction/dev/mlflow/&quot;)</pre><p><strong>Model Selection</strong></p><p>One of our main problems is that two different data scientists are trying models on different notebooks, but it is difficult to determine which one is the best. To address this problem, we can use <strong>MLflow</strong> to log important information during the training phase. By adding <strong>MLflow</strong> to our training function, we can record details such as the hyperparameters used, the evaluation metrics, and the version of the code used to train the model.</p><p>This approach has several advantages.</p><ul><li>It allows us to easily examine the logs from a single point and compare the performance of different models. This can help us to identify which model produced the best results and which features were most effective in achieving those results.</li><li>It provides a way to reproduce experiments and results at a later time, as all the necessary information is stored in the logs. This can be especially useful when trying to replicate a study or share results with others.</li></ul><p>In addition, <strong>MLflow</strong> allows us to visualize the results of our experiments in a user-friendly way, making it easier to interpret and communicate the results to others. This can be particularly helpful in collaborative projects where multiple team members are involved.</p><pre>### IMPORT NECESSARY LIBRARIES ###<br><br># Define a function that trains a LightGBM classifier using stratified k-fold cross-validation and logs the training metrics to MLflow<br>def train(X, y, k=5):<br>    <br>    # Set the path to the Google application credentials file<br>    os.environ[&quot;GOOGLE_APPLICATION_CREDENTIALS&quot;] = &quot;GOOGLE_APPLICATION_CREDENTIALS_PATH&quot;<br><br>    # Set the MLflow tracking URI<br>    mlflow.set_tracking_uri(&quot;MLFLOW_TRACKING_URI&quot;)<br><br>    # Set the MLflow experiment name<br>    mlflow.set_experiment(&quot;churn_prediction_dev&quot;)<br><br>    # Initialize lists to store the training and validation metrics for each fold<br>    val_f1_list = []<br>    train_f1_list = []<br><br>    # Initialize a LightGBM classifier<br>    model = LGBMClassifier(objective=&quot;multiclass&quot;, random_state=42)<br><br>    # Initialize a stratified k-fold cross-validator<br>    skf = StratifiedKFold(n_splits=k, shuffle=True, random_state=42)<br><br>    # Auto log all MLflow entities<br>    mlflow.lightgbm.autolog()<br><br>    # Write the column names to a text file<br>    with open(&#39;column_names.txt&#39;, &#39;w&#39;) as f:<br>        f.write(&#39;\n&#39;.join(X.columns))<br><br>    # Train the model<br>    with mlflow.start_run() as run:<br>        # Set tags for the run<br>        mlflow.set_tags({&quot;Data Scientist&quot;: &quot;Data Scientist Name&quot;, <br>                        &quot;Run Reason&quot;: &quot;Model Selection&quot;, <br>                        &quot;Model&quot;: &quot;LightGBM&quot;})<br><br>        # Train and validate the model for each fold<br>        for fold, (train_index, val_index) in enumerate(skf.split(X, y)):        <br>            # Split the data into training and validation sets<br>            X_train, y_train = X.iloc[train_index], y.iloc[train_index]<br>            X_val, y_val = X.iloc[val_index], y.iloc[val_index]<br><br>            # Fit the model to the training data and validate it on the validation data<br>            model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose = False)<br>            <br>            # Compute the f1 score for the training data<br>            y_train_pred = model.predict(X_train)<br>            train_f1 = f1_score(y_train, y_train_pred)<br><br>            # Compute the f1 score for the validation data<br>            y_val_pred = model.predict(X_val)<br>            val_f1 = f1_score(y_val, y_val_pred)<br><br>            # Log the metrics for the current fold<br>            mlflow.log_metric(&quot;train_f1_fold&quot;, train_f1)<br>            mlflow.log_metric(&quot;val_f1_fold&quot;, val_f1)<br><br>            # Append the f1 scores to the lists for each fold<br>            val_f1_list.append(val_f1)<br>            train_f1_list.append(train_f1)<br>        <br>        # Log the column names file as an artifact<br>        mlflow.log_artifact(&quot;column_names.txt&quot;)<br>        <br>        # Compute and log the average f1 scores for training and validation data<br>        mlflow.log_metric(&quot;val_f1_avg&quot;, np.mean(val_f1_list))<br>        mlflow.log_metric(&quot;train_f1_avg&quot;, np.mean(train_f1_list))<br><br># Define a function that converts the input data to NumPy arrays and calls the &#39;train&#39; function to train the model<br>def train_model(features: pd.DataFrame, labels: pd.DataFrame):<br><br>    # Convert the features and labels dataframes to NumPy<br>    X = features.sort_values(by=[&quot;id&quot;]).drop(columns=[&quot;id&quot;]).to_numpy()<br>    y = (<br>        labels[[&quot;id&quot;, &quot;label&quot;]]<br>        .sort_values(by=[&quot;id&quot;])<br>        .drop(columns=[&quot;id&quot;])<br>        .astype(int)<br>        .to_numpy()<br>    )<br><br>    train(X, y, 3)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    features = get_features()<br>    labels = get_labels()<br><br>    train_model(features, labels)</pre><p><strong>Hyperparameter Tuning</strong></p><p>As i mentioned, once we have selected a model for our machine learning task, the next step is to optimize its performance by tuning its hyperparameters. This is often a challenging and time-consuming process, as there are usually many possible combinations of hyperparameters to try, and it’s not always clear which ones are likely to work best.</p><p>To make this process more efficient, we can use the <strong>Hyperopt</strong> library. <strong>Hyperopt</strong> is a Python library that provides a flexible and easy-to-use interface for performing hyperparameter optimization. The beauty of <strong>Hyperopt</strong> is that it can automatically try different combinations of hyperparameters and evaluate the performance of the resulting models.</p><p>In addition to finding the best parameters, <strong>Hyperopt</strong> also allows us to log the parameter settings and corresponding performance metrics using <strong>MLflow</strong>. This enables us to keep track of our experiments, reproduce our results, and analyze the impact of different hyperparameters on the model’s performance.</p><p>Overall, using <strong>Hyperopt with MLflow</strong> can help us find the most successful parameters for our model more efficiently and systematically, ultimately leading to better performance and more accurate predictions.</p><pre>### IMPORT NECESSARY LIBRARIES ###<br><br># Set the path to the Google Cloud service account credentials<br>os.environ[&quot;GOOGLE_APPLICATION_CREDENTIALS&quot;] = &quot;GOOGLE_APPLICATION_CREDENTIALS_PATH&quot;<br><br># Set the MLflow tracking URI<br>mlflow.set_tracking_uri(&quot;MLFLOW_TRACKING_URI&quot;)<br><br># Set the experiment name<br>mlflow.set_experiment(&quot;EXPERIMENT_NAME&quot;)<br><br># Get features and labels<br>features = get_features()<br>labels = get_labels()<br><br># Prepare the data for training and testing<br>X = features.sort_values(by=[&quot;id&quot;]).drop(columns=[&quot;id&quot;]).to_numpy()<br>y = (<br>    labels[[&quot;id&quot;, &quot;label&quot;]]<br>    .sort_values(by=[&quot;id&quot;])<br>    .drop(columns=[&quot;id&quot;])<br>    .astype(int)<br>    .to_numpy()<br>)<br><br># Split the data into train and test sets<br>train_x, test_x, train_y, test_y = train_test_split(X, y, stratify=y, test_size=0.33, random_state=42)<br><br># Define the evaluation function<br>def evaluate(y, pred):<br>    cr = classification_report(y, pred, output_dict=True)<br>    recall_0 = cr[&#39;0&#39;][&#39;recall&#39;]<br>    f1_score_0 = cr[&#39;0&#39;][&#39;f1-score&#39;]<br>    recall_1 = cr[&#39;1&#39;][&#39;recall&#39;]<br>    f1_score_1 = cr[&#39;1&#39;][&#39;f1-score&#39;]<br>    acc = accuracy_score(y, pred)<br>    precision = precision_score(y, pred, average=&#39;micro&#39;)<br><br>    return recall_0, f1_score_0, recall_1, f1_score_1, acc, precision<br><br># Define the objective function for hyperparameter tuning<br>def objective(params):<br>    with mlflow.start_run():<br>        mlflow.set_tags({&quot;Data Scientist&quot;: &quot;Data Scientist Name&quot;,<br>                         &quot;Run Reason&quot;: &quot;Hyperparameter Tuning&quot;,<br>                         &quot;Model&quot;: &quot;XGBoost&quot;})<br>        mlflow.log_params(params)<br><br>        # Train the XGBoost classifier with the given hyperparameters<br>        lr = xgb.XGBClassifier(n_estimators=params[&#39;n_estimators&#39;],<br>                               max_depth=int(params[&#39;max_depth&#39;]),<br>                               learning_rate=params[&#39;learning_rate&#39;],<br>                               gamma=params[&#39;gamma&#39;],<br>                               min_child_weight=params[&#39;min_child_weight&#39;],<br>                               subsample=params[&#39;subsample&#39;],<br>                               colsample_bytree=params[&#39;colsample_bytree&#39;])<br>        lr.fit(train_x, train_y)<br><br>        # Make predictions on the test set<br>        pred = lr.predict(test_x)<br><br>        # Evaluate the predictions<br>        recall_0, f1_score_0, recall_1, f1_score_1, acc, precision = evaluate(test_y, pred)<br><br>        # Log evaluation metrics<br>        mlflow.log_metric(&quot;accuracy_score&quot;, acc)<br>        mlflow.log_metric(&quot;precision&quot;, precision)<br>        mlflow.log_metric(&quot;recall_0&quot;, recall_0)<br>        mlflow.log_metric(&quot;f1_score_0&quot;, f1_score_0)<br>        mlflow.log_metric(&quot;recall_1&quot;, recall_1)<br>        mlflow.log_metric(&quot;f1_score_1&quot;, f1_score_1)<br><br>        # Calculate the loss based on the F1 score<br>        f1 = f1_score(test_y, pred)<br>        loss = 1 - f1<br><br>    return {&#39;loss&#39;: loss, &#39;status&#39;: STATUS_OK}<br><br># Define the hyperparameter search space<br>space = {<br>    &#39;max_depth&#39;: hp.choice(&#39;max_depth&#39;, range(5, 30, 1)),<br>    &#39;learning_rate&#39;: hp.quniform(&#39;learning_rate&#39;, 0.01, 0.5, 0.01),<br>    &#39;n_estimators&#39;: hp.choice(&#39;n_estimators&#39;, range(20, 205, 5)),<br>    &#39;gamma&#39; : hp.quniform(&#39;gamma&#39;, 0, 0.50, 0.01),<br>    &#39;min_child_weight&#39; : hp.quniform(&#39;min_child_weight&#39;, 1, 10, 1),<br>    &#39;subsample&#39; : hp.quniform(&#39;subsample&#39;, 0.1, 1, 0.01),<br>    &#39;colsample_bytree&#39; : hp.quniform(&#39;colsample_bytree&#39;, 0.1, 1.0, 0.01)}<br><br># Perform hyperparameter tuning using TPE algorithm<br>best_result = fmin(<br>    fn=objective,<br>    space=space,<br>    algo=tpe.suggest,<br>    max_evals=10,<br>    trials=Trials()<br>)</pre><h4>Conclusion</h4><p><strong>MLflow</strong> is a comprehensive platform for managing end-to-end machine learning workflows. In this post, we explored its purpose, usage, deployment options, and experiment tracking capabilities. We learned <strong>MLflow</strong> enables data scientists to track and log experiments, compare different runs, and integrate experiment tracking into workflows.</p><p>In the upcoming second part of our blog post, we will delve into another powerful feature of <strong>MLflow</strong>: the model registry’s capability for auto retraining. We will explore how <strong>MLflow</strong> enables automated retraining of models based on specified triggers or schedules, ensuring optimal performance in dynamic environments.</p><p>By leveraging <strong>MLflow’s</strong> extensive capabilities, data scientists can streamline their machine learning pipelines and increase productivity. Stay tuned for the next part of our blog post, where we will explore the exciting world of auto retraining using the <strong>MLflow Model Registry.</strong></p><h4>References</h4><ul><li><a href="https://mlflow.org/">https://mlflow.org/</a></li><li><a href="https://github.com/hyperopt/hyperopt">https://github.com/hyperopt/hyperopt</a></li><li><a href="https://xgboost.readthedocs.io/en/stable/">https://xgboost.readthedocs.io/en/stable/</a></li><li><a href="https://lightgbm.readthedocs.io/en/v3.3.2/">https://lightgbm.readthedocs.io/en/v3.3.2/</a></li><li><a href="https://cloud.google.com/storage/docs/copying-renaming-moving-objects">https://cloud.google.com/storage/docs/copying-renaming-moving-objects</a></li></ul><p><em>If you want to see more article, click the </em><a href="https://medium.com/hepsiburada-data-science"><em>link</em></a><em> to see our other articles.</em></p><p><em>If you like what we do, click the </em><a href="https://www.linkedin.com/company/hepsiburada/"><em>link</em></a><em> to see the opportunities.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0IC-fwfIVBlNWWamf5Hmg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dbd10f1e7af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hepsiburada-data-science/mlflow-in-production-at-hepsiburada-8dbd10f1e7af">Optimizing Data Science Workflows with MLflow: Exploring Use Cases and Best Practices — Part 1</a> was originally published in <a href="https://medium.com/hepsiburada-data-science">Hepsiburada Data Science and Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Monty Hall Problem]]></title>
            <link>https://hakanateslii.medium.com/the-monty-hall-problem-7c08adb1c66e?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c08adb1c66e</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[monty-hall-problem]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Tue, 23 May 2023 14:13:24 GMT</pubDate>
            <atom:updated>2023-05-23T14:13:24.437Z</atom:updated>
            <content:encoded><![CDATA[<p>Many people have heard of the Monty Hall Problem, either from personal experience or from the famous scene in the movie “21” (Blackjack). In this article, we will attempt to explain the problem so that you can understand it even if you’ve never heard of it before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*3w1pi7nRKZPwFZBK-8Af7Q.jpeg" /><figcaption><a href="https://paulvanderlaken.com/2020/04/14/simulating-visualizing-monty-hall-problem-python-r/">Image</a></figcaption></figure><p>The Monty Hall Problem originated from the American game show “<em>Let’s Make a Deal</em>” during the 1960s-1970s and was named after the show’s host, <em>Monty Hall</em>. For a more detailed look at the problem’s history, you can visit <a href="https://evrimagaci.org/monty-hall-problemi-nedir-yarismada-kapi-veya-kutu-tercihini-degistirmek-kazanma-ihtimalini-neden-iki-katina-cikarir-2742">this</a> website.</p><p>The problem can be summarized as follows: you are in a competition with three doors in front of you. Behind one door is a car, and behind the other two doors are goats. The host asks you to choose a door, and you choose one (for example, the 1st door). The host then opens a door that you did not choose and <strong>reveals that there is a goat behind it </strong>(for example, the 3rd door). The host then asks you, “Would you like to choose the 2nd door?” Would you change your choice?</p><p>Let’s go a little deeper…</p><p>Let’s start with a simple question. There are three doors in front of us, and behind one of them, there is a car. What are our chances of choosing the door with the car? Of course, it’s one in three or 33.3%.</p><p>Now consider this: Monty Hall doesn’t know what’s behind the doors and opens one of them <strong>randomly</strong>. Let’s say there is a goat behind the door he opened. In other words, two doors remain, one with the car and the other with a goat. How likely are you to choose the door with the car in this situation? Would changing your choice increase your chances? <strong>No, it would not.</strong> The probability of choosing the door with the car is 50% because all choices are <strong>completely random</strong>. The car could be behind the door that Monty Hall had opened.</p><p>I’m highlighting <strong><em>randomness</em></strong> because that’s where the crux of the problem lies. In our problem, Monty Hall knows what is behind the doors, and there is definitely a goat behind the door he opens. In randomness, the probabilities depend on the situation at the time you made the choice. Since the random opening of the door does not provide any information for your next choice, the probabilities will change depending on the number of doors remaining for your later choice.</p><p>So, why does it matter if the host knows what’s behind the doors? This is exactly what turns the problem into a probability problem instead of a logic one. Let’s say you chose door 1. Monty <strong>non-randomly </strong>opened the third door with the goat behind it. If you switch to the 2nd door, your probability of winning the car is now 66.6%.</p><p>Let’s modify the question slightly and try to understand it better. Suppose you choose one of the three doors again. However, this time, before opening the door, Monty asks you, “Would you like to switch your choice to the other two doors instead?” If you answer “Yes” to Monty’s question in this scenario, your chances of winning the car, which were initially 1/3, will suddenly increase to 2/3. Although the phrasing of the questions is different, the underlying logic is the same. How does it work?</p><p>We know that there is definitely a goat behind one of the two doors you chose in question 2. In the first question, our chances are exactly the same as choosing 2 doors, because we know that there is definitely a goat behind the door that Monty opens.</p><p>Do you still have questions? If so, let’s try this…</p><p>I have listed all the potential scenarios that we may encounter in the competition in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*F3LIpUl1cAihy3yywJARyw.png" /></figure><p>As shown in the table, changing our chances doubles, meaning they increase to 66.6%.</p><p>At this stage, I would like to mention another common mistake people make. Even though our chances of winning the car increase to 66.6%, <strong>it doesn’t mean we have won the car.</strong> Our probability of winning the car remains at 66.6%. As the table clearly shows, if we change our choice, there is still a 33.3% probability that the car is behind the door we initially picked.</p><p>To see the Monty Hall Problem experimentally, you can play a game on the New York Times website for a fee. Access the game through this <a href="https://www.nytimes.com/2008/04/08/science/08monty.html">link</a>.</p><h3><em>References</em></h3><ul><li>C. Wheelan. (2018). Naked Statistics<em> sf.149–154</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c08adb1c66e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Segmentation for Financial Services]]></title>
            <link>https://medium.com/analytics-vidhya/customer-segmentation-for-financial-services-58fbfc417669?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/58fbfc417669</guid>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Mon, 30 Aug 2021 22:34:57 GMT</pubDate>
            <atom:updated>2021-09-06T06:14:17.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IWOp6nK2KxAQsHUG.jpg" /></figure><p>This is a blog post for a technical audience summarising my work on the final capstone project of the Udacity’s Data Scientist Nanodegree.</p><p>Customer Segmentation is the process of dividing customers into groups based on common characteristics so companies can market to each group effectively and appropriately. Customers are segmented according to their similarities in behavior and habits.</p><p>In this project, I will analyze demographics data for customers of a mail-order sales company in Germany, comparing it against demographics information for the general population. I’ll use unsupervised learning techniques to perform customer segmentation, identifying the parts of the population that best describe the core customer base of the company. Then, I’ll apply what you’ve learned on a third dataset with demographics information for targets of a marketing campaign for the company, and use a model to predict which individuals are most likely to convert into becoming customers for the company.</p><p>Blog Sections:</p><ul><li>Business Case</li><li>Data Exploration And Preprocessing</li><li>Unsupervised Model</li><li>Supervised Model</li><li>Result-Conclusion</li><li>References</li></ul><h3>1- Business Case</h3><p>The main goal of every company is to find the right customers. Finding the right customer group leads the company to profitability in terms of both marketing expenses and sales returns. In this project, I aim to find the right customer base by comparing the demographic data of existing customers and people in Germany.</p><h3>2- Data Exploration And Preprocessing</h3><h4>Data File</h4><ul><li>Udacity_AZDIAS_052018.csv: Demographics data for the general population of Germany; 891 211 persons (rows) x 366 features (columns).</li><li>Udacity_CUSTOMERS_052018.csv: Demographics data for customers of a mail-order company; 191 652 persons (rows) x 369 features (columns).</li></ul><p>Along with the data, two files describing the data were provided:</p><ul><li>DIAS Attributes — Values 2017.xlsx: a data dictionary of the columns including description, possible values, and what the values mean.</li><li>DIAS Information Levels — Attributes 2017.xlsx: indicates the information level for each column (Person, Household, Building, etc)</li></ul><p>We will use these two files both when processing the missing data in the data preprocessing stage and when analyzing the model results.</p><h4>Dtype Warning</h4><p>Columns ‘CAMEO_DEUG_2015’, ‘CAMEO_DEUINTL_2015’ in both datasets contained both string and integer values. Also, the values that should be nan were defined as ‘X’. I got rid of these and made these two columns error free.</p><h4>Missing Value</h4><p>When we examined the datasets, we found the column numbers without missing data as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kj0EowupdMvFTE1a2DhKGw.png" /></figure><p>Only 25% of the dataset has all columns filled. You can examine a portion of the remaining 75% from the graph you see below. We can clearly see that there is almost no data in the ALTER columns. But there is one more step we need to solve in the missing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*RopxRZCb6YCakGmFmVz-RA.png" /></figure><p>By examining the Attribute files, we found which columns contain unknown values and replaced these columns with NaN values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Ga8pqfiMHQQ-s-tesQ4n_Q.png" /></figure><p>As can be seen in the graph, the actual number of missing data is quite high compared to its original state.</p><p>Now that we have found the actual number of records, we can examine the missing data rates for each column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXRcI5m0FRAjixkpqIcnTw.png" /></figure><p>We drop the columns with more than 75% missing data in the dataset. In the literature, this ratio is 2/3.</p><p>Most rows have less than 50 missing values. So 50 is a good threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*NfVbJOKn5FK0XlLQU8R0rw.png" /></figure><p>So if the number of missing columns of a row is less than 50, I deleted that row.</p><h4>Categorical Data</h4><p>We have columns containing 4 categorical data:</p><ul><li>D19_LETZTER_KAUF_BRANCHE — Indicates the last purchase sector.</li><li>CAMEO_DEU_2015 — Indicates the special group it belongs to.</li><li>EINGEFUEGT_AM — Data insert date.</li><li>OST_WEST_KZ — Flag indicating the former GDR/FRG.</li></ul><p>Since the CAMEO_DEU_2015 and D19_LETZTER_KAUF_BRANCHE columns contain very detailed information, we will abandon these columns to simplify our model.</p><p>Using only the year column in the EINGEFUEGT_AM column is a good way to simplify our model.</p><p>The OST_WEST_KZ column seems quite reasonable for encoding.</p><h4>Imputing Data</h4><p>Until we got to this stage, we deleted many columns and lost data. But there are still missing data as seen in the chart above. Now it’s time to fill in this data. Missing data are usually filled in with the mean or most common values.</p><p>We filled in our missing data by assigning the most common data, which is the most appropriate method for demographic data.</p><p>And now we no longer have any missing value.</p><h4>Standardizing Data</h4><p>There is one last step left to complete the data preprocessing step. In order for our model not to be affected by different values, we compressed all values between [-1,1] with the standardization method. Thus, the model will not be affected by the very large or very small values of the data.</p><h3>3- Unsupervised Model</h3><p>We used unsupervised learning techniques to describe the relationship between the demographics of the company’s current customers and the general population of Germany.</p><h4>Dimentionality Reduction</h4><p>Principal Component Analysis (PCA) was performed because of the large number of features and the fact that many of them provide almost the same information. For the customer segmentation task, a clustering algorithm will be used and they run very slowly with large numbers of features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAHna0-UsoKS_2rIIQkXLg.png" /></figure><p>From the cumulative variance explained graph, it was determined that at 95% the gain in explained variance levels off. This occurs at 194 principal components.</p><h4>PCA Interpretation</h4><p><strong>First Principial Component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZJqek2ts2eGKshbyzroKA.png" /></figure><p>Highest:</p><ul><li>PLZ8_ANTG3 is number of 6–10 family houses in the PLZ8 (3 = high share)</li><li>KBA13_ANTG3 is number of 6–10 family houses in the cell (3 = high share of 6–10 family homes)</li><li>KBA13_ANTG4 is number of &gt;10 family houses in the cell (2 = high share of &gt;10 family homes)</li></ul><p>Lowest:</p><ul><li>KBA13_ANTG1 is number of 1–2 family houses in the cell (4 = very high share of 1–2 family homes)</li><li>PLZ8_ANTG1 is number of 1–2 family houses in the PLZ8 (1 = very high)</li><li>MOBI_REGIO is mobility patterns (1 = very high)</li></ul><p><strong>1.Principial Component is an indicator of the number of share family in the house.</strong></p><p><strong>Second Principial Component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDoqYRh5BfKqLAKKBSB7pQ.png" /></figure><p>Highest:</p><ul><li>KBA13_HERST_BMW_BENZ is share of BMW &amp; Mercedes Benz within the PLZ8 (5 = very high)</li><li>KBA13_MERCEDES is share of MERCEDES within the PLZ8 (5 = very high)</li><li>KBA13_SEG_OBEREMITTELKLASSE is share of upper middle class cars and upper class cars (BMW5er, BMW7er etc.) (5 = very high)</li></ul><p>Lowest:</p><ul><li>KBA13_SEG_KLEINWAGEN is share of small and very small cars (Ford Fiesta, Ford Ka etc.) in the PLZ8 (5 = very high)</li><li>KBA13_KMH_140_210 is share of cars with max speed between 140 and 210 km/h within the PLZ8 (5 = very high)</li><li>KBA13_SITZE_5 is number of cars with 5 seats in the PLZ8 (5 = very high)</li></ul><p><strong>2.Principial Component is obviously an indicator of Cars related properties.</strong></p><h4>K-MEANS Algorithm</h4><p>K-means is a centroid-based algorithm, or a distance-based algorithm, where we calculate the distances to assign a point to a cluster. In K-Means, each cluster is associated with a centroid.</p><p>The main objective of the K-Means algorithm is to minimize the sum of distances between the points and their respective cluster centroid.</p><p><strong>Number of Cluster</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6dDfwCLYA_2mWGJISPVIQ.png" /></figure><p>To determine the optimal number of clusters, the elbow method was used. The average within-cluster distance across variance k clusters were calculated and plotted. It was determined that 7 clusters would be a good starting point.</p><p><strong>Cluster Comparison</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*rY0739zz_ehA-UtP2EgtVA.png" /></figure><p>As seen in the graph, clusters 0, 1and 2 are under-represented clusters. In other words, they are the clusters with the least potential to become customers in the future. Clusters 3, 4, 5, and 6 are multi-representational sets. These are the clusters with the highest potential to become customers in the future.</p><p>The first 3 components of cluster 3:</p><p>[ 3.39913675, 0.24727438, -3.84673168]</p><p>According to the information we obtained from the first 2 components, the 3rd cluster represents a segment that has a high number of family houses and gets on luxury vehicles. Also, according to the information we obtained from the 3rd Component, we can see that there is an elderly group.</p><p>The first 3 components of cluster 5:</p><p>[-5.50107478, -0.98508396, 3.804263 ]</p><p>According to the information we obtained from the first 2 components, the 5th cluster represents a segment where the number of family residences is low and who rides vehicles in the lower segment. Also, when we look at the 3rd Component, we can see that it is mostly a young cluster and they are not financially prepared.</p><h3>4- Unsupervised Model</h3><h4>Evaluation Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*mbb-eAV-PJ1uyzSucj86aA.png" /></figure><p>The class label distribution is highly imbalanced, in this particular binary classification problem there are 42,430 observations with label ‘0’ and only 532 observations with label ‘1’. For this problem, we need to be able to tell whether a person will be a future possible customer. AUROC metric which considers both true positive rate and false positive rate seem to be a good choice for this problem, since we want to be able to correctly predict both cases i.e. whether a person becomes a customer or not. Since, both these predictions are important for us.</p><p>For this reason, Area Under Receiver Operating Characteristic (AUROC), has been selected as an evaluation metric. The AUROC gives an idea about overall performance of the model, where the curve is created by plotting True positive rate and False positive rate under different threshold settings. A good performing model will have<br>an AUROC of 1. So higher the AUROC better the performance of the model.</p><h4>Choosing Model</h4><p>After setting the evaluation model, the data has been scaled with the standard scaler and is split into training and validation split. Different algorithms have been trained on the training split and have been evaluated on validation split. The algorithms that have been selected for this step are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_jE-FBecGIMwYe5AI01Uw.png" /></figure><p>As seen in the graph, when we look at the time-success values, we can see that the best model is Gradient Boost. The difference in time value is within an acceptable range.</p><p>In Gradient Boosting, each predictor tries to improve on its predecessor by reducing the errors. But the fascinating idea behind Gradient Boosting is that instead of fitting a predictor on the data at each iteration, it actually fits a new predictor t<em>o the residual errors made by the previous predictor.</em></p><h4>Hyperparameter Tuning</h4><p>Gradient Boost classifiers have been tuned with the help of a Grid Search. A set of hyperparameters have been selected for tuning and Grid Search has been performed for to determine the best performing model.</p><p>The best classifier has the following hyperparameters and score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*5WjT7QVNJgYqURob_db_rQ.png" /></figure><p>The score calculated over training set using parameterized model is unsignificantly higher then default model (0.773 vs 0.758).</p><p>The feature importances plot demonstrates that the most important feature is D19_SOZIALES, for which description unfortunately is not available. The next important features relate to consumption type (EINGEFUEGT_AM_YEAR) and year of movement EXTSEL992 (information not available).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*L-qVxCkGbfO_RlJZawU7Pw.png" /></figure><h3>5- Result-Conclusion</h3><ul><li>In the first part, data evaluation and data preprocessing were performed. As in every data science project, we had a hard time in the data preprocessing phase. Some of the reasons we struggled: There were too many features and observations, some features were unexplained, some features had less missing data than they should have been.</li><li>In the unsupervised part, dimensionality reduction was made using PCA to 194 latent features describing 95% of the explained variance. PCA was useful and it was good to see that the first three key components were able to distinguish seven clusters effectively.</li><li>Finally, the Gradient Boosting Classifier was selected and parameterized to build the supervised model and make predictions on the test dataset on KAGGLE. The resulting performance of the supervised learning algorithm is 77.3%.</li></ul><p>Code for this analysis can be found in its <a href="https://github.com/hakanatesli/Customer-Segmentation-Report-for-Arvato-Financial-Services">Github repo</a>.</p><h3>6- Kaggle Competition</h3><p>The best performing model (Gradient Boosting Classifier) was used to predict the response variable. These probabilities were then submitted to Kaggle and as of writing this, the score puts me in 161. place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFGQ_kBvr7teqL-YWQejrg.png" /></figure><h3>7- References</h3><ul><li><a href="https://pub.towardsai.net/principal-component-analysis-pca-with-python-examples-tutorial-67a917bae9aa">https://pub.towardsai.net/principal-component-analysis-pca-with-python-examples-tutorial-67a917bae9aa</a></li><li><a href="https://github.com/pranaymodukuru/Bertelsmann-Arvato-customer-segmentation">https://github.com/pranaymodukuru/Bertelsmann-Arvato-customer-segmentation</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html</a></li><li><a href="https://github.com/mkeisenbach/arvato">https://github.com/mkeisenbach/arvato</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58fbfc417669" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/customer-segmentation-for-financial-services-58fbfc417669">Customer Segmentation for Financial Services</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What does a Heart Attack depend on?]]></title>
            <link>https://hakanateslii.medium.com/what-does-a-heart-attack-depend-on-8f6192503174?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6192503174</guid>
            <category><![CDATA[hearth]]></category>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 19:00:46 GMT</pubDate>
            <atom:updated>2021-06-16T19:00:46.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msMTI-CSEOdAx1TYZvi8zw.jpeg" /></figure><p>As many of you know, Danish player Eriksen suffered a heart attack in the 45th minute of the match between Denmark and Finland in the Euro2020 Tournament. This view scared the whole world and me.</p><p>So what is this Heart Attack? What could be causing this?</p><p>A heart attack happens when a part of the heart muscle doesn’t get enough blood. The more time that passes without treatment to restore blood flow, the greater the damage to the heart muscle.</p><p>Now we know what a Heart Attack is. Now it’s time to find out what a heart attack depend on.</p><p>I used this dataset from kaggle to analyze Heart Attack.(<a href="https://www.kaggle.com/rashikrahmanpritom/heart-attack-analysis-prediction-dataset">https://www.kaggle.com/rashikrahmanpritom/heart-attack-analysis-prediction-dataset</a>)</p><h3>Dataset</h3><p>The explanations of the variables in the dataset are as follows;</p><p>* Age : Age of the patient</p><p>* Sex : Sex of the patient</p><p>* exang: exercise induced angina (1 = yes; 0 = no)</p><p>* ca: number of major vessels (0–3)</p><p>* cp : Chest Pain type chest pain type</p><p>* Value 0: typical angina</p><p>* Value 1: atypical angina</p><p>* Value 2: non-anginal pain</p><p>* Value 3: asymptomatic</p><p>* trtbps : resting blood pressure (in mm Hg)</p><p>* chol : cholestoral in mg/dl fetched via BMI sensor</p><p>* fbs : (fasting blood sugar &gt; 120 mg/dl) (1 = true; 0 = false)</p><p>* rest_ecg : resting electrocardiographic results</p><p>* Value 0: normal</p><p>* Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of &gt; 0.05 mV)</p><p>* Value 2: showing probable or definite left ventricular hypertrophy by Estes’ criteria</p><p>* thalach : maximum heart rate achieved</p><p>* target : 0= less chance of heart attack 1= more chance of heart attack</p><h3>Correlation Matrix</h3><p>A correlation matrix is a table showing correlation coefficients between variables. Each cell in the table shows the correlation between two variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3ZLrN-6qkgOhqb5gJuTaw.png" /></figure><ul><li><em>As can be understood from the correlation matrix of our dataset, There is no apparent linear correlation between numeric variable.</em></li><li><em>Correlation matrix suggests that there might be some correlation between output and cp, thalachh and slp.</em></li></ul><h3><strong>Distribution Plot</strong></h3><p>Distribution plots visually assess the distribution of sample data by comparing the empirical distribution of the data with the theoretical values expected from a specified distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*eOJmcQyAu87Tly3jWECJ5Q.png" /></figure><p>When we examine the distribution charts, we can make some predictions. Some of those:</p><ul><li><em>According to the distribution plot of thalachh output, people with higher maximum heart rate achieved have higher chances of heart attack.</em></li><li><em>According to the distribution plot of oldpeak output, people with lower pevious peak achieved have higher chances of heart attack.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*b5mIqF_7U-MSThI3bhnnFg.png" /></figure><ul><li><em>Although the sex = 0 is less than the sex = 1, the probability of having a heart attack is 45.0% for sex = 1, while it is 75.0% for sex = 0.</em></li><li><em>People with Non-Anginal chest pain, that is with cp = 2 have higher chances of heart attack.</em></li></ul><h3>Prediction Model</h3><p>Finally, I tried to develop a model that predicts heart attack risk using the heart attack dataset. For this, I first did data preprocessing. I made one hot encoding of categorical data. I scaled the numerical data.</p><p>I created 4 different models and trained this model with the training data set.</p><p>And result;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*1pyJT2PwYgzSkBhYAGGTsQ.png" /></figure><h3>REFERENCES</h3><ul><li><a href="https://www.udacity.com/course/data-scientist-nanodegree--nd025">https://www.udacity.com/course/data-scientist-nanodegree--nd025</a></li><li><a href="https://www.kaggle.com/namanmanchanda/heart-attack-eda-prediction-90-accuracy">https://www.kaggle.com/namanmanchanda/heart-attack-eda-prediction-90-accuracy</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6192503174" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RBM Öneri Sistemleri(Bölüm 1)]]></title>
            <link>https://hakanateslii.medium.com/rbm-%C3%B6neri-sistemleri-b%C3%B6l%C3%BCm-1-13073539afdb?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/13073539afdb</guid>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[rbm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 08:25:34 GMT</pubDate>
            <atom:updated>2021-06-12T08:25:34.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Ufsjg5WbmdLA_dhQPk4stw.png" /></figure><p>Merhabalar, Bu yazıda bitirme çalışması için geliştirdiğimiz uygulamada kullandığım RBM Öneri Sistemlerinden bahsedicem. Yapmış olduğum araştırmalar sonucu elde ettiğim bilgileri Genel(Bölüm 1) ve Teknik(Bölüm 2) olacak şekilde 2 yazıda derledim.</p><p>Yazıda Öneri Sistemleri nedir? Nerede, ne amaçla kullanılır? gibi soruları yanıtlamayacağım. Bunlar için aşağıdaki linkten bilgi edinebilirsiniz.</p><p><a href="https://medium.com/@irmcilingir/%C3%B6neri-sistemleri-recommendation-systems-28a3f341c0a9">Öneri Sistemleri (Recommendation Systems)</a></p><p>Bu yazıda sizlere işbirliğine dayalı filtrelemenin bir alt dalı olan Sınırlandırılmış Boltzmann Makineleri (Restricted Boltzmann Machines) kısaca RBM öneri sisteminden, yapısından ve nasıl işlediğinden bahsedicem.</p><p>Bölüm 2&#39;de ise modelin matematiğinden ve tekniğinden bahsedicem. İlginizi çekerse Bölüm 2&#39;ye bakabilirsiniz.</p><p>Boltzmann makineleri deterministik olmayan (veya stokastik) üretken derin öğrenme modelleridir ve yalnızca iki tür düğüm içerir. Bunlar görünür(giriş) ve gizli düğümlerdir. Çıkış düğümü yoktur. Modele stokastik özelliğini veren şeyde budur. Modellerin Stochastic Gradient Descent kullanılarak öğrenildiği ve optimize edildiği tipik 1 veya 0 tipi çıktıları yoktur. Bu yetenek olmadan kalıpları öğrenirler ve modeli özel yapan da bu özelliğidir.<a href="https://towardsdatascience.com/restricted-boltzmann-machines-simplified-eab1e5878976">[1]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*Nv2kX4mGcUiW8kfmSDlcqQ.png" /><figcaption>Şekil 1. Boltzmann Makinesi</figcaption></figure><p>RBM’ler ise Boltzmann Makinelerinin özel bir sınıfıdır ve görünür ve gizli birimler arasındaki bağlantılar açısından sınırlandırılmıştır. Boltzmann Makineleri ile karşılaştırıldığında uygulanması daha kolaydır. Boltzmann Makinelerinde görüldüğü üzere her düğüm birbiri ile bağlanabilmektedir. RBM’ler de ise görünür katmandaki her düğüm gizli katmandaki her düğüme bağlıdır ancak aynı gruptaki iki düğüm birbirine bağlı değildir. Bu kısıtlama, genel Boltzmann makineleri sınıfı için mevcut olandan daha verimli eğitim algoritmalarına olanak sağlar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Ufsjg5WbmdLA_dhQPk4stw.png" /><figcaption>Şekil 2. Sınırlandırılmış Boltzmann Makinesi</figcaption></figure><p>RBM’leri diğer derin öğrenme modellerinden ayıran özelliklerinden biri de gizli düğümden görünür düğüme gidebilmesidir. Genellikle derin öğrenme modellerinde girdi katmanında çıktı katmanına doğru bir yön vardır. Fakat RBM’lerde görünür katmandan gizli katmana gidebildiğimiz gibi gizli katmandan da görünür katmana gidebilmekteyiz. (Not: Bu geri yayılım ile karıştırılmamalıdır.)</p><p>RBM’leri diğer bilinen derin öğrenme modellerinden ayıran bir diğer özelliğide enerji temelli bir model olmasıdır. Enerji’yi derin öğrenme ile ilişkilendirmek başta biraz zordur. Fakat derin öğrenme modellerinin amacı, değişkenler arasındaki bağımlılıkları kodlamaktır. Enerji temelli modellerde bağımlılıkların yakalanması, bir uyumluluk ölçüsü olarak hizmet eden değişkenlerin her bir konfigürasyonuna bir skaler enerjinin ilişkilendirilmesi yoluyla gerçekleşir. Yüksek enerji, kötü uyumluluk anlamına gelir. Enerji tabanlı bir model, önceden tanımlanmış bir enerji işlevini her zaman en aza indirmeye çalışır. RBM’ler için enerji işlevi şu şekilde tanımlanır:<a href="https://www.udemy.com/course/recommender-systems/">[2]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*6tQu5VFlkwnYAxYyEimSuw.png" /><figcaption>Şekil 3. Enerji Formülü</figcaption></figure><p>Sınırlandırılmış Boltzmann Makineleri olasılıklıdır. Şekil 2’te RBM’in olasılıksal sinir ağı modeline bakacak olursak derin öğrenme ile ilgilenenler oldukça aşinalardır. Model W ağırlık vektörü ve A ve B sapma(bias) vektörlerini içermektedir. Şekil 1’deki modelde de görüldüğü gibi RBM iki yönlü bir sinir ağıdır. Ayrıca dikkatli bakarsanız W ağırlık vektörü paylaşımlı kullanılmaktadır. Model’de görüldüğü gibi sinir ağı modelimizin aktivasyon fonksiyonu sigmoid’dir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*YgUr7Gtr-hnVOmb7FonLlw.png" /><figcaption>Şekil 4. Olasılık Formülleri</figcaption></figure><p>Bir RBM sinir ağında yapmak istediğimiz şey, V (görünür düğüm)’den H(gizli düğüm)’ ye gitmek ve H’den V’ye geri dönmektir. Yani girdi olarak verilen ve çıktı olarak aldığımız V için bir dağılım hesaplamaktır. Şöyle düşünelim;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*oBJ2UsrI4hquAfVEysEYfw.png" /><figcaption>Şekil 5. RBM İşlem Sırası</figcaption></figure><p>V’den H’ye gittiğimizde bulduğumuz h~ vektörünü H’den V’ye dönerken modelimizde kullanıyoruz. Bunu neden yaptığımızı açıklamak için Otomatik Kodlayıcıları (AutoEncoder) düşünelim. Hem girdi hem de gizli katmanında sigmoid aktivasyon fonksiyonunu kullandığını ve iki katmanda da ağırlıkların aynı olduğunu varsayarsak bu bize görünür katmandan gizli katmana gidip oradan da geri dönen bir RBM’i hatırlatır. Yani V girişinin V çıkışına ne kadar yakın olduğunu gözlemlersek, 2. bölümde detaylı şekilde bahsedilecektir, çapraz entropi, biz onu optimize etmesek bile, model eğitilirken kendiliğinden azalacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*h53IhU0CYnc7ubDSxBed8A.png" /><figcaption>Şekil 6. Autoencoders And RBMs</figcaption></figure><p>RBM Öneri Sistemlerinin genel işleyiş mantığı bu şekildedir. Bölüm 2&#39;de RBM modellerinin arkasında yatan matematiğe derinlemesine giriş yapacağız. Yazıyı okuduğunuz için Teşekkürler.</p><p>Bölüm 2&#39;ye geçenlere şimdiden iyi okumalar.</p><h3>KAYNAKÇA</h3><ul><li><a href="https://www.udemy.com/course/recommender-systems/">https://www.udemy.com/course/recommender-systems/</a></li><li><a href="https://towardsdatascience.com/restricted-boltzmann-machines-simplified-eab1e5878976">https://towardsdatascience.com/restricted-boltzmann-machines-simplified-eab1e5878976</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13073539afdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kronecker Product(Kronecker Çarpımı)]]></title>
            <link>https://hakanateslii.medium.com/kronecker-product-kronecker-%C3%A7arp%C4%B1m%C4%B1-d71dec9fed4b?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71dec9fed4b</guid>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[kronecker-delta]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 14:57:34 GMT</pubDate>
            <atom:updated>2021-03-07T15:15:36.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*xqzsJglxAnveCGnml1c5VA.png" /></figure><p>Not: Kendime çalışma notudur.</p><p>Geçtiğimiz hafta sonu katıldığım Yapay Öğrenme Kış Okulu’nda <a href="http://home.ku.edu.tr/~mehmetgonen/">Mehmet Gönen</a> hocanın bir çalışmasında kullandığı hesaplama metodu ilgimi çekti. Bende neden araştırmıyorum dedim…</p><h4>1) Tarihçe</h4><p>Tarihçesinden kısaca bahsedecek olursak Kronecker çarpımı adını Alman matematikçi Leopold Kronecker’den almıştır, ancak onu ilk tanımlayan ve kullanan kişi olduğuna dair çok az kanıt vardır. Kronecker çarpımı, 1858&#39;de bu matris işlemini tanımlayan Johann Georg Zehfuss‘dan sonra Zehfuss matrisi olarak da adlandırılmıştır, ancak Kronecker çarpımı şu anda en yaygın kullanılan ismidir. ⊗, şekli ile gösterimi yapılır.</p><h4><strong>2) Tanım</strong></h4><p>A, m x n boyutlu ve B, p x r boyutlu iki matris olsun. Bu iki matrisi Kronecker çarpımı ile çarparsa, <strong>A</strong> ⊗ <strong>B</strong>,<strong> </strong>sonuç olarak (pm) x (nr) boyutlu bir blok matris elde edilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*ZRn3eArri5RjsHOcy0T7ew@2x.jpeg" /></figure><h4>3) Özellikler</h4><p><strong>Özellik.1)</strong> Kronecker çarpımı değişmeli değildir. (<strong>A</strong>⊗<strong>B </strong>eşit değildir<strong> B</strong>⊗<strong>A</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*wCbQF1271OW1tUi4531kvQ@2x.jpeg" /></figure><p>Kronecker çarpımı değişmeli değildir fakat her iki çarpım sonucuna bakacak olursak aynı değerlerin farklı yerlerde olduğunu görürüz. Buda bizi şöyle bir gerçeğe sürükler;</p><p>m1, n1, m2, n2 sabit boyutlu her P, Q <strong>permütasyon matrisi</strong> için</p><p>PA ⊗ BQ = B⊗A</p><p>eşitliği sağlanır. m1=m2=n1=n2 iken Q matrisi P matrisinin transpoz’una eşittir. Yani</p><p>P(A ⊗ B)P<em>T</em> = B⊗A</p><p><em>Bilgi: Permütasyon matrisini bir matrisle çarptığınızda sonuç olarak sadece çarptığınız matrisin elemanlarının yerleri değişir.</em></p><p><strong>Özellik.2)</strong> x, skaler bir değer olsun. (xA) ⊗ B = A ⊗ (xB) = x(A ⊗ B)</p><p><strong>Özellik.3)</strong> Birleşme özelliği vardır. (A ⊗ B) ⊗ C = A ⊗ (B ⊗ C)</p><p><strong>Özellik.4)</strong> Dağılma özelliği vardır. (A + B) ⊗ C = (A ⊗ C) + (B ⊗ C)</p><p><strong>Özellik.5) </strong>Transpoz alımı kolaydır.(A ⊗ B)<em>T</em> = A<em>T</em> ⊗ B<em>T</em></p><p><strong>Özellik.6) </strong>Kronecker çarpımı normal martis çarpımına göre oldukça hızlı çalışır.</p><p>Örneğin; elimizde A, B, C, D matrisleri olsun. Bu matrisler “compatible dimensions” yani çarpılabilir boyutlu matrisler olsun.</p><p>(A⊗B)(C⊗D) = (AC)⊗(BD) eşitliği sağlanır.</p><p>A mxn boyutlu, B pxq boyutlu, C nx1 boyutlu, D qx1 boyutlu olduğunu düşünelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*MMu3VRLoP-7PCjAxJv2aUA@2x.jpeg" /></figure><p>Buda önceki işlemin karmaşıklığına göre oldukça hızlı olduğunu gösteriyor.</p><p><strong>Özellik.7) </strong>A ve B matrisi tersi alınabilir bir matris ise A⊗B‘de tersi alınabilirdir. Kanıtlamak için özellik.6’daki eşitliği kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*SvcgkQ0YpLM-kInbOMVFtw@2x.jpeg" /></figure><p><strong>Kronecker Çarpımı ile Özdeğer ve Özvektörleri Bulma</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*KEIx3PcYQyuMsoDDFqQZzw@2x.jpeg" /></figure><p>A ve B matrislerinin gösterildiği gibi olduğunu düşünelim. Q ve P matrisleri A ve B matrislerinin özvektörini kolonlar halinde bulunduran özvektör matrisleridir. Λ ve μ matrisleri ise A ve B matrislerinin özdeğerlerini köşegen şeklinde bulunduran matrislerdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*Ru7UWefuNx_6Frv_-Dxkrg@2x.jpeg" /></figure><p>A⊗B matrisinin <strong>köşegenleştirilebilir </strong>olduğunu anlattığımız özellikleri kullanarak kanıtlamış olduk.</p><p>Son olarak, A⊗B matrisinin “eigen-pairs” özvektör ve özdeğer çiftleri olduğunu biliyoruz (qi⊗pj), (Λi,μj). (qi, Q matrisinin i.kolonu anlamına gelmektedir. )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*vgCBu2EVI5ONwMSfJM7H7w@2x.jpeg" /></figure><p>Kaynakça bölümünde çalışma notunu hazırlarken yararlandığım kaynakları ve Kronecker çarpımının kullanıldığı bazı çalışmaları bulabilirsiniz.</p><h4>KAYNAKÇA</h4><ul><li><a href="https://en.wikipedia.org/wiki/Kronecker_product">https://en.wikipedia.org/wiki/Kronecker_product</a></li><li><a href="https://www.youtube.com/watch?v=6Nj2lJTTKIQ">https://www.youtube.com/watch?v=6Nj2lJTTKIQ</a></li><li><a href="https://kisi.deu.edu.tr/kemal.sehirli/%C3%96zde%C4%9Ferler.pdf">https://kisi.deu.edu.tr/kemal.sehirli/%C3%96zde%C4%9Ferler.pdf</a></li><li><a href="https://www.statlect.com/matrix-algebra/Kronecker-product-properties">https://www.statlect.com/matrix-algebra/Kronecker-product-properties</a></li><li><a href="https://www.imageclef.org/system/files/CLEF2016_Kronecker_Decomposition.pdf">https://www.imageclef.org/system/files/CLEF2016_Kronecker_Decomposition.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71dec9fed4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAKLI MARKOV MODELLERİ]]></title>
            <link>https://hakanateslii.medium.com/sakli-markov-modelleri%CC%87-67b0e74c422c?source=rss-bc6cb6ba9a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b0e74c422c</guid>
            <category><![CDATA[derin-öğrenme]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[markov-models]]></category>
            <category><![CDATA[hidden-markov-models]]></category>
            <category><![CDATA[markov-chains]]></category>
            <dc:creator><![CDATA[Hakan Ateşli]]></dc:creator>
            <pubDate>Sat, 23 Jan 2021 19:43:18 GMT</pubDate>
            <atom:updated>2024-01-10T07:03:29.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>Saklı Markov Modelleri</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*UVik0X6V_JheO7Rh.png" /><figcaption>İki durumlu basit bir Markov Zinciri</figcaption></figure><p>Markov Zincirini anlamama yardımcı olan çok güzel bir siteyi ekliyorum. Yazıyı okuduktan sonra bu siteye gitmenizi tavsiye ederim. Görsel olarak da modelin nasıl çalıştığını görmenin yazıyı pekiştireceğine eminim. Ayrıca yorumlara bakmayı ihmal etmeyin :)</p><p><a href="https://setosa.io/blog/2014/07/26/markov-chains/index.html">Markov Chains</a></p><h4>1-) Kesikli Markov Süreçleri</h4><p>Markov modelleri, bir durumun olasılığını bulmak için önceki durumlara bakılan matematiksel bir sistemdir. Yani örnekler bağımlıdır. Örneğin bir kitap satış sitesinde “Cemal Süreyya-Sevda Sözleri” kitabına bakan bir kişinin “Nazım Hikmet-Memleketimden İnsan Manzaraları” kitabına da bakma olasılığı yüksektir, fakat “Philip Kotler-Pazarlama 4.0” kitabına bakma olasılığı düşüktür. Bu durumda bu kişiye olasılıksal olarak yüksek olasılıklı kitapları önerirsiniz. Markov modellerinin en bilinen örneklerinden biride Google PageRank algoritmasıdır. Google’da arama yaptığınızda karşınıza çıkan sitelerin sıralanmasında Markov modeli kullanılmaktadır. Dil işleme, DNA sıralama ve daha pek çok sıralamada kullanılabilir.</p><p>Modeli açıklamaya başlamadan önce kullanacağımız bazı tanımları açıklamak istiyorum:</p><ul><li>S1,S2,…,SN ile gösterdiğimiz N tane durumdur. Sıralamanın herhangi bir anında bunlardan biri vardır.</li><li>qt, t=1,2,… t anındaki durum anlamına gelir. qt = Si dediğimizde sıralamanın t anında Si durumunda olduğunu anlamalıyız.</li><li>t anında dediğimizde ise herhangi bir sıralamanın(dizgenin) t’inci index’i olarak anlayabilirsiniz.</li></ul><p>Sıralamada(dizge) her bir t anında belirli bir olasılık dağılımına bağlı olarak bir durumdan başka bir duruma geçebilir veya kendi durumunda kalabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*2zomKwAPNNyUC1GSTid1Og@2x.jpeg" /><figcaption>Önceki durumlar verildiğinde qt+1 anında Sj durumu olma koşullu olasılığı</figcaption></figure><p>Birinci dereceden bir Markov modelinde t+1 anındaki durumun olasılığını t anındaki duruma bakarak buluruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*02YCR2jLgtaq--S1TdkFSw@2x.jpeg" /><figcaption>Geçiş Olasılığı</figcaption></figure><p>Burada aij, t anındaki durumdan(Si) t+1 anıdaki duruma(Sj) geçme olasılığıdır. Dolayısıyla <em>geçiş olasılığı</em> adı verilir. aij eksi olamaz ve bütün aij’lerin toplamı 1 olmalıdır. Geçiş olasılıklarını (Satırların toplamı 1&#39;dir. Her bir durumun geçebileceği durumların geçiş olasılıklarıdır.) NxN boyutlu A = [aij] geçiş olasılıkları matrisi ile gösterebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*9u9cYX8gwpy9feukyVBEvg@2x.jpeg" /><figcaption>Geçiş Olasılığı koşulları</figcaption></figure><p>Geçiş olasılığı zamandan bağımsızdır. Buda Si durumundan Sj durumuna geçiş dizinin herhangi bir yerinden aynıdır anlamına gelir. Tek bir istisna il durumdur. t=1 anındaki durum için <em>başlangıç olasılıkları</em> tanımlanır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*ecNRAleBZIsz4irPruUDwg@2x.jpeg" /><figcaption>Başlangıç Olasılığı ve koşulu</figcaption></figure><p>Not: Başlangıç olasılıklarının toplamı da 1 olmak zorundadır.</p><p>Gözlenebilir bir Markov modelinde herhangi bir t anındaki qt durumunu biliriz. Sıralamada bir durumdan başka bir duruma geçerken arka arkaya gelen bu durum değerlerine gözlem dizisi adı verilir. O = Q ={q1,q2,..,qN} durum dizisinin olasılığı dizideki durumların görülme olasılıkları çarpımıdır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*GjqAGPCUcCtgHWGQ86mHGg@2x.jpeg" /><figcaption>Gözlem Dizisi Görülme Olasılığı</figcaption></figure><p>Şimdi küçük bir örnek yapalım. Örneğimizde 3 kutu ve her kutuda farklı renk olduğunu ve bu kutularda top çektiğimizi her çektiğimiz topun renginide sıraya eklediğimizi düşünelim.</p><p>S1 = Kırmızı, S2 = Mavi , S3 = Yeşil</p><p>Başlangıç olasılıkları ve geçiş olasılıkları aşağıdaki gibidir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*CDwvb2AMBglMTiGA9QmN7A@2x.jpeg" /></figure><p>Şimdi sıralamamızın “Kırmızı, Mavi, Yeşil” olsun. O={S1,S2,S3} olma olasılığı inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*9BC6AZbUE5ucgncjG9z4yg@2x.jpeg" /></figure><p>Şimdide “Yeşil, Kırmızı, Mavi” olsun O={S3,S1,S2} olma olasılığını inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*bTjXiMEdmSrtZuLxCyYdFA@2x.jpeg" /></figure><p>Tamamdır, olasılık hesaplamayı öğrendiğimize göre şimdi de başlangıç ve geçiş olasılık parametrelerini nasıl hesaplayacağımızı öğrenelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*XGQPBxPTJ-jrDxWUd9WtSg@2x.jpeg" /></figure><p>Not: 1(b), b doğru olduğunda 1, yanlış olduğunda 0 değeri aldığı anlamına geliyor.</p><p>Başlangıç olasılıklarını yukarıdaki formülde görüldüğü gibi, Si ile başlayan gözlem dizisi sayısı bölü olabilecek tüm gözlem dizisi sayısı şeklinde hesaplıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*rp7wNIxRPMU5QrgTEPwzLQ@2x.jpeg" /></figure><p>Geçiş olasılıklarını ise içinde Si’den Sj’ye geçiş yapılan dizilerin sayısı bölü içinde Si olan dizi sayısı ile hesaplıyoruz.</p><h4>2-) Saklı Markov Modelleri</h4><p>Saklı Markov Modellerinde(SMM) durumlar kutu-top örneğimizdeki gibi gözlenemez. Her duruma belirli bir olasılığa bağlı gözlem oluştururuz. Bu olasılığı şu şekilde gösteriyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*4ggpmGZgqKlMQ8Y9YrKyNA@2x.jpeg" /></figure><p>bj(m), Sj durumunda vm simgesinin <em>gözlem olasılığını</em> gösterir. Aslında modeli “Saklı” yapan da {<em>O}</em> gözlem dizisinin biliyor fakat {<em>Q} </em>durum dizisini bilmiyor olmamızdır.</p><p>Daha açıklayıcı olursak, örneğimizde şöyle bir değişiklik yaptık. N adet kutu ve M adet renk olduğunu düşünelim fakat bu sefer her kutuda tek renk yerine, her renkten en az 1 adet top var. Ve kutulardan seçim yaparken hangi kutudan seçim yaptığımızı bilmiyoruz. Yani bir perdenin arkasından elimizi uzatarak bir kutudan bir top seçiyoruz. Top “Kırmızı” renkte olsun, bu gözlemi <em>O</em> gözlem dizisine yazıyoruz ama topun hangi kutudan geldiğini görmediğimiz için durum dizisine herhangi bir değer yazamıyoruz.</p><p>Saklı Markov modelini aşağıdaki gibi kafes gösterim şeklinde gösterebiliriz. Kırmızı renkli daireler t anıdan gözlem dizisindeki t. gözlemin hangi durumda olduğunu bize göstermektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*vj9_J0ZWBvvt-UwZKr-P6w@2x.jpeg" /><figcaption>SMM Kafes Gösterim Şekli</figcaption></figure><p>Not: Gözlenebilir bir Markov modeli, saklı bir Markov modelinin özel bir hali olduğunu söyleyebiliriz: M = N ve bj(m), j = m olduğunda 1 değilse 0.</p><p>1989 yılında Rabiner tarafından Saklı Markov modellerinin üç temel sorunla karakterize edilmesi gerektiği fikrini ortaya attı. Bu 3 soruna geçmeden önce Saklı Markov modelini tanımlayan bileşenleri tanıtalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*futL6wrLL1mDlQLL-6PDJw@2x.jpeg" /></figure><p><strong>Not: λ = (A,B,π) , </strong>saklı bir Markov modelinin parametre kümesi olarak tanımlanır.</p><p><strong>Sorun 1: λ ile tanımlanmış bir model için, P(O|λ) olasılığını nasıl hesaplarız?</strong></p><p>Hesaplama işlemine geçmeden önce kısa bir şekilde yöntemden bahsetmek istiyorum. Yönteme ileri-geri yöntemi adı verilmiş. Bu yöntem, gözlem dizisini, ilk parçası 1&#39;den t’ye, ikinci parçası t+1&#39;den T’ye olacak şekilde 2 parçaya bölüyor.</p><p>İlk olarak , verilmiş bir <strong>λ</strong> için, gözlem dizisinin ilk {O1,…,Ot} parçasını gözleyip t anında Si durumuna varma olasılığını veren αt(i) <em>ileri değişkenini </em>tanımlayalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*bl_xTM4kx-o7tCJYF1nQVQ@2x.jpeg" /><figcaption>İleri Değişkeni</figcaption></figure><p>Böyle bir tanımın güzel yanı, sonrakilerin özçağrılı(rekürsif) bir şekilde öncekilerden hesaplanabilmesi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*opnp0ryzjKQppYNPcGsBpQ@2x.jpeg" /><figcaption>İleri Değişkeni Algoritması</figcaption></figure><p>αt(i) değeri ilk t gözlemi açıklandığında Si durumunda sonlanan parçayı açıklar. Bu değeri aij olasılığı ile çarparak bir sonraki Sj durumuna geçeriz, ve burada önceki durum için N tane seçenek olduğundan olası tüm Si durumları üzerinden toplam almak gerekiyor. Ardından t+1 anında Sj durumunda bj(Ot+1) olasılığıyla (t+1). gözlemi de gördüğümüzde artık ilk t+1 gözlemi açıklamış ve Sj durumuna erişmiş oluyoruz. İleri değişkenlerini dizi sonuna kadar hesapladığımızda da tüm dizinin görülme olasılığını hesaplamış oluyoruz.</p><p>Sorun 1&#39;in çözümü için gerekmese de ileriki sorunlarımızı da karşımıza çıkacak bir değişken daha var. O da βt(i), <em>geri değişkeni</em>’dir. βt(i), ileri değişkeni tamamlayacak biçimde, t anında Si durumundan başlayarak dizinin sonraki bölümü olan {Ot+1…OT} dizi parçasını gözlemenin olasılığı olarak tanımlanır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*3uH_rRVyeBgTYw-tvhpwKw@2x.jpeg" /><figcaption>Geri Değişkeni</figcaption></figure><p>Bu değerler yine özçağrılı olarak, bu kez ters yönde sondan başlanılarak hesaplanır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*r8AoJlCAzflG5-pUz2ieCg@2x.jpeg" /><figcaption>Geri Değişkeni Algoritması</figcaption></figure><p>Si durumundan sonra, üzerlerinden toplam almak gereken N tane olası sonraki Sj durumu vardır ve bunlara geçiş olasılığı aij değeriyle verilmiştir. Her birindeyken (t+1). gözlemini görmenin ve ardından kalan dizi parçasının olasılığı olan βt+1(j) değerinin hesaba katmak gerekir.</p><p>Örnek olarak aşağıdaki parametreleri verilmiş bir modelde, gözlem dizimiz {Casual Wear, Winter Apparel} olsun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*7yMk1P5G8TX0gAQvNU8pOw@2x.jpeg" /><figcaption>Örnek Modelimizin Parametreleri</figcaption></figure><p>2 adet gözlemimiz olduğunda kafes modelimizde 2 sıra bulunmaktadır. İleri ve geri değişkenleri aşağıda gördüğümüz şekilde hesaplanmaktadır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*T0cEsY99KwdAkM24pP4tTw@2x.jpeg" /><figcaption>İleri Değişkeni Algoritması 2 adım işlenmiş hali</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*lxskvTik1BpzE0woPXTaSA@2x.jpeg" /><figcaption>Geri Değişkeni Algoritması 2 adım işlenmiş hali</figcaption></figure><p>İleri-geri değişkenlerinin python kodu ile kodlaması da aşağıdaki gibidir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4624daf3f96523965b79f8e803afad6e/href">https://medium.com/media/4624daf3f96523965b79f8e803afad6e/href</a></iframe><p><strong>Sorun 2:</strong> <strong>Bir λ modeli ve <em>O</em> gözlem dizisi verildiğinde, bu gözlem dizisinin türetilme olasılığını en fazla yapan durum dizisinin nasıl bulabiliriz? İstediğimiz öyle bir <em>O*</em> bulmak ki P(<em>Q</em>|<em>O</em>,λ) en büyük olsun.</strong></p><p>En iyi durum dizisini(yolunu) bulmak için geçiş olasılıklarını göz önüne alan ve dinamik programlamaya dayanan <em>Viterbi algoritması</em> kullanılmaktadır. Viterbi algoritması, model parametrelerinin optimize edildiği ve gözlemlenen verilerin verildiği gizli durumlara bir çıkarım veya tahmin yapmanın etkili bir yoludur. Bir zaman adımından diğerine giden yolun nasıl seçildiğini bulmak en iyi bir kafes şekli ile görselleştirilir.</p><p>Bu adımda yeni bir değişken tanımlıyoruz. δt(i), ilk t gözlemi açıklayan ve S<em>i</em> durumunda biten olası tüm yollar içinde olasılığı en yüksek olanın olasılık değerini gösterir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*cgtKj9hbjdmdcdq80xONkQ@2x.jpeg" /></figure><p>En yüksek olabilirliği olan durum dizisini aşağıdaki algoritmayı izleyerek bulabiliriz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*R_643IBWBJJOtEtZIgIIOA@2x.jpeg" /><figcaption>Viterbi Algoritması</figcaption></figure><p>Viterbi algoritmasının karmaşıklığı, ileri değişkenlerin hesaplanmasının karmaşıklığı ile aynı; zaten dikkat edersek tek fark, toplam almak yerine en büyük olanı bulmak. Aşağıda da Sorun 1&#39;deki örneğimiz için Viterbi algoritmasını 2 adım ilerlettik:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*6Bja8lnalGH1PC9U8KoHMQ@2x.jpeg" /></figure><p>En sağda kırmızı ile yazılmış formüller örneğimizdeki maksimum değerler, yani δ değeri de diyebiliriz. Kırmızı çizgiler ise δ değerini maksimum yapan durum geçişleridir. Şimdide Viterbi algoritmasının python kodunu görelim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a134560628da346a89de9d451efdd59a/href">https://medium.com/media/a134560628da346a89de9d451efdd59a/href</a></iframe><p><strong>Soru 3:</strong> <strong>Gözlem dizilerinden oluşan bir X = {O<em>k</em>}<em>k</em> öğrenme kümesi verildiğinde bu gözlem kümesini türetme olasılığı en büyük olan model parametreleri nasıl bulunur? İstediğimiz öyle bir λ* bulmak ki P(X|λ) en büyük olsun.</strong></p><p>Son ve en önemli soruya, yani saklı bir Markov modelini veriden öğrenmeye geldik. Bu bölümde saklı bir Markov modelini nasıl eğitiriz sorusuna cevap arıyoruz. Bunun için ise sıklıkla kullanılan <em>Baum-Welch algoritmasını </em>öğreneceğiz. Bu algoritma bir Beklenti Büyütme (Expectation-Maximization) Algoritmasıdır.</p><p>Şimdi son bir değişken daha tanımlıyoruz. ξ<em>t(i,j)</em> değeriyle tüm gözlem kümesi verildiğinde, arada herhangi bir t anında Si durumundan sonraki t+1 anındaki Sj durumuna geçme olasılığını gösteriyoruz. αt(i) değişkeni ilk t gözlemi açıklandıktan sonra t anında Si durumuna gelir. Oradan aij olasılığı ile Sj durumuna geçer, (t+1). gözlemi türetir ve t+1 anından sonra Sj durumundan dizinin kalanını açıklayacak biçimde βt+1(j) olasılığıyla devam ederiz. Paydaki bu değeri, t ve t+1 anında geçebilecek olası tüm durum çiftlerin değerlerinin toplamına bölerek normalleştiriyoruz. γt(i) ise t anında Si durumunda olma olasılığıdır. Bunu da olası tüm sonraki durumlara geçiş olasılıklarının toplamı olarak hesaplayabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*ZrB8r3CHxOtaVmO9Jctijw@2x.jpeg" /></figure><p><em>Baum-Welch algoritmasının </em>2 adımı vardır:<em> B</em>eklenti(Expectation) adımı ve Maksimizasyon(Maximization) adımı. Beklenti adımında, o anki <strong>λ=(A, B, π) </strong>değerlerini kullanarak ξt(i,j) ve γt(i) değerlerini buluruz, Maksimizasyon adımında da, ξt(i,j) ve γt(i) değerlerini kullanarak sonraki λ değerini kestiriyoruz. Bu iki adımı yakınsama olana dek yineliyoruz; bu sırada P(O|λ) olabilirlik değerinin hiç azalmadığı gösterilmiştir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*rep9MhujJGF6Wg62VwS-Cw@2x.jpeg" /><figcaption>Yeni parametrelerin hesaplanma formülleri</figcaption></figure><p>Maksimizasyon adımında yeni parametre değerlerinin hesaplarız. âij parametresi, Si durumundan Sj durumuna beklenen geçiş sayısı bölü Si durumunda toplam geçiş sayısı ile verilir. Yeni bj parametresi, yani Sj durumunda vm simgesini görme olasılığı, Sj durumunda vm simgesinin gözlenme sayısı bölü Sj durumundan toplam geçiş sayımız ile verilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*kL6M13F8tlotjN7usRSCXQ@2x.jpeg" /></figure><p>Fakat birden çok gözlem dizisi olduğunu ve bunların birbirinden bağımsız olduğunu varsayarsak parametre değerlerini kestirirken olası diziler üzerinden toplam alırız:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*kI69E0Vmv8hh2NiS0PvUjQ@2x.jpeg" /></figure><p>Son olarak baştan sonra bir Saklı Markov Modelinin python kodunu görelim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e15c8cb74561dac8075953e83fe62da/href">https://medium.com/media/8e15c8cb74561dac8075953e83fe62da/href</a></iframe><p>Saklı Markov Modeli için yazılmış hazır kütüphanelerde vardır. Bunlara da göz atmanızı tavsiye ederim.</p><p><a href="https://hmmlearn.readthedocs.io/en/latest/tutorial.html">hmmlearn</a></p><p><strong>KAYNAKÇA</strong></p><ul><li>Ethem Alpaydın, Yapay Öğrenme, (İstanbul: Boğaziçi Üniversitesi Yayınevi, 2018),311–331.</li><li><a href="https://tr.wikipedia.org/wiki/Markov_zinciri">https://tr.wikipedia.org/wiki/Markov_zinciri</a></li><li><a href="https://web.stanford.edu/~jurafsky/slp3/A.pdf">https://web.stanford.edu/~jurafsky/slp3/A.pdf</a></li><li><a href="https://datascience.stackexchange.com/questions/74126/hidden-markov-model-forward-algorithm-implementation-in-python">https://datascience.stackexchange.com/questions/74126/hidden-markov-model-forward-algorithm-implementation-in-python</a></li><li><a href="https://www.adeveloperdiary.com/data-science/machine-learning/implement-viterbi-algorithm-in-hidden-markov-model-using-python-and-r/">https://www.adeveloperdiary.com/data-science/machine-learning/implement-viterbi-algorithm-in-hidden-markov-model-using-python-and-r/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b0e74c422c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>