<?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 M. Can Benli on Medium]]></title>
        <description><![CDATA[Stories by M. Can Benli on Medium]]></description>
        <link>https://medium.com/@can-benli?source=rss-4bdcf9d3f64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vKIQw1H5X9Eob5R2e1hICA.jpeg</url>
            <title>Stories by M. Can Benli on Medium</title>
            <link>https://medium.com/@can-benli?source=rss-4bdcf9d3f64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:32:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@can-benli/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[Optimizing Material Assignment in KARDEX Warehouse System]]></title>
            <link>https://medium.com/@can-benli/optimizing-material-assignment-in-kardex-warehouse-system-3fc844423626?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fc844423626</guid>
            <category><![CDATA[operation-research]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[gam]]></category>
            <category><![CDATA[mathematical-modeling]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 22:21:26 GMT</pubDate>
            <atom:updated>2024-01-24T22:25:59.327Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>ABSTRACT</strong></p><p>This study was carried out in a company that uses Kardex warehouse system as a warehouse system, with the aim of reaching the material as soon as possible in order to carry out a work order index during the production in a certain production by assigning materials to Kardex shelves. The problem defined in the article is defined as the question of whether the work order will be completed in the shortest time by placing which materials on which shelves. In the article, the problem was solved with the help of GAMS by transforming it from a non-linear structure to a linear structure as a management model. As a result of the study, it was determined which materials would be placed on which shelves and the time was calculated in order to place the work orders as quickly as possible.</p><p><strong>Keywords: </strong>GAMS (General Algebraic Modeling System), Linear programming, Material assignment, Optimization, Sensitivity analysis, Warehouse management</p><p><strong>1. INTRODUCTION</strong></p><p>The efficiency of production processes is closely tied to accurate and effective inventory management. In this context, the use of modern storage solutions such as the Kardex warehouse system, the assignment of materials to the correct shelves and the impact of this assignment on production processes can increase the competitive advantage of businesses. In this article, a study was conducted to ensure rapid access to the production line, minimizing in warehouse transportation times and increasing operational efficiency when materials are assigned to the correct shelves in the Kardex warehouse system in a business. The main purpose of this study is to assign materials to Kardex shelves in line with a specific production and a specific work order and to remove these materials from these shelves as soon as possible.</p><p>The Kardex warehouse system includes the product range of a company that offers automated storage solutions and material handling systems. These systems optimize warehouse management using automated shelving, elevators, and software-based control systems. High storage capacity and fast access advantages provide effective solutions for industrial storage needs. Kardex warehouse systems are generally used in the production, logistics and storage sectors. The Kardex system used by the company in this study consists of 20 shelves, and each shelf has the capacity to hold 24 units (a certain volume) of materials. These shelves also have the potential to lift a certain weight of material, but since the materials used in production at the facility are of low weight, the weight capacity will not be taken into account in the study.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*dSgnN3yZh0LTY9l-OFd7eg.jpeg" /></figure><p><strong><em>Figure 1.</em></strong><em> Kardex Warehouse System</em></p><p>The material assignment problem is a critical issue that businesses face in their complex operational processes today. This challenge involves trying to cope with limited resources, increasing demands, and various constraints. Businesses have to deal with material assignment problems in order to increase their efficiency, optimize their operational processes and minimize costs. In the study in this article, the company has 20 different work orders to produce a product. In the work orders, 150 different materials required to perform the work in that work order are specified. Additionally, the time spent on purchasing a material from Kardex shelves will be important for modeling and these times were taken into account in the study. The main focus of this study is the optimization problem of material assignment so that 150 different materials can be accessed to 20 shelves in the Kardex Warehouse System as quickly as possible during production. Additionally, successfully meeting 20 work orders derived from these shelves was also taken into account. Automated storage solutions and material handling systems provided by Kardex as a global industry partner form the basis of this study.</p><p>In conclusion, in this article, an operational model will be developed using the number of work orders, the number of kardex shelves, the time to access a material from these shelves, the total number of materials and the maximum number of materials that the shelves can hold according to a certain unit volume. It is planned to create a model that will determine which materials will be assigned to which shelves and give the total material collection time in order to access the materials in the work orders as quickly as possible.</p><p><strong>2. LITERATURE REVIEW</strong></p><p>Material assignment problems, and especially the issue of material assignment to shelves, host important research studies to enable businesses to use resources in the most effective way, optimize operational processes and gain competitive advantage. This literature review provides a general evaluation of material assignment problems and studies conducted in this context.</p><p>In a study conducted by Chieh-Yuan Tsai and Ming-Chang Wu [1] in 2010, an approach was developed in the arrangement of shelves that takes into account product type similarities as well as the relationships between product categories. The study differs from previous research in this aspect. The study focuses on improving the solution quality by developing an effective heuristic algorithm while solving a multi-level shelf space allocation problem. The study shows that the proposed two-stage shelf allocation method provides an effective solution to complex shelf space allocation problems. In a study by Kateryna Czerniachowska and Marcin Hernes [2], they address the problem of assigning materials to the shelf using genetic algorithms, taking into account vertical position effects. This study not only presents an effective shelf space allocation model in the retail industry, but also reveals the potential of genetic algorithms in solving such complex problems.</p><p>In a study titled “Mathematical and Intuitive Solution Approaches for the Shelf Assignment Problem in Multiple Warehouses” [3], a study focusing on the layout of products in warehouses was carried out. It was mentioned that the shelf assignment process of products in multiple warehouses is a very critical issue in terms of logistics and warehouse management, and in the study examined two basic approaches to solving this complex problem: mathematical modeling and heuristic algorithms. The aim of this study is to design an effective warehouse system for assigning pallet pairs of raw materials to shelves. The aim of the model is to minimize the transportation distance between warehouses, taking into account the priority coefficients of the raw material. In this study, an approach has been developed that aims to design an effective warehouse management system by solving the shelf assignment problem in multiple warehouses, minimizing logistically important transportation distances and reducing the number of used shelves in warehouses. The developed mathematical model aims to improve in-warehouse logistics processes and use resources more effectively.</p><p>Another study titled “A Heuristic Algorithm for the Warehouse Space Assignment Problem Considering Operational Constraints: Application with a Case Study” [4] focuses on the warehouse space assignment problem and discusses a heuristic algorithm that takes operational constraints into account. The article emphasizes that warehouses play an important role in logistics cost control and states the importance of effective stock management and warehouse allocation. This study aims to make the assignment processes of materials in the warehouse more effective by emphasizing the importance of logistics cost control. This study demonstrates its effects in real-world applications through case studies and offers a practical perspective on improving operational processes.</p><p>In conclusion,these studies cover a wide range of research on material assignment problems and shelf material assignment, and make significant contributions to increasing the operational efficiency of businesses. These studies address various challenges in efficient use of resources and gaining competitive advantage by providing applicable solutions in various industry fields. The approaches in these articles were used during this study as a reference point in modeling such problems, understanding general approaches and determining the factors that may affect them.</p><p><strong>3. METHODOLOGY</strong></p><p>In this article, a model has been developed to determine the assignments required to collect the materials required for that production from Kardex shelves as soon as possible according to the current work order index in a particular production and to find the total material collection time. In order to develop this model, information was first collected from various data sources to obtain a detailed understanding of the Kardex warehouse system. This data includes data such as work orders, properties of materials, capacities of Kardex shelves, access times to materials, transportation times between shelves and material transportation costs. The collected data was used in the mathematical modeling process.</p><p>Following the data collection phase, a mathematical model was created for the material assignment problem. This model includes the materials to be assigned to Kardex racks under specific work orders and constraints to optimize the total material picking time of that assignment. While developing the model, Linear programming and Non-Linear model linearization methods were used. The created mathematical model was solved using an appropriate GAMS algorithm. In this step, it is determined which shelves the materials under certain work orders will be assigned to and the total material collection time is minimized.After the solution, sensitivity analysis will be performed and sensitivity values for the variables in the solution are examined. This is an important step to understand how the solution reacts to various scenarios and changes.</p><p><strong>3.1. Data Collection</strong></p><p>In our study, various data were needed for the developed model to work effectively and for appropriate operations research to be conducted. The data required to develop a model to determine the assignments required to collect the material from the shelves as soon as possible in a given production and to find the total material collection time were: number of work orders, time to take a material from the ith shelf, number of shelves, which material is exist in which work order and the total number of materials.</p><p>The first data in this study were the number of work orders in the production where the study was carried out, which material was in which work order, and the total number of materials. There are 20 work orders in the production studied in this study and there are a total of 150 materials in those work orders. Which materials are in which work order is dataized using the 1–0 matrix. A data set is created by giving the value 1 if there is jth material in the kth work order, and 0 if not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*ZD26y_lnmySpzyeWqjaFYQ.png" /></figure><p><strong><em>Table 1.</em></strong><em> Work Order Index(WOI) and Material Index(MI) 1–0 Matrix</em></p><p>The second data set in this study is the time spent to access the material in the ith work order. The Kardex warehouse system in this study consists of a total of 20 shelves and the time required to reach each shelf is different. The unit of time used in the data set is minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*8T-0AUAeL6ZSSFbda_s7GA.png" /></figure><p><strong><em>Table 2.</em></strong><em> Times to reach the shelves</em></p><p><strong>3.2. Mathematical Modeling</strong></p><p>Mathematical models are created to address practical challenges and identify optimal resolutions for them. Comprising decision variables, parameters, and problem constraints, these models are executed within specific limitations and rely on the model outcomes to attain the most favorable solution within the solution set. One key advantage of mathematical models lies in their ability to swiftly resolve real-life problems demanding substantial resources and time. Widely applied across diverse sectors, mathematical models serve various purposes through their utility in numerous functional areas. The mathematical model proposed in this study is built on the minimum time-oriented material assignment methodology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*JtAAIrbv5XDNstsJ-Vu2Rw.png" /></figure><p><strong><em>Table 3.</em></strong><em> Definitions of the proposed mathematical models’ components</em></p><p>This method ensures that materials are assigned to the most appropriate shelves in order to reach them as quickly as possible in a production situation. The accuracy of estimated time values and shelf assignments in this methodology is of great importance for production efficiency. In this study, the parameters to be used in the following models were obtained based on production work order forms. Kardex shelves are defined as cluster i, work orders as cluster k, and materials as cluster j. Definitions of the sets, parameters, and decision variables of the proposed mathematical models are given in Table 2. The mathematical model established in the study assigns a shelf for each material and each shelf has different access times. Using the definitions in Table 2, the mathematical model that allows the company to collect the materials in the work orders from the warehouse as quickly as possible during production is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*KNz_uQeo8xUHRJEbcFz_7w.png" /></figure><p>The first equation of the proposed mathematical model is the objective function, which multiplies the time required to reach a shelf for a work order and adds these times. In other words, the objective function of the mathematical model is a function that aims to go to as few shelves as possible by collecting and comparing the times for each shelf visited. For this reason, the decision maker of the company where the study is carried out wants to minimize this period. Equation (2) limits the number of materials in the ith shelf, so the number of materials assigned to the shelf cannot be higher than the maximum number of materials level of the KARDEX shelf. The third equation (3) states that an item can be assigned to only one shelf. Equation (5) shows the mathematical definition of decision variables.</p><p><strong>3.3. Mathematical Model: Relating Two Decision Variables in Equation</strong> <strong>4</strong></p><p>To further elaborate on the mathematical model and the relationship between two decision variables, let’s delve into the details. The proposed mathematical model establishes a relationship between two decision variables, specifically cik and xij. This connection is crucial for accurately representing the constraints and optimizing the assignment of materials to shelves during the production process.</p><p>This constraints essentially represents an if-else condition. It servers to establish a connection between the two decision variables <em>cik</em> and <em>xij</em> within the context of a particular order<em> k</em> and a particular shelf <em>i</em>. Let’s break down the meaning of this constraint:</p><ul><li>If <em>cik</em> is 1 (indicating that the <em>i</em></li><li>th shelf is necessary for the <em>k</em>th order), then the left-hand side can reach a maximum value denoted as <em>M.</em></li><li>If <em>cik</em> is 0 (indicating that the <em>i</em></li><li>th shelf is not required for the <em>k</em>th order), then the left-hand side evaluates to 0.</li></ul><p>It reflects the necessity of a particular shelf for a specific order and contributes to the overall optimization goal of minimizing the time required for material collection. Another purpose of this restriction is to prevent the model from counting the duration of a shelf more than once. In other words, if there is more than one item in the same work order on the same shelf, it prevents the <em>ai </em>value of that shelf from being counted more than once. Since the shelf comes only once, all the ingredients can be taken at the same time. The model efficiently assigns materials to shelves during production, optimizing the process by establishing crucial relationships between decision variables <em>cik</em>​ and <em>xij</em>. This interplay accurately mirrors real-world production scenarios, offering a comprehensive representation of the material assignment problem.</p><p><strong>3.4. Model Solution with GAMS</strong></p><p>In this part of the study, the material assignment model introduced in section 3.2 was analyzed using GAMS. Model parameters use data received and generated from the company during the study period. The model aims to reach the minimum time by looking at the decision variable <em>cik</em>, that is, whether a shelf is required for a work order, and using the ai parameter, that is, the times required to reach the<em> i</em> th shelf. To achieve this, it looks at the <em>bjk</em> parameter and examines which material is required for which work order, and as a result, different combinations are tried. At the end of all these iterations, it determines that the materials can be collected from the shelves in the shortest time possible and presents this in an Excel file. Additionally, it also shows how long it will take to collect the materials as a result of the combination it finds. The GAMS model is given in APPENDIX 1.</p><p>As a result of the assignments made based on the 20 work orders in the production to be made at the end of the GAMS solution and the materials required to realize these orders, the minimum collection time of 150 materials from KARDEX shelves was calculated as 37.40 minutes and these assignments were made as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*BnD505Hbl2l8yxYXVWv8zA.png" /></figure><p><strong><em>Table 4. </em></strong><em>Results of GAMS</em></p><p><strong>3.5. Sensivity Analysis</strong></p><p>After obtaining the solution in this study, a sensitivity analysis was carried out to evaluate the sensitivity of the model to various variables and parameters. This step is critical to understanding how the solution responds to various scenarios and changes. Sensitivity analysis will specifically examine how the optimal solution will change if some constraints on the solution are relaxed or tightened. It will also focus on the consequences of changes to specific variables in the solution. Sensitivity analysis results will provide valuable insights into the applicability of the model and the robustness of its solution.</p><p>In this study, there are four basic constraints in the model mentioned in section 3.2; Equation 5 is the mathematical representation and equation 4 is the conditions that ensure linearity for the applicability of the model. Therefore, it is not possible to perform sensitivity analysis on these two constraints. Equation 2 indicates the material capacity of the KARDEX rack in a given unit volume. In Equation 3, there is a restriction that each material can be placed on only 1 shelf. By performing sensitivity analysis on these two equations, the reactions of the constraints to changes will be measured and evaluated.</p><p>Since the constraint in Equation 3 indicates the product capacity of the KARDEX shelf in a certain unit volume, it will not be possible to make such a change instantly in the company because the shelf capacity of the KARDEX warehouse system is fixed and cannot be changed. However, analyzing this constraint will allow the company to see how effectively its current system can meet the needs of the company and the efficiency it will achieve in comparison with the money it will spend in possible investments. Currently, 24 materials can be placed on each shelf. In the analysis, this number will be increased from 24 to 150, which is the number of collected materials, and the collection speed of the materials during production will be observed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*Y0uhhFXJmYOjbASoH8fCZA.png" /></figure><p><strong><em>Table 5.</em></strong><em> Optimal Value Results by Sensitivity Analysis Constraint 2</em></p><p>As a result of the sensitivity analysis, it was observed that increasing the KARDEX shelf capacity reduced the material collection time up to a certain capacity. As seen in Figure 2, as the shelf capacity is increased up to 80, the material collection decreases. In the first case, the time, which was 37.4 minutes, decreased to 17.44 minutes by increasing the capacity to 80. Increasing the capacity by more than 80 units of material does not provide any benefit to the company. Data regarding this is also available in Table 5 and can be observed in Figure 2. However, increasing the capacity up to 80 units of material will be costly as KARDEX systems are expensive. The decisions to be taken at this point may vary depending on the company’s priorities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*TK09QweWmbi5OfhX1sExmw.png" /></figure><p><strong><em>Figure 2.</em></strong><em> Sensivity Analysis of Constraint 3</em></p><p><strong>4. DISCUSSION</strong></p><p>The focus of this study is on optimizing material assignment in a company using the Kardex warehouse system. In this part of the study, it is aimed to evaluate the results obtained in a broad perspective and understand the potential effects of the solution on the business.</p><p>The study results show that the optimal material assignment strategy aims to carry out work orders in a certain production as soon as possible. Reducing the total material collection time to 37.4 minutes is an important result that can strengthen the competitive advantage of the business by increasing operational efficiency. Additionally, the sensitivity analysis evaluated the sensitivity of the model to various variables and constraints. Analysis on rack capacity has shown that the optimal solution is sensitive up to a certain capacity level. In the analysis made on the number of shelves, it was observed that the number of shelves that can be used for a particular work order did not have a significant effect on the model results.</p><p>The practical feasibility and cost analysis of the optimal material assignment strategy should evaluate its suitability to the business’s existing KARDEX warehouse system. It is important to compare the time advantage gained by increasing the shelf capacity with the cost of KARDEX systems. When implementing this solution, the business must take a balanced approach in terms of both short-term efficiency and long-term return on investment. Considering the limitations of the study, it may be beneficial in future studies to extend the model for more complex operational scenarios and examine its applicability on different systems. Additionally , the cost analysis of shelf capacity increase can be discussedd in more detail. In conclusion, this study reveals the potential business benefits of optimizing material assignment times using gthe KARDEX warehouse system. However, a detailed implementation and cost analysis is required to evaluate whether this solution is compatible with operating conditions.</p><p><strong>5. CONCLUSION</strong></p><p>This research provides a focus on optimizing a company’s material assignment times using the KARDEX warehouse system. The main goal of the study is to determine optimal material assignment strategies to complete work orders in a specific production in the shortest time. Reducing the total material collection time to 37.40 minutes brings a significant competitive advantage for the business.</p><p>The sensitivity analysis evaluated the model’s responses to various variables and constraints. Analysis on rack capacity has shown that the optimal solution is effective up to a certain capacity level. It has been observed that rack capacity can significantly affect material collection time. However, whether this capacity increase is compatible with operating costs should be evaluated with a detailed cost analysis. Analysis on the number of shelves revealed that the number of shelves that can be used for a particular work order does not have a significant effect on the model results. As a result, the practical feasibility and cost analysis of the optimal material assignment strategy must evaluate its suitability for the business’s existing KARDEX warehouse system.</p><p><strong>REFERENCES</strong></p><p>[1] Tsai, C.-Y., &amp; Wu, M.-C. (2010). Applying a Two-Stage Simulated Annealing Algorithm for Shelf Space Allocation Problems. In Proceedings of the World Congress on Engineering 2010 (Vol. III), WCE 2010, June 30 — July 2, 2010, London, U.K.</p><p>[2] Czerniachowska, K., &amp; Hernes, M. (2020). A Genetic Algorithm for the Shelf-Space Allocation Problem with Vertical Position Effects. Center for Intelligent Management Systems, Wroclaw University of Economics and Business, 53–345 Wroclaw, Poland.</p><p>[3] Sanei, O., Nasiri, V., Marjani, M.R., &amp; Moattar Husseini, S.M. (2011). A heuristic algorithm for the warehouse space assignment problem considering operational constraints: with application in a case study. In Proceedings of the 2011 International Conference on Industrial Engineering and Operations Management, Kuala Lumpur, Malaysia, January 22–24, 2011. Department of Industrial and Engineering, Amirkabir University of Technology, Tehran, Iran.</p><p>[4] Kamışlı Öztürk, Z., Akyol Özer, E., Gülen, Ç., Çiçek, A., &amp; Serttaş, M. D. (2019). Mathematical and heuristic solution approaches for shelf assignment problem in multiple warehouses. Journal of Industrial Engineering, 30(1), 63–74. Eskisehir Technical University, Engineering Faculty, Department of Industrial Engineering, Eskisehir.</p><p><strong>APPENDIX 1 (GAMS CODE)</strong></p><pre>sets<br>i /1*20/<br>j /1*150/<br>k /1*20/<br><br>Parameter a(i)<br>$call GDXXRW.exe ordertime.xlsx par=a rng=Sayfa1!A1 rdim=1<br>$GDXIN ordertime.gdx<br>$LOAD a<br>$GDXIN<br>display a;<br><br>Parameter b(j,k)<br>$call GDXXRW.exe handling.xlsx par=b rng=Sayfa1!A1 rdim=1 cdim=1<br>$GDXIN handling.gdx<br>$LOAD b<br>$GDXIN<br>display b;<br><br>binary variable x(i,j) ;<br>binary variable c(i,k) ;<br>free Variables z ;<br><br>Equations<br>obj<br>capacity<br>assingment<br>ordercost<br>zlow<br>zup<br>;<br><br>obj.. z=e= sum( (i,k), c(i,k)*a(i) ) ;<br>zlow.. z=l=60;<br>zup.. z=g=0 ;<br>capacity (i).. sum ( (j), x(i,j) ) =l= 24 ;<br>assingment(j).. sum ( (i), x(i,j) )=e=1 ;<br>ordercost (i,k).. sum( (j), x(i,j)*b(j,k))=l= c(i,k)*100 ;<br><br>model wh /all/ ;<br>wh.OptFile= 1 ;<br>solve wh using MIP minimizing z;<br><br>display z.l, x.l, c.l<br><br>execute_unload &quot;layout.gdx&quot; x.L<br>execute &#39;gdxxrw.exe layout.gdx var=x.L&#39;<br>execute &#39;gdxxrw.exe layout.gdx var=c.L rng=NewSheet! &#39;</pre><p>Check out my website</p><p><a href="https://canbenli.com.tr/en/blog/optimizing-material-assignment-in-kardex-warehouse-system/">https://canbenli.com.tr/en/blog/optimizing-material-assignment-in-kardex-warehouse-system/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fc844423626" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classification and Regression Trees (CART)]]></title>
            <link>https://medium.com/@can-benli/classification-and-regression-trees-cart-ed65e4b5a0b6?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed65e4b5a0b6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cart]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 09:20:52 GMT</pubDate>
            <atom:updated>2023-11-23T12:41:24.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ki-Ykfa4vl85gPQ-ObU92w.png" /></figure><p>Today, data analysis and machine learning play an important role in finding solutions to complex problems. Classification and Regression Trees (CART), one of the various techniques used in this field, is a powerful tool for understanding and making predictions about data sets. In this article, we will explore the CART modeling technique step by step.</p><p>Classification and Regression Trees is a statistical modeling technique. This technique is used in fields such as data mining and pattern recognition. Basically, a tree structure is created that divides a data set into separate subgroups for classification or regression analysis.</p><p>Decision trees are based on the idea of asking a problem as simple yes/no questions and answering those questions based on data. Each node represents a decision point, and the branches of the tree are divided into different subgroups based on the data. This decomposition process allows the data set to be divided into smaller and more homogeneous subgroups.</p><p>Classification trees are used to predict a categorical or classifiable target variable, whereas regression trees are used to predict a continuous target variable. The CART method is known for its ability to recognize meaningful patterns on data sets and perform classification or regression using these patterns. At the same time, this method is an important building block that forms the basis of more complex algorithms such as Random Forest.</p><p>The main purpose of CART is to transform complex structures in the data set into simpler decision structures. This technique is used to divide heterogeneous data sets into homogeneous subgroups based on a specified target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*gzUqjUIgfqdN4s8bGQWyLQ.png" /></figure><p>According to the explanation given above, the statistics and salaries of the athletes in the data set are depicted with the CART structure according to certain rules. The average salary (logarithm) of athletes with less than 4.5 years of experience was determined as 5.11. In addition, a different branching was created based on another variable, the number of shots fired, for athletes with years of experience equal to or more than 4.5 years. Accordingly, the average salary of athletes who made less than 117.5 shots was expressed as 6, and the average salary of athletes who made equal or more shots was expressed as 6.74 with its logarithm taken. This CART structure can be used to estimate players’ salaries based on years of experience and number of innings pitched.</p><p>Decision trees have a structure similar to filters in Excel tables. The variable at the top of a decision tree diagram is considered the most important variable because it has the highest impact. In decision trees, independent variables may be called explanatory variables or “Features”. The decision points that divide the independent variables on the decision trees are called “Internal Nodes”. The points at the ends of the decision trees are called “Terminal Nodes”.</p><p><strong>Determination of Decision Rules</strong></p><p>One of the most important elements in the CART structure is to determine the decision rules. This is done through an algorithmic process and optimizations are made based on certain reference points. As a result of these optimizations, internal node and end node points are determined and decision rules based on these points are derived. In this context, these decision rules are determined using metrics such as Chi-Square, GINI, Entropy (Information Gain), RSS (SSE), Reduction in Variance.</p><p><strong>RSS (SSE) — Sum of squares error</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*KhpGrlShm-1G67Uj_8IMaA.png" /></figure><p>When creating a decision tree, the points where the decision rules are determined are the points with the lowest RSS (SSE) value. At these points, decision tree branches (zoning, branching, boxing) are created and the decision tree is shaped. In this process, the expression YRⱼ represents the regions where the predicted values are located.</p><p>When decision trees are used in regression problems, YRⱼ prediction values are determined by averaging the values of the dependent variable in the parts under the branches (regions, boxes, leaves). These predicted values represent the last node values of the corresponding branch.</p><p>According to the RSS result, the variable with the lowest error is first determined and this variable is at the top of the decision tree. Afterwards, the branch points are determined to have the lowest RSS value, and the final nodes are determined through a mathematical optimization process.</p><p><strong>CART for Classification Problem: Cost &amp; Loss Objective Function</strong></p><p>For classification problems, GINI coefficient and Entropy can be used as cost &amp; loss objective functions in the CART algorithm:</p><p><strong>GINI Coefficient</strong> measures the probability of misclassifying a randomly selected item at a node of a decision tree. That is, it is the probability that a sample at a node will be misclassified when assigned to a randomly selected class. The GINI coefficient is used to determine the purity or homogeneity of a node. If a node is completely pure (that is, all samples belong to the same class), its GINI coefficient will be 0. However, if the samples in a node are evenly distributed (i.e., there are an equal number of samples from each class), the GINI coefficient approaches 1 (the maximum value).</p><p><strong>Entropy </strong>measures uncertainty or randomness in a system and expresses diversity. In data science, it is used to determine the purity or promiscuity of samples in a node. If a node is completely pure (that is, all instances belong to the same class), its entropy will be 0. However, if the examples in a node are evenly distributed (that is, there are an equal number of examples of each class), entropy approaches 1 (the maximum value).</p><p>Both metrics are used when making the decision to split a node of a decision tree or random forest. The node with the lower GINI coefficient or entropy value provides a higher information gain and is therefore selected. These methods can be used effectively in classification problems and also provide a control mechanism against overlearning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*GmAbjpBCQywdViQ_Wa8YVA.png" /></figure><p>Measurement methods of prediction success basically arise as a result of evaluating the differences between real values and predicted values with various techniques. Among these measurement methods, Entropy and GINI values provide important information in evaluating prediction success. These success metrics guide the determination of the branch points of the decision tree. While the SSE metric is used for regression problems, the focus functions seen above (representing Entropy and GINI values) are preferred for classification problems. These functions are often called “purity measures” and the lower its value, the higher the prediction success is considered. Additionally, in the approach called The Weighted Loss, errors on the right and left sides of the branches are calculated as weighted.</p><p><strong>Hyperparameter Optimization</strong></p><p>When creating decision trees (CART), some important hyperparameters need to be optimized. Keeping the Max Depth and Min Sample Split hyperparameters at optimal levels while creating the CART model significantly affects the model success.</p><p><strong>Max Depth:</strong> This hyperparameter determines how deeply the created tree will branch. Repeated splitting of initially formed branches reduces error rates, but can lead to overfitting. Therefore, specifying this hyperparameter controls how deep into the tree one goes.</p><p><strong>Min Sample Split: </strong>This hyperparameter determines the minimum number of observations needed for each branch to occur. Branching is not done until this number is reached. This parameter also controls the tendency of the tree to over-learn. It prevents branches from being too small and excessive learning.</p><p>Correctly tuning these two hyperparameters both helps preserve the predictive ability of the tree and reduces the risk of overlearning. It is also important to minimize loss of generalizability (randomness). Optimization of these hyperparameters allows effective and balanced use of tree methods.</p><p>In this article, I included important information about CART, a statistical modeling technique. Thank you for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/classification-and-regression-trees-cart/">https://canbenli.com.tr/en/blog/classification-and-regression-trees-cart/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed65e4b5a0b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KNN Application]]></title>
            <link>https://medium.com/@can-benli/knn-application-339605e35616?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/339605e35616</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[knn-classification]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 17:20:28 GMT</pubDate>
            <atom:updated>2023-10-22T17:20:28.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AIXGJj7nD-lrNLXBmgBQg.png" /></figure><p>The data set we will work with in the KNN application is a telecommunications provider data. Based on this data, let’s assume that the telecommunications provider segments its customer base according to service usage patterns and divides the customers into four groups. Demographic data can be used to predict which group the customer is in and special campaigns and marketing strategies can be developed. For example, there may be a focus on using demographic data such as region, age, and marital status to predict usage patterns. The target variable, called Custcat, has four possible values corresponding to four customer groups:</p><ol><li>Basic Service</li><li>E-Service</li><li>Plus Service</li><li>Total Service</li></ol><p>Our goal is to create a KNN model to predict the class of unknown situations. Let’s start now.</p><p>Let’s start by importing the necessary libraries first.</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import seaborn as sns<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.model_selection import train_test_split, cross_val_score<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.metrics import accuracy_score, confusion_matrix, classification_report</pre><p>Let’s continue with the data reading and preprocessing steps. If the data set contains missing data, we can detect it with “.isnull()”. We can reach the total number of missing data with “.sum()”. We said that our target variable is “custcat”. Let’s also look at how many values there are in the classes.</p><pre>df = pd.read_csv(&#39;telecommunication.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*y3igaBxEf8pCFF5cFcwQNw.png" /></figure><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*ggwVZb1m4bS5b3E3dhwCqQ.png" /></figure><pre>df[&#39;custcat&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*KZJtV_cx7TMhl6vKxxz2jQ.png" /></figure><pre>X = df.drop(&#39;custcat&#39;, axis=1).values</pre><p>Data Standardization is an important process, especially in distance-based methods of data points such as KNN. Because this method makes the data zero mean and unit variance. I talked about this method in detail in my article “Feature Scaling”. Click to review.</p><pre>scaler = StandardScaler()<br>X = scaler.fit_transform(X.astype(float))<br>y = df[&#39;custcat&#39;].values</pre><p>We divide the data set into 80% training and 20% test data sets with the train_test_split function. The random_state parameter ensures that the random division process is repeatable. If you enter the same random_state value as me, you will get the same results.</p><pre>X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=12)</pre><p>Now it’s time to determine our K value. We will perform 5-fold cross-validation for each of the K (number of neighbors) values from 1 to 99 and the accuracy scores will be kept in a list.</p><pre>k_values = range(1, 100)<br>cv_scores = []<br>for k in k_values:<br>    knn = KNeighborsClassifier(n_neighbors=k)<br>    scores = cross_val_score(knn, X_train, y_train, cv=5, scoring=&#39;accuracy&#39;)<br>    cv_scores.append(scores.mean())</pre><p>To find the best K value, let’s select the K value by taking the K value corresponding to the highest accuracy score in the cv_scores list.</p><pre>optimal_k_values = [k_values[i] for i in range(len(cv_scores)) if cv_scores[i] == max(cv_scores)]</pre><pre>print(optimal_k_values)</pre><p>24</p><p>Let’s visualize the accuracy rates corresponding to the K values in order to see them in the graph.</p><pre>plt.plot(k_values, cv_scores)<br>plt.xlabel(&#39;K Value&#39;)<br>plt.ylabel(&#39;Cross-Validation Accuracy&#39;)<br>plt.title(&#39;Accuracy - Cross Validation Plot&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*PmRWT-2nu4cDvvPvuV8z8Q.png" /></figure><p>The data was standardized and we reached our optimal K value. Let’s finish the process by setting up the model.</p><pre>knn = KNeighborsClassifier(n_neighbors = optimal_k_values[0]).fit(X_train,y_train)</pre><p>Let’s create a new variable and assign our prediction values to this variable.</p><pre>y_pred = knn.predict(X)<br>df[&quot;custcat_predict&quot;]=pd.DataFrame(y_pred)<br>df[[&quot;custcat&quot;,&quot;custcat_predict&quot;]].head(15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*SDaHnoJKXUZnhhpc0aPRyg.png" /></figure><p>Let’s calculate the accuracy score (accuracy_score) between the actual and estimated values, create a confusion matrix and visualize it as a heat map with sns.heatmap().</p><pre>acc = round(accuracy_score(y, y_pred), 2)<br>cm = confusion_matrix(y, y_pred)<br>sns.heatmap(cm, annot=True, fmt=&quot;.0f&quot;)<br>plt.xlabel(&#39;y_pred&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.title(&#39;Accuracy Score: {0}&#39;.format(acc), size=10)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*2x__DUDNWtBe0tnPWaSmHQ.png" /></figure><p>If we interpret the graph, my example shows that 238 in the upper left;</p><p>238 of the values belonging to class 1 were predicted as 1, that is, they were predicted correctly. Similarly, in the section labeled 12, 12 of the items belonging to class 1 were predicted as class 2, meaning they were guessed incorrectly. Rather than examining these values one by one, let’s easily evaluate the ratios in a table.</p><pre>print(classification_report(y, y_pred))</pre><p>Let’s evaluate the table. The precision value measures the rate at which samples predicted as positive are actually positive. That is, it shows how many of the examples the model predicts as positive are actually correct. It is a proportional expression of the interpretation we made on the heat map. 80% of those predicted as “1” are actually “1”.</p><p>In my article “Evaluating Success in Classification Problems”, I explained what the values mean. Click to review.</p><p>Recall measures how many truly positive examples were correctly predicted by the model. That is, it shows how many of the truly positive samples were detected by the model. 89% of the true “1&#39;s” were guessed correctly.</p><p>F1-score provides a balance score by taking the harmonic average of the precision and recall metrics. This metric takes into account whether both precision and recall are good. F1-score is the average of precision and recall values. If both precision and recall are high, F1-score will be high.</p><p>Support shows how many examples are in the actual dataset for each class. This value represents the number of data points belonging to that class. For example, class “1” has 266 data points.</p><p>Accuracy shows the ratio of correctly predicted samples to the total number of samples. That is, it expresses the rate of correct prediction of all classes. For example, the accuracy rate is 71%, meaning that the proportion of samples that the model predicts correctly is 71%.</p><p>Macro average takes the arithmetic average of the metric values of each class. Weighted average calculates the metric values of each class by weighting them according to the number of examples of that class. This provides a more accurate assessment in case of imbalance between classes.</p><p>As a result, it can be interpreted that the performance of the model is unbalanced between classes. Particularly low precision and sensitivity are observed for class “2”, indicating that the model has difficulty predicting this class accurately. However, since it is a beginner and is not subjected to too much pre-processing, it can be considered a normally successful model.</p><p>We reinforced our knowledge with the KNN application. Thank you for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/knn-application/">KNN Application | Can Benli</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339605e35616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbors (KNN)]]></title>
            <link>https://medium.com/@can-benli/k-nearest-neighbors-knn-6f0d01f95135?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f0d01f95135</guid>
            <category><![CDATA[k-nearest-neighbors]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 07:58:03 GMT</pubDate>
            <atom:updated>2023-10-18T07:58:03.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBbKM1M-hLHS-3KOItdWGg.png" /></figure><p>K-Nearest Neighbors (KNN) algorithm is an approach used in regression and classification problems in supervised machine learning models. This algorithm detects the K different observation units closest to the observation unit we want to make a prediction for and makes a prediction for the relevant observation through the dependent variables of these K observation units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*EvokdIh_4kJFoRSEoksntQ.png" /></figure><p>The operation of this algorithm is quite simple. First, a K value is determined; This K value represents the number of neighbors. When making a prediction, it searches for the K nearest neighbors in the entire data set and calculates the distance between these neighbors. The Euclidean function is usually used in distance calculation, but alternatively Manhattan, Minkowski, Hamming and Cosine functions can also be preferred. After the distance is calculated, the neighbors are ranked and the observation to be predicted is assigned to the appropriate class based on these neighbors.</p><p>KNN is a lazy algorithm with no training phase; it does not learn the training data, it just keeps the dataset in its memory. Therefore, when one wants to make a prediction, one turns directly to the neighbors. This algorithm, which is widely used especially in classification problems, stands out with its simple structure and effective results.</p><p><strong>Determination of K Value</strong></p><p>Determining the K value is very important in the K-Nearest Neighbor (KNN) algorithm because choosing an incorrect K value can affect the accuracy of the model. Usually the optimal K value is calculated as the square root of the number of observations in the data set. This is usually a good starting point.</p><p>“Cross-validation” techniques are often used to determine the optimal K value. In this technique, the data set is randomly divided into subgroups (layers) and the model is validated for each subgroup. This verification process is repeated for different K values. Then, the optimal K value is selected based on the accuracy value.</p><p>It is important to find a balance between overfitting and underfitting when determining the K value. If the K value is too small (for example, 1 or 2), too much noise may be added to the model, which can lead to overfitting. On the other hand, if the K value is too large (for example, N/2 or larger), the model may have learned poorly and underfitting may occur.</p><p>Choosing the correct K value based on cross-validation results increases the accuracy and generalization ability of the KNN algorithm. Now let’s see how we can choose the optimal K value on the iris dataset.</p><p>Let’s start by importing the necessary libraries first.</p><pre>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split, cross_val_scorefrom sklearn.neighbors <br>import KNeighborsClassifier</pre><p>Use the “matplotlib.pyplot” library for graphic drawings, the “load_iris” function from the “sklearn.datasets” module to load the iris dataset, the “train_test_spli” function to divide the data into training and test sets, the “cross_val_score” function to calculate cross-validation accuracy values. and we use the “KneighborsClassifier” class to create the KNN model.</p><p>We load the iris dataset and assign it to our variables.</p><pre>iris = load_iris()<br>X = iris.data<br>y = iris.target</pre><p>We divide the data set into training and test data. We determine 70% of the data as the training set and 30% as the test set. If you keep the random_state argument to the same value as me, you will get the same output.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><p>We will calculate cross-validation accuracy values for different K values. A KNN model will be created for each K value, then 5-fold cross-validation accuracy values will be calculated with the cross_val_score function and the average of these values will be added to the cv_scores list.</p><pre>k_values = range(1, 50)<br>cv_scores = []<br> <br>for k in k_values:<br>   knn = KNeighborsClassifier(n_neighbors=k)<br>   scores = cross_val_score(knn, X_train, y_train, cv=5, scoring=&#39;accuracy&#39;)<br>   cv_scores.append(scores.mean())</pre><p>We draw a graph containing cross-validation accuracy values against K values with the “plt.plot” function. In the graph, the K value will be on the x-axis and the cross-validation accuracy value will be on the y-axis.</p><pre>plt.plot(k_values, cv_scores)<br>plt.xlabel(&#39;K Value&#39;)<br>plt.ylabel(&#39;Cross-Validation Accuracy&#39;)<br>plt.title(&#39;Accuracy - Cross Validation Plot&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*1szQ8ogbMhIWgUjIR9_cHA.png" /></figure><p>We can observe that as the K value increases, the cross-validation accuracy value decreases. Let’s write a code to choose the K value with the highest accuracy.</p><pre>optimal_k_values = [k_values[i] for i in range(len(cv_scores)) if cv_scores[i] == max(cv_scores)]</pre><p>It will find the K values with the highest accuracy in the cv_scores list and add these values to the optimal_k_values list.</p><p>These values can be determined as the k values that give the highest accuracy rate.</p><p><strong>Distance Metrics Used in KNN Algorithm</strong></p><p><strong>Euclidean Distance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*TJNDjkV1LWcJH0PPngOY1A.png" /></figure><p>Euclidean distance is used as a common metric to calculate the distance between numerical data points. This distance represents the length of a straight line between two data points.</p><p><strong>Minkowski Distance</strong></p><p>Minkowski distance is a metric designed for real-valued vector spaces and can only be calculated in a normed vector space. This distance has the flexibility to calculate the distance between data points in different ways. For example, for p = 1 it is known as the Manhattan distance, for p = 2 it is known as the Euclidean distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*YREB-CXsT_QzAGtD3eTAcw.png" /></figure><p><strong>Manhattan Distance</strong></p><p>Manhattan distance is used when calculating the distance between two data points on a grid-like path, such as a city block. This distance can be found by setting the p value of the Minkowski distance to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*FvCvO29WDui91kwBSJ3ItA.png" /></figure><p><strong>Hamming Distance</strong></p><p>Hamming distance is a measure for comparing different bits of two binary data strings. When comparing two binary strings of equal length, the Hamming distance gives the number of different bit positions in the two strings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*5pr4A6cKhpFDAHX0qOu6WA.png" /></figure><p><strong>Cosine Distance</strong></p><p>Cosine distance is used to measure the similarity between two vectors. This distance determines whether two vectors are in the same direction or in opposite directions. It is often used to measure document similarity in text analysis and provides a different perspective on business problems with algorithms such as KNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*Omn6YGT7ZBNNOShDOkYLkw.png" /></figure><p><strong>KNN in Regression Problems</strong></p><p>The dependent variable and independent variables are given together in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*NkHSxojkE6B1bzH-0DtVXA.png" /></figure><p>Estimating the dependent variable Y for an observation unit with an X1 and X2 value is usually done with the k-NN (k-nearest neighbors) algorithm or a similar method. In this method, the nearest K observation units are determined using Euclidean or another distance calculation and a prediction is made using the dependent variables (Y values) of these observation units. The prediction can be made by a statistical measure such as the mean of the Y values of these K nearest neighbor units of observation. This approach is based on the assumption that observation units with similar characteristics have similar Y values.</p><p><strong>KNN in Classification Problems</strong></p><p>The dependent variable and independent variables are given together in the table below. The dependent variable is a binary variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*wwxfoVkQLw3Mf9LT_O2hiA.png" /></figure><p>In the classification problem, in the first step of estimating the Y dependent variable for an observation unit with any X1 and X2 values, distance calculation is made and thus the nearest K observation units are determined. The Y values of these immediate neighbors are taken into account and the most frequently observed Y value is considered the predicted class. This method is an effective approach in classification problems and is often used with the KNN (K-Nearest Neighbors) algorithm.</p><p>In this article, I included detailed information about the KNN algorithm. Thank you for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/k-nearest-neighbors-knn/">https://canbenli.com.tr/en/blog/k-nearest-neighbors-knn/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f0d01f95135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression Application]]></title>
            <link>https://medium.com/@can-benli/logistic-regression-application-997f7aac61da?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/997f7aac61da</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 09:35:35 GMT</pubDate>
            <atom:updated>2023-10-14T09:35:35.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIyrOyIXlViHtjh0_BlgCg.png" /></figure><p>We will work on the “Diabetes” data set. We will predict whether someone with values in different variables has diabetes. Let’s start by importing the necessary libraries.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>from sklearn.preprocessing import RobustScaler<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, roc_auc_score, confusion_matrix, classification_report<br>from sklearn.model_selection import train_test_split, cross_validate<br>from sklearn import metrics<br>from sklearn.metrics import RocCurveDisplay</pre><pre>df = pd.read_csv(&quot;diabetes.csv&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*1ArpS2U1g5yke5y5pkiCHg.png" /></figure><pre>df.shape</pre><p>(768, 9)</p><p>There are 9 variables in our data set, and 8 of these 9 variables are independent and 1 is a dependent variable. We need to model the relationship between dependent and independent variables. We also saw that there are 768 observation units in this dataframe.</p><p>Let’s analyze the dependent variable and independent variables separately. Then, let’s cross the dependent and independent variables and analyze them together.</p><pre>df[&quot;Outcome&quot;].value_counts()</pre><p>0 500</p><p>1 268</p><p>When we look at our dependent variable, there are 268 observations from class 1 and 500 observations from class 0. If we want to visualize it as a column chart;</p><pre>sns.countplot(x=&quot;Outcome&quot;, data=df)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*adhKn-iOzT49ha3ebraQsw.png" /></figure><p>Let’s continue by analyzing our independent variables.</p><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*tP1BrINYL2sT5lRB1VlxcA.png" /></figure><p><strong>Outlier Analysis</strong></p><p>At this stage, we will evaluate the outlier situation on the basis of categories in the data set. To do this, we code a function that will determine the lower and upper threshold values in order to find outlier values, and then a function that answers the question of whether there is an outlier on the basis of variables.</p><pre>def outlier_thresholds(dataframe, col_name, q1=0.05, q3=0.95):<br>    quartile1 = dataframe[col_name].quantile(q1)<br>    quartile3 = dataframe[col_name].quantile(q3)<br>    interquantile_range = quartile3 - quartile1<br>    up_limit = quartile3 + 1.5 * interquantile_range<br>    low_limit = quartile1 - 1.5 * interquantile_range<br>    return low_limit, up_limit<br><br>def check_outlier(dataframe, col_name):<br>    low_limit, up_limit = outlier_thresholds(dataframe, col_name)<br>    if dataframe[(dataframe[col_name] &gt; up_limit) | (dataframe[col_name] &lt; low_limit)].any(axis=None):<br>        return True<br>    else:<br>        return False</pre><p>Let’s evaluate which columns are inconsistent with ”check_outlier”.</p><pre>for col in cols:<br>    print(col, check_outlier(df, col))</pre><p>Pregnancies False</p><p>Glucose False</p><p>BloodPressure False</p><p>SkinThickness False</p><p>Insulin True</p><p>BMI False</p><p>DiabetesPedigreeFunction False</p><p>Age False</p><p>We found out that there were outliers in the “Insulin” variable. Let’s solve this outlier problem with the suppression method. Let’s define a function for this and suppress outliers to lower and upper threshold values.</p><pre>def replace_with_thresholds(dataframe, variable):<br>    low_limit, up_limit = outlier_thresholds(dataframe, variable)<br>    dataframe.loc[(dataframe[variable] &lt; low_limit), variable] = low_limit<br>    dataframe.loc[(dataframe[variable] &gt; up_limit), variable] = up_limit<br>replace_with_thresholds(df, &quot;Insulin&quot;)<br><br>for col in cols:<br>    print(col, check_outlier(df, col))</pre><p>Pregnancies False</p><p>Glucose False</p><p>BloodPressure False</p><p>SkinThickness False</p><p>Insulin False</p><p>BMI False</p><p>DiabetesPedigreeFunction False</p><p>Age False</p><p>The next stage is Variable Scaling. Standardization processes are generally very important in linear and distance-based methods and methods using gradient descent. The standardization process is important to us in two respects. First, it ensures that models treat variables equally. Secondly, it enables the parameter estimation methods used to make faster and more accurate estimates.</p><p>Let’s standardize all variables using RobustScaler(). I explained the details about RobustScaler() in my previous articles. Don’t forget to take a look.</p><pre>for col in cols:<br>    df[col] = RobustScaler().fit_transform(df[[col]])<br><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*J14gA_7kgUuqDOS4Yif2lQ.png" /></figure><p>We adapted our data set to the logistic regression model. Now it’s time for modelling.</p><pre>y = df[&quot;Outcome&quot;]<br>X = df.drop([&quot;Outcome&quot;], axis=1)</pre><p>We defined dependent and independent variables. Our target variable is the “Outcome” variable, so we extracted it with “.drop()” when defining our independent variables. Now let’s fit the model.</p><pre>log_model = LogisticRegression().fit(X, y)</pre><p>Let’s check the prediction values.</p><pre>y_pred = log_model.predict(X)<br>df[&quot;outcome_predict&quot;]=pd.DataFrame(y_pred)<br><br>df[[&quot;Outcome&quot;,&quot;outcome_predict&quot;]].head(15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*lSqJEn3K0eIhQrKaSsnFZQ.png" /></figure><p><strong>Model Success Evaluation</strong></p><p>The “confusion_matrix()” function is used to calculate the numerical equivalents of values such as Accuracy, Precision, Recall, F1 score obtained from the complexity matrix. We added some features to visually address this function.</p><pre>acc = round(accuracy_score(y, y_pred), 2)<br>cm = confusion_matrix(y, y_pred)<br>sns.heatmap(cm, annot=True, fmt=&quot;.0f&quot;)<br>plt.xlabel(&#39;y_pred&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.title(&#39;Accuracy Score: {0}&#39;.format(acc), size=10)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*M2ksf9AGmdc_28eTbzeBhg.png" /></figure><pre>print(classification_report(y, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*lD5WvJoMvFzG2agc-cWZzA.png" /></figure><p>We are interested in class 1. It is the class that expresses the state of being diabetic. The precision value is 0.74, meaning 1, and 74% of our predictions were correct.</p><p>We were able to correctly classify those with a recall value of 0.58, i.e. 1, with 58% success.</p><p>The F1 score, or harmonic mean, is 0.65.</p><p>Another value to look at is the ROC AUC value.</p><p><strong>Roc Curve</strong></p><p>Without a model, when only an average value is predicted, the success achieved is expected to be similar to the results predicted by a random classifier. As the ROC curves above the random classifier line concavely approach a perfect classifier, the success rate increases. These curves are created through the complexity matrix by calculating True Positive and False Positive values according to possible threshold values.</p><p>The area between the ROC curve and the random classifier is called “Area Under Curve” (AUC). The AUC metric is a numerical measure of the ROC curve. It represents an aggregate measure of performance for all possible classification thresholds. A high AUC value indicates that the classification is well done.</p><p>(Classification threshold values will change, for example, when it gets values such as 0.4, 0.5, it will calculate what the success rate is and give us the best result accordingly.)</p><p>To calculate this metric, we need estimated values of the probability of occurrence of a class of the dependent variable.</p><pre>y_prob = log_model.predict_proba(X)[:, 1]<br>roc_auc_score(y, y_prob)</pre><p>0.8393955223880598</p><p><strong>Model Verification (Holdout Method)</strong></p><p>The holdout working principle divides the data set into two: train and test, trains the model on the train set, and tests it on the test set.</p><pre><br>X_train, X_test, y_train, y_test = train_test_split(X,<br>                                                    y,<br>                                                    test_size=0.20,<br>     random_state=17)<br><br>log_model = LogisticRegression().fit(X_train, y_train)<br><br>y_pred = log_model.predict(X_test)<br>y_prob = log_model.predict_proba(X_test)[:, 1] #We also need probability values for AUC values. That&#39;s why we kept them in the y_prob object as well.<br>print(classification_report(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*X8HTJbaqjgFzIh_zTykdUA.png" /></figure><p>When the comparison was made, it became clear that the model might not be as successful as expected against data it had not seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*k6tASXc7AgzrEbiQ7KMOiA.png" /></figure><p>If we look at the prediction rates on the trained data, we observe that the recall and f1 score values have decreased.</p><pre>RocCurveDisplay.from_estimator(log_model, X_test, y_test)<br>plt.title(&#39;ROC Curve&#39;)<br>plt.plot([0, 1], [0, 1], &#39;r--&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*ccZx-YTD8FepapClPe-lZg.png" /></figure><pre>roc_auc_score(y_test, y_prob)</pre><p>0.8755652016639537</p><p>The AUC value has now increased, but we still cannot make a clear comment about the model.</p><p><strong>Model Validation (10-Fold Cross Validation)</strong></p><p>The most accurate way to make the validation process of the model at this point is cross-validation. Let’s make another evaluation with 10-fold cross-validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*g8tEibAMUj7V-tMfuiwfDA.png" /></figure><p>The dataset is divided into 10 parts, the model is built with 9 parts and the test is performed with 1 part. This process is tried for all parts and all validation errors are averaged.</p><pre>y = df[&quot;Outcome&quot;]<br>X = df.drop([&quot;Outcome&quot;], axis=1)<br><br>log_model = LogisticRegression().fit(X, y)<br>cv_results = cross_validate(log_model,<br>                            X, y,<br>                            cv=10,<br>                            scoring=[&quot;accuracy&quot;, &quot;precision&quot;, &quot;recall&quot;, &quot;f1&quot;, &quot;roc_auc&quot;])</pre><p>Let’s call the values we obtained.</p><pre>cv_results[&#39;test_accuracy&#39;].mean()<br>#0.7774042950513538<br>cv_results[&#39;test_precision&#39;].mean()<br>#0.7297924767622267<br>cv_results[&#39;test_recall&#39;].mean()<br>#0.5784765897973445<br>cv_results[&#39;test_f1&#39;].mean()<br>#0.6439787675857748<br>cv_results[&#39;test_roc_auc&#39;].mean()<br>#0.8325422781271838</pre><p>We can say that it is a normal level model. In this article, we have seen how to apply logistic regression, model success and model validation. Thank you for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/logistic-regression-application/">https://canbenli.com.tr/en/blog/logistic-regression-application/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=997f7aac61da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression]]></title>
            <link>https://medium.com/@can-benli/logistic-regression-3e7a85e7b968?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e7a85e7b968</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 09:24:09 GMT</pubDate>
            <atom:updated>2023-10-14T09:24:09.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s7VQzy-wSizyS74Ycve9Q.png" /></figure><p>Logistic regression is one of the machine learning methods and is used for a general purpose classification problem. In this method, the relationship between the independent variables and the dependent variable is attempted to be modeled in a linear manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*LzTv_LKhkwzSxrxFkFdeQQ.png" /></figure><p>When the result of the linear regression equation Z is obtained, this value is given to the Sigmoid function. The sigmoid function produces a probability value between 0 and 1. This probability value expresses the probability that an observation belongs to class 1 and is concluded by comparing it with a certain threshold value. If the probability is greater than a certain threshold value, the observation is assigned to class 1; otherwise it is assigned to class 0. In this way, in the classification problem, the probability of belonging to class 1 is calculated for each observation and a class prediction is made.</p><p>This problem is solved by determining the weights in order to minimize the Log Loss value by minimizing the differences between the actual values and the predicted values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jqCQcGJpU97iujDcGaRjqw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*LF7w6IHu9SJ1nIwC7Uc2Rg.png" /></figure><p>In classical regression methods, when the dependent variable is between classes such as 0 and 1, it may not be possible for the resulting prediction values to always be strictly between 0 and 1. In such cases, the Sigmoid function comes into play. The sigmoid function maps the results of linear regression to between 0 and 1.</p><p>In short, the results transformed by the Sigmoid function based on the values of the independent variables correspond to the probability of occurrence of class 1 of the dependent variable. For example, in a scenario where a variable expresses survival, survival is usually expressed as 1, while non-survival is represented as 0. After this transformation, a probability threshold is typically determined and results exceeding this threshold value are considered 1, while results below it are considered 0.</p><p>This transformation process forms the basis of Logistic Regression and is widely used in artificial intelligence and deep learning classification problems.</p><p><strong>Gradient Descent for Logistic Regression</strong></p><p>Gradient descent is an optimization algorithm that aims to reach the global minimum value and proceeds by starting with randomly selected variables. In the context of logistic regression, gradient descent aims to obtain J(θ) values obtained over the cost function for use during iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*xMfYqE8c9RwGmcfmbQbsWw.png" /></figure><p>hₒ(xᶦ) refers to the predicted values and yᶦ refers to the actual values. In this problem, the loss function is calculated using the log loss expression. J(θ) is calculated by evaluating each observation unit individually. The term hₒ(xᶦ) in the log loss function expresses the predicted probability of occurrence of class 1 of the dependent variable. Therefore, the term -yᶦlog(hₒ(xᶦ)) includes the predicted probability of occurrence of class 1 of the dependent variable, while the term (1-yᶦ)log(1-hₒ(xᶦ)) includes the predicted probability of occurrence of class 1 (i.e., the predicted probability of class 0 not occurring). includes the probability of occurrence).</p><p>At the same time, since the actual values of yᶦ will be 0 or 1 due to the structure of the equation, the terms to the right of the sum symbol will be zero, either -yᶦlog(hₒ(xᶦ)) or (1-yᶦ)log(1-hₒ(xᶦ)).</p><p>In general, this expression is called the cross-entropy loss function. The higher the entropy, the greater the diversity. Therefore, low entropy, i.e. little diversity, in terms of actual value and predicted value is desired. The higher the predicted probability of belonging to a class, the lower the entropy.</p><p>As a result, the closer the actual values and the estimated probability of occurrence are to each other, the lower the loss value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*1awDWZ9DPUPyiYDfHdoe7Q.png" /></figure><p>As a result of using a particular set of weights during a loop, an error value is calculated. Then, the partial derivative of the cost function is taken with respect to the relevant weights. According to the result of this calculation, the value of the weights is corrected. This correction is made in a negative direction against the direction of the resulting value. This process leads to a decrease in error values. Thanks a lot for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/logistic-regression/">https://canbenli.com.tr/en/blog/logistic-regression/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e7a85e7b968" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Success in Classification Problems]]></title>
            <link>https://medium.com/@can-benli/evaluating-success-in-classification-problems-cc30f78b2eb5?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc30f78b2eb5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-problem]]></category>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 12:14:44 GMT</pubDate>
            <atom:updated>2023-12-08T09:38:20.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNtkV89XtxrX39Vq5d-PtQ.png" /></figure><p>Artificial intelligence models and algorithms are evaluated for their ability to make accurate classifications. However, choosing the right metrics and interpreting the results correctly when making this assessment can be quite a complex process. Performance evaluation in classification problems plays a fundamental role in understanding and improving the performance of a model. In this article, we will explore the importance of evaluating success in classification problems and best practices for choosing the right metrics.</p><p><strong>Evaluating Success in Classification Problems</strong></p><p>When we examine the sample customer abandonment data set, the dependent variable of customer abandonment is expressed as Churn. Abandonment status is represented as 1, while non-abandonment status is represented as 0. In this context, the model to be created is aimed at predicting customer abandonment or non-abandonment based on their characteristics. The success of this model depends on the agreement of the predicted and actual value in the relevant observation unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*8EQwmk7L2dqVpoCyX7gfsQ.png" /></figure><p>There are various success metrics used to evaluate the success of classification models. These metrics include Confusion Matrix, Accuracy, Precision, Recall, F1 Score and ROC Curve.</p><p><strong>Confusion Matrix</strong></p><p>Confusion Matrix is an important tool used to evaluate the performance of a classification model. It visualizes different situations by comparing the model’s prediction results with the actual values.</p><ul><li>True Positive (TP): Cases where the model correctly predicts class 1.</li><li>True Negative (TN): Cases where the model correctly predicts class 0.</li><li>False Positive (FP): Situations where the model incorrectly predicts class 1. (Type one error)</li><li>False Negative (FN): Situations where the model incorrectly predicts class 0. (Type two error, critical error)</li></ul><p>These values are used to better understand the performance of the model and evaluate error types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*L7kcxDND4C4mP55IPpRR1A.png" /></figure><p>By comparing actual values with predicted values, the success of a model can be expressed numerically by the following metrics:</p><p><strong>Accuracy:</strong> It refers to the correct classification rate. The formula <strong>(TP+TN)/(TP+TN+FP+FN)</strong> is used to calculate.</p><p>If the class distribution in the classification problem under consideration is balanced (there is a similar number of data in each class), the accuracy metric can be used. However, if the class distribution is unbalanced, the problem of capturing a lower number of classes may arise. In the case of unbalanced class distribution, precision and sensitivity metrics are examined instead of accuracy.</p><p><strong>Precision:</strong> It expresses the success rate of the predictions of the positive class (1). That is, it shows how many of the predicted positive classes (classes predicted as 1) are actually positive. The first type of error is dealt with. Focuses on prediction success. The formula <strong>TP/(TP+FP) </strong>is used to calculate.</p><p><strong>Recall:</strong> It refers to the rate of correct prediction of the positive class (1). It shows how many of the predicted positive classes were predicted correctly. The second type of error is dealt with. It determines the cost of oversight, so it is an important metric. It focuses on the success of capturing the facts. The formula TP/(TP+FN) is used to calculate.</p><p><strong>F1 Score: It is the harmonic average of sensitivity and sensitivity values. Contains both Precision and Recall values. The formula 2*(Precision*Recall)/(Precision+Recall) is used to calculate.</strong></p><p><strong>Probability threshold value in classifications (classification threshold)</strong></p><p>When evaluating the success of classification models, we first need to obtain the predicted values of the dependent variable. After this step, we can calculate success metrics. At this point, we consider the probability values obtained using the Sigmoid function. Using these probability values, classification predictions are made based on values that exceed or fall below a determined threshold value. This threshold value is called “classification threshold”.</p><p>To explain with an example: Suppose we estimate the probability that a customer will abandon. Probability value calculated with the sigmoid function, for example 0.7. If the threshold value we set is 0.5, we predict this customer to be in the “might abandon” class because 0.7 &gt; 0.5. If the threshold value is higher than 0.7, the class prediction may change.</p><p>This threshold value can affect the model’s metrics such as sensitivity and precision. As the threshold value increases, true positives may increase, true negatives may decrease, and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*JSWskGMB8aNXL63RtnQCdA.jpeg" /></figure><p>In this example, classes predicted at a threshold value of 0.50 are explained according to the probability values of the first class. If the threshold value increases, the accuracy value may decrease. Therefore, the selection of the threshold value at which calculations will be made is important and different threshold values should be considered. To solve this type of problem, the ROC curve (Receiver Operating Characteristic curve) method is used in classification problems.</p><p>The ROC curve allows us to visually analyze the sensitivity (recall) and 1 — specificity ratios when different threshold values are used. It allows us to get an idea about how the sensitivity and specificity performance of the model changes by changing the threshold values. The area under the ROC curve (AUC) is used to evaluate the overall performance of the model. If the area under the ROC curve is high, it can be said that the model performs well at different threshold values.</p><p><strong>Roc Curve</strong></p><p>Without a model, when only an average value is predicted, the success achieved is expected to be similar to the results predicted by a random classifier. As the ROC curves above the random classifier line concavely approach a perfect classifier, the success rate increases. These curves are created through the complexity matrix by calculating True Positive and False Positive values according to possible threshold values.</p><p>The area between the ROC curve and the random classifier is called “Area Under Curve” (AUC). The AUC metric is a numerical measure of the ROC curve. It represents an aggregate measure of performance for all possible classification thresholds. A high AUC value indicates that the classification is well done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*DG9e6Fx4VfUvPDC3YqAuQw.png" /></figure><p><strong>LOG LOSS</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*Ta9MeJQnbD4dfLNQAEe0ug.png" /></figure><p>Log loss is a metric that evaluates the success of the model and is also used for optimization. It is important for optimization of both hyperparameters and weights. This metric is also called “cross entropy”. The term cross-entropy is used in the field of information theory and measures the difference between the estimate of a probability distribution and the actual distribution.</p><p>The log loss metric attempts to measure how well the predictions of the classification model match the actual values. This fit is expressed through cross-entropy. The lower the log loss value, the closer the model’s predictions are to the real values and the higher the success.</p><p>The term entropy means diversity. High entropy, that is, cross entropy, indicates that the information content and diversity of predictions are high. Therefore, low entropy is desirable because it reflects more precise and reliable predictions. While the success evaluation made through log loss tries to measure how close the predictions are to the real values, it also makes a measurement in terms of entropy.</p><p>In this post, I mentioned about success evaluation methods in classification problems. Thank you for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/evaluating-success-in-classification-problems/">https://canbenli.com.tr/en/blog/evaluating-success-in-classification-problems/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc30f78b2eb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression Analysis]]></title>
            <link>https://medium.com/@can-benli/linear-regression-1a28c2aabbc6?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a28c2aabbc6</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 11:26:42 GMT</pubDate>
            <atom:updated>2023-11-23T12:42:56.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwOO74hodvOpsTZ3Um8yzA.png" /></figure><p>More and more data is produced in the digital world every day, and analyzing this data correctly has become the key to gaining competitive advantage in the business world. Data analysis plays an important role in many fields, from the world of science to business. Linear regression is a powerful statistical method frequently used in data analysis processes. In this article, we will explain the basic concepts of linear regression and then examine how to create a simple linear regression model using Python.</p><p><strong>Linear Regression</strong></p><p>Linear regression is used to predict the value to be predicted by relating it to other variables. While the variable to be predicted is called the dependent variable, other variables that directly affect the variables making the prediction and affecting the result are called independent variables.</p><p>Linear regression analysis is used to understand the relationship between the dependent variable and the independent variable or variables. This analysis aims to examine the effect of the independent variable on the dependent variable. The main goal is to find a mathematical expression that best explains the dependent variable from the independent variables.</p><p>Linear regression is a machine learning algorithm that allows us to relate numerical inputs to numerical outputs and fit data points with a line. In simple linear regression analysis, there are two variables, called x and y. The equation that describes how the dependent variable y is related to the independent variable x is known as the regression model.</p><p>The simple linear regression model is expressed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*4h0s9slvWm3K5Zbb9Di4yw.png" /></figure><p>In this context, b and w are considered model parameters. b represents the constant term and refers to the intersection of the linear equation with the y-axis. w shows the slope of the line and indicates the effect of the independent variable on the dependent variable. The simple linear regression equation is represented graphically as a straight line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPWKEbhmcf2s3xRJy5oTbA.png" /></figure><p>The main purpose of the linear regression algorithm is to find the best fit line by obtaining the best values for b0 and b1. The best fit line is the line where the difference between the predicted values and the actual values is minimum, that is, the error is at the lowest level. The graph of the resulting model results from the equation created with the parameters in which the independent variables best represent the dependent variable.</p><p><strong>Linear Regression Application</strong></p><p>We import the libraries required to create and evaluate the linear regression model. We will use the “sklearn.linear_model” module to create the LinearRegression model, the “sklearn.metrics” module to calculate error metrics, the “sklearn.model_selection” module to split the dataset and cross-validate, and the “pandas” library to process the data.</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, mean_absolute_error<br>from sklearn.model_selection import train_test_split, cross_val_score</pre><p>We load the data set in the “advertising.csv” file using the pandas library.</p><pre>df = pd.read_csv(&quot;advertising.csv&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*cr1mA1KdZiiQ40GQYlCz7g.png" /></figure><p>We make a choice by assuming that there is a relationship between two variables in the data set. For example, let’s select the variables “TV” and “sales”. The “sales” variable is our dependent variable in this example. It can be thought that it will be discussed how sales numbers behave compared to TV commercials. We define x and y variables as independent and dependent variables.</p><pre>X = df[[&quot;TV&quot;]]<br>y = df[[&quot;sales&quot;]]</pre><p>We create a linear regression model with the LinearRegression() function and train it with the data set (X and y).</p><pre>reg_model = LinearRegression().fit(X, y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*4h0s9slvWm3K5Zbb9Di4yw.png" /></figure><p>The intercept and coefficient (slope) values of the created linear regression model should be obtained. Let’s get the cutoff point with “intercept_” and the coefficient values with “coef_”.</p><pre># constant value for expression &quot;b&quot;<br>reg_model.intercept_[0]</pre><p>7.032593549127693</p><pre># coefficient of tv (w1)<br>reg_model.coef_[0][0]</pre><p>0.047536640433019764</p><p>So how to make a prediction? For example, “How much sales are expected if 150 units of TV are spent?” Let’s answer the question.</p><pre>reg_model.intercept_[0] + reg_model.coef_[0][0]*150</pre><p>14.163089614080658</p><pre>df.describe().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*OwxUSBu7SnfjG8XAkvXLPg.png" /></figure><p>We see that the maximum value in the “TV” variable is 296.40. In other words, thanks to the model, we can see what the sales amount is as a result of higher expenditures. What would our sales be if we spent 500 units of TV?</p><pre>reg_model.intercept_[0] + reg_model.coef_[0][0]*500</pre><p>30.800913765637574</p><p>A sales estimate of 30 units was made. Now let’s see our regression line by visualizing the model.</p><p><strong>Visualization of the Model</strong></p><pre>g = sns.regplot(x=X, y=y, scatter_kws={&#39;color&#39;: &#39;b&#39;, &#39;s&#39;: 9},ci=False, color=&quot;r&quot;)</pre><p>We create the linear regression graph using the “Seaborn” library. We said that x data represents the independent variable and y represents the dependent variable. You can adjust the color and size of the scatter points with the “scatter_kws” parameter. Confidence interval display is turned off with “ci=False”. Otherwise chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*AQs4VtdSSm5CnocOgfR5VQ.png" /></figure><p>We determine the chart title. The intercept term is taken with “reg_model.intercept_[0]” and the slope coefficient is taken with “reg_model.coef_[0][0]”. We kept these values above.</p><pre>g.set_title(f&quot;Sales={round(reg_model.intercept_[0],2)}+TV*{round(reg_model.coef_[0][0],2)}&quot;)</pre><p>Let’s determine the labels of the y-axis and x-axis. The Y axis is labeled “Number of Sales” while the X axis is labeled “TV expenses”.</p><pre>g.set_ylabel(&quot;Number of Sales&quot;)<br>g.set_xlabel(&quot;TV expenses&quot;)<br><br>plt.xlim(-10, 310)<br>plt.ylim(bottom=0)</pre><p>We limit the display range for the x-axis (TV spending). The X-axis displays between -10 and 310, while the Y-axis (Number of Sales) displays its lowest value as 0.</p><pre>g = sns.regplot(x=X, y=y, scatter_kws={&#39;color&#39;: &#39;b&#39;, &#39;s&#39;: 9}, ci=False, color=&quot;r&quot;)<br>g.set_title(f&quot;Sales = {round(reg_model.intercept_[0], 2)} + TV*{round(reg_model.coef_[0][0], 2)}&quot;)<br>g.set_ylabel(&quot;Number of Sales&quot;)<br>g.set_xlabel(&quot;TV expenses&quot;)<br>plt.xlim(-10, 310)<br>plt.ylim(bottom=0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*Tgep6iUQPjPAsnMaQIX3Bw.png" /></figure><p><strong>Prediction Success</strong></p><p>When we evaluate our linear regression model, it is important to understand the means first. The mean of the sales data we have is 14.02 units and the standard deviation is 5.22 units. This generally means that our sales average between 9 and 19 units. An ideal prediction model aims to minimize the difference between actual values and predictions.</p><pre>y.mean()</pre><p>14.02</p><pre>y.std()</pre><p>5.22</p><p><strong>MSE</strong></p><pre>y_pred = reg_model.predict(X)<br><br>mean_squared_error(y, y_pred)</pre><p>10.512652915656757</p><p>MSE value was found to be 10.51. This shows that on average our model makes predictions that are 10.51 units away from the true values. Considering the spread and standard deviation of our data, we can say that this value is high. A lower MSE means more consistent estimates.</p><p><strong>RMSE</strong></p><pre>np.sqrt(mean_squared_error(y, y_pred))</pre><p>3.2423221486546887</p><p>RMSE value was calculated as 3.24. This value shows that the predictions are on average 3.24 units away from the real values. This means that our model made this big of an error on average in its sales forecasts.</p><p><strong>MAE</strong></p><pre>mean_absolute_error(y, y_pred)</pre><p>2.549806038927486</p><p>MAE value was found to be 2.55. MAE measures the average absolute distance of predictions from actual values. This value shows that our model makes an overall error of 2.55 units.</p><p><strong>R2 score</strong></p><pre>reg_model.score(X, y)</pre><p>0.611875050850071</p><p>It is a very important metric for the success of the linear regression models. It expresses the percentage of independent variables in the dataset explaining the dependent variables.</p><p>R² score was calculated as 0.61. This value indicates that our model can explain approximately 61% of the variance in the dataset. So, we can say that our model is moderately successful in explaining sales.</p><p><strong>Conclusion and Evaluation</strong></p><p>Our linear regression model can produce results close to the average in sales forecasts. However, we are still at a point where there is room for improvement. In particular, we can improve prediction accuracy by such methods as adding more data or using a more complex model.</p><p>In this post, “What is Linear Regression?”, “How is it applied?”, “How is it evaluated?” I answered your questions. Thanks for reading.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/linear-regression/">https://canbenli.com.tr/en/blog/linear-regression/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a28c2aabbc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Weights in Regression Models]]></title>
            <link>https://medium.com/@can-benli/finding-weights-in-regression-models-e195ad5d9423?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/e195ad5d9423</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 11:11:53 GMT</pubDate>
            <atom:updated>2023-10-01T11:35:14.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_J4hyZXPNze9rIj6M-BexQ.png" /></figure><p>The main goal in the process of estimating parameters is to determine the constants and weights that will provide the smallest error. In this process, the Cost Function is used, similar to the Mean Square Error (MSE) expression. Our aim is to analyze the error values calculated for certain constant and weight combinations and to choose these constant and weight values in a way that provides the smallest value for the Cost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*emv-B3FUwOyejSJVNxH2vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*VSpbCFv5Q3AuLYuF5eBQ1w.png" /></figure><p>For this purpose, techniques such as Normal Equations Method and Gradient Descent Method are used to find the optimum weights and constant value. These methods allow parameters in regression models to be determined accurately so that the model can be best fitted to the data.</p><p><strong>Method of Normal Equations (Least Squares Method): </strong>As an analytical solution, it is based on differentiation and is expressed in matrix form. This method is used when there is only one dependent variable and one independent variable in a model, partial derivatives are taken for these variables separately and set equal to zero. In this way, each parameter in the model, for example b₀ and b₁, is obtained. If a multivariate model is being studied, partial derivatives related to the parameters are calculated in a similar way. As a result of these partial derivatives, a matrix is formed. Solving this matrix provides the predicted ß values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*SLFGT7F19GM2uJRmjS-iTg.png" /></figure><p>The Normal Equations Method involves inverting the matrix in the analysis of multivariate models. However, this process can become complex as the number of observations and variables increases. Therefore, especially in large data sets or high-dimensional data analysis, the use of optimization-based approaches such as the Gradient Descent Method becomes important. The Gradient Descent Method can work faster and more efficiently on large data sets and multidimensional models because it tries to reach the minimum by updating step by step. Therefore, it is important to choose the right method to effectively estimate model parameters.</p><p><strong>Gradient Descent Method (Optimization Solution):</strong> It is a frequently used method in the fields of machine learning and optimization. Its main purpose is to find appropriate parameter values to minimize or maximize a function. This method can be used for any differentiable function and aims to optimize the minimum or maximum points of this function.</p><p>The Gradient Descent method starts by taking partial derivatives of the function according to the relevant parameter. These partial derivatives form the gradient value and specify the direction of maximum increase of the function. The method updates the parameter values at each iteration by moving in the negative direction of the gradient. These updates aim to converge towards the minimum value of the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*HFN73U1cpWuZnwzpMI5ETw.png" /></figure><p>In other words, the Gradient Descent Method aims to obtain the minimum or maximum value of the relevant function by interactively updating the parameter values by moving in the negative direction of the gradient, called the “steepest descent” direction. In this context, it is used as an effective tool to minimize the Cost function and find optimum parameter values by using it in regression models or other optimization problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*YeM-teQKiUCpSOYrp40ycg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsBakfF2Geh1zgY4HJbwFQ.gif" /></figure><p>In gradient descent, this cost function can be expressed in a different notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*Fk4Limyp-mS8Lx6gjp8YaA.png" /></figure><p>Here hₒ(xᶦ) represents the predicted values and yᶦ values represent the actual values. Error is measured by squaring the difference between actual values and predicted values. This is a variant of MSE (Mean Square Error). The m value, which is the number of observations, is multiplied by 2 to eliminate the 2 in the square operation we use in partial derivatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*RXslIdy1U9E5lUd7_nbcAw.png" /></figure><p>A graph showing how the cost function changes according to changing weight values is examined. The Gradient Descent method aims to find the optimal value of the weight by moving on this graph and aims to reach the lowest point of the graph. The cost function is expressed as J(θ₀, θ₁) and is tried to be minimized according to the parameters θ₀ and θ₁. For this purpose, first partial derivatives are calculated according to the relevant parameters. Then, the weight values are updated with the negative value of these partial derivatives. This process is called “Update Rule”. The reversal process takes place according to the alpha value called “Learning Rate”, which can be set by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*KaOHnLUjwQzmukZ_JKnCfg.jpeg" /></figure><p>A large Learning Rate (α) value may lead to sudden and extreme changes, which carries the risk of the algorithm quickly going in the wrong direction. On the other hand, if the Learning Rate is too small, we progress towards the goal very slowly, which requires too many updates, which can lead to wasted time. Choosing the most appropriate Learning Rate helps us reach the minimum in the fastest and most accurate way.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/finding-weights-in-regression-models/">https://canbenli.com.tr/en/blog/finding-weights-in-regression-models/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e195ad5d9423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Success in Regression Models]]></title>
            <link>https://medium.com/@can-benli/evaluating-success-in-regression-models-eec59f24fef2?source=rss-4bdcf9d3f64------2</link>
            <guid isPermaLink="false">https://medium.com/p/eec59f24fef2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[M. Can Benli]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 11:08:06 GMT</pubDate>
            <atom:updated>2023-09-30T11:08:06.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzIzsV7ARn9KijaNx0bK1w.png" /></figure><p>With the wealth of data brought by the digital age, the business world is focusing on gaining valuable insights from complex data sets. Navigating this big data ocean has become the key to gaining competitive advantage and creating the right strategies. This is exactly where regression models come into play. As a powerful branch of data science and statistics, regression encompasses a number of important applications, from predicting the future to analyzing market trends. However, evaluating the success of regression models is vital to obtaining accurate results. In this blog post, we will explore the importance of evaluating success in regression models and what the metrics used mean.</p><p><strong>Evaluating Success in Regression Models</strong></p><p><strong>MSE (Mean Square Error)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*MXI9opwJQS8_wy91MAE8Vg.png" /></figure><p>MSE, that is, Mean Square Error, is calculated by dividing the sum of the squares of the differences between the actual values and the predicted values by the number of observations. In this metric, squaring the errors prevents positive and negative values from canceling each other, allowing us to measure the magnitude of the errors more accurately. However, squaring may overscale the magnitude of errors. As a solution to this situation, RMSE (Root Mean Square Error) and MAE (Mean Absolute Error) metrics come into play.</p><p><strong>RMSE (Root Mean Square Error)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*LbU_jd_-73hFOlqt71b2lw.png" /></figure><p>RMSE is used to avoid inflation in MSE and obtain more accurate measurements. Unlike MSE, the RMSE metric measures errors by squaring them and then taking their square root. In this way, the effect of large error values is more balanced.</p><p><strong>MAE (Mean Absolute Error)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*6qD-82oQI8b1nVQ_Sp9hZQ.png" /></figure><p>MAE serves a similar purpose to RMSE, but has a different approach. It evaluates the differences (i.e. error values) between actual values and predicted values in absolute value. This maintains the balance between negative and positive errors and also prevents the magnitude of errors from becoming overinflated. Therefore, these metrics are used to evaluate the predictive success of regression models and are important measures used to obtain accurate results.</p><p>Check out my website :)</p><p><a href="https://canbenli.com.tr/en/blog/evaluating-success-in-regression-models/">https://canbenli.com.tr/en/blog/evaluating-success-in-regression-models/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eec59f24fef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>