<?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 Eduardo Furtado on Medium]]></title>
        <description><![CDATA[Stories by Eduardo Furtado on Medium]]></description>
        <link>https://medium.com/@eduardoftdo?source=rss-6b2457c7e84d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*yop0LTn1wdVg7PSE0H32Hg.jpeg</url>
            <title>Stories by Eduardo Furtado on Medium</title>
            <link>https://medium.com/@eduardoftdo?source=rss-6b2457c7e84d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:34:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eduardoftdo/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[Using Association Rules with categorical data]]></title>
            <link>https://medium.com/data-science/using-association-rules-with-categorical-data-e984f8bb8ee4?source=rss-6b2457c7e84d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e984f8bb8ee4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apriori]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[association-rule]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Eduardo Furtado]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 13:21:13 GMT</pubDate>
            <atom:updated>2020-04-26T20:51:49.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Association Rules for HR Analysis</h3><h4>Or: how to use Apriori with data other than basket shop analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QbWawzvbQj3ChVoS" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Association Rules algorithms such as <strong>Apriori </strong>are a great way to find what items regularly occur together in your dataset and see their relationship. <br>It is an unsupervised machine learning model commonly used to find relationships in transactions, eg. clients purchases.</p><p>An item is considered frequent if its occurrences is <em>greater than the threshold</em> we set. If you have 100 lines of data and set a threshold of 0.1, everything that happens more than 10 times will show in our result.</p><p>In this example, we’ll use Apriori for a different type of problem. We are going to use an HR dataset that contains ages, gender, level of education, etc and we will try to find the frequent characteristics that happen when the employees <em>do not have Attrition</em>.</p><p>Firstly a quick recap of the main Apriori components:</p><blockquote><strong><em>Support </em></strong><em>is how much an item appears</em><br>freq(A, B)/Total</blockquote><blockquote><strong><em>Confidence </em></strong><em>is the probability of B happening given that A happened</em><br>freq(A, B)/freq(A)</blockquote><blockquote><strong><em>Lift </em></strong><em>is similar to the confidence but it also accounts for how popular B is</em><br>freq(A, B)/support(A)*Support(B)</blockquote><p>In this example, we’ll use the IBM HR Analytics Employee Attrition &amp; Performance from Kaggle which you can download from the link below:</p><p><a href="https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset">IBM HR Analytics Employee Attrition &amp; Performance</a></p><p>This code will be written in Python using the MLxtend library (<a href="http://rasbt.github.io/mlxtend/">http://rasbt.github.io/mlxtend/</a>)</p><p>Firstly, we import our libraries. For this project, only <strong>Pandas </strong>and <strong>MLxtend </strong>are needed.</p><pre>import pandas as pd<br>from mlxtend.frequent_patterns import apriori<br>from mlxtend.frequent_patterns import association_rules</pre><p>After reading the data, we can see that there are 35 columns to work with but we will only use a few that look more interesting to us.</p><p>There are a couple of columns that would be nice to use but they <strong>are not categorical</strong>, so what we can do is create <em>bins </em>for them. Pandas <strong>qcut </strong>function can divide the Age, DistanceFromHome and HourlyRate columns into bins of 4 for us.</p><pre>pd.qcut(df[&#39;Age&#39;], q=4)</pre><p>This piece of code shows us that the Age column could be divided in these 4 categories:</p><p><em>Categories (4, interval[float64]): [(17.999, 30.0] &lt; (30.0, 36.0] &lt; (36.0, 43.0] &lt; (43.0, 60.0]]</em></p><p>So we can create an Age_Range column like so:</p><pre>df[&#39;Age_Range&#39;] = pd.qcut(df[&#39;Age&#39;], q=4, labels=[&#39;&lt;=30&#39;, &#39;&gt;30 &lt;=36&#39;, &#39;&gt;36 &lt;=43&#39;, &#39;&gt;43&#39;])</pre><p>After doing the same for DistanceFromHome and HourlyRate now we have to prepare our data for the algorithm. Apriori only accepts <strong>boolean values</strong>, so instead of sending the MaritalStatus column with ‘Single’, ‘Married’ and ‘Divorced’ values we will convert this into 3 different columns called ‘MaritalStatus_Single’, ‘MaritalStatus_Married’ and ‘MaritalStatus_Divorced’ with 0 or 1 values in them.</p><p>For this, the Pandas <strong>get_dummies</strong> function can be used for each column that needs to be converted. First we’ll create a list with all the columns that are going to used, and also a second list with the remaining columns. After using get_dummies, the original columns will be removed and only the boolean columns will be there, however, the unused columns are still there too, so we drop them.</p><pre>columns = [&#39;Attrition&#39;,<br>          &#39;Age_Range&#39;,<br>          &#39;BusinessTravel&#39;,<br>          &#39;Department&#39;,<br>          &#39;DistanceFromHome_Range&#39;,<br>          &#39;Education&#39;,<br>          &#39;EducationField&#39;,<br>          &#39;EnvironmentSatisfaction&#39;,<br>          &#39;Gender&#39;,<br>          &#39;HourlyRate_Range&#39;,<br>          &#39;JobInvolvement&#39;,<br>          &#39;JobLevel&#39;,<br>          &#39;JobRole&#39;,<br>          &#39;JobSatisfaction&#39;,<br>          &#39;MaritalStatus&#39;]</pre><pre>not_used_columns = list(set(df.columns.to_list()) - set(columns))</pre><pre>df = pd.get_dummies(df, columns=columns)</pre><pre>df.drop(labels=not_used_columns, axis=1, inplace=True)</pre><p>Now we have a dataframe ready to use and generate the frequent items.</p><p>Our dataset has a total of 1470 lines so let’s start choosing a <em>minimum support of 0.05</em>. This means that only results that occurred <strong>more than 73 times</strong> in our data will be considered. And <em>max_len</em> is the amount of columns combinations generated in the antecedents column.</p><pre>#Apriori min support<br>min_support = 0.05</pre><pre>#Max lenght of apriori n-grams<br>max_len = 3</pre><pre>frequent_items = apriori(df, use_colnames=True, min_support=min_support, max_len=max_len + 1)</pre><pre>rules = association_rules(frequent_items, metric=&#39;lift&#39;, min_threshold=1)</pre><pre>rules.head(10).sort_values(by=&#39;confidence&#39;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*La-sTQsRhYrw2Q7HNPGQHA.png" /><figcaption>Association Rules results</figcaption></figure><p>That’s it! Now you can see the frequent relationships in the dataset.</p><p>But what if we want to know only what gives us <strong>‘Attrition_Yes’ </strong>or <strong>‘Attrition_No’</strong> in the consequents column?</p><p>First of all, let’s see how many occurrences of each there is in our dataframe.</p><pre>df[&#39;Attrition_No&#39;].value_counts()</pre><pre>#1     1233<br>#0     237<br>#Name: Attrition_No, dtype: int64</pre><p>There are way more cases of <em>No</em> than <em>Yes</em> so we’ll also need to take that in consideration choosing our threshold since one is more common than the other.</p><p>For <em>No</em>, let’s increase the threshold to 0.1 and filter the consequents column for <strong>Attrition_No</strong>:</p><pre>#Apriori min support<br>min_support = 0.1</pre><pre>#Max lenght of apriori n-grams<br>max_len = 3</pre><pre>frequent_items = apriori(df, use_colnames=True, min_support=min_support, max_len=max_len + 1)<br>rules = association_rules(frequent_items, metric=&#39;lift&#39;, min_threshold=1)</pre><pre>target = &#39;{\&#39;Attrition_No\&#39;}&#39;</pre><pre>results_attrition_no = rules[rules[&#39;consequents&#39;].astype(str).str.contains(target, na=False)].sort_values(by=&#39;confidence&#39;, ascending=False)</pre><pre>results_attrition_no.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*y1bXaZrcGMpXCXslGaDOyg.png" /><figcaption>Association Rules results with only Attrition_No in the consequents column</figcaption></figure><p>Now we can see that a person that is from the Research &amp; Development Department and Job Level 2 happens 11% of the time in our dataset, however <strong>almost 95% of those</strong> <strong>do not have Attrition</strong>.</p><p>Sidenote: the antecedents and consequents columns are frozensets which look like this:</p><p><em>array([frozenset({‘JobSatisfaction_4’, ‘JobLevel_2’}),<br> frozenset({‘Department_Research_&amp;_Development’, ‘JobLevel_2’}),<br> frozenset({‘Department_Research_&amp;_Development’, ‘JobInvolvement_3’, ‘JobLevel_2’})…</em></p><p>If you want to beautify it and export this result you can use this piece of code:</p><pre>df[&#39;antecedents&#39;] = df[&#39;antecedents&#39;].apply(lambda x: &#39;,&#39;.join(list(x))).astype(&#39;unicode&#39;)</pre><pre>df[&#39;antecedents&#39;] = df[&#39;antecedents&#39;].str.title().str.replace(&#39;_&#39;, &#39; &#39;)</pre><p>Now let’s change our threshold to 0.02 and see what we have for <strong>Attrition_Yes</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*hmpVnIdypk8VnTdIM-KTpQ.png" /><figcaption>Association Rules results with only Attrition_Yes in the consequents column</figcaption></figure><p>The biggest confidence is for people younger than 30 years old, single and Job Level 1. But differently from the previous case, <em>only 45% of those cases have Attrition</em>.</p><p>And that’s the very basic of using Apriori with HR data! Hope you try it in your next project and find new relationships in your dataset that can give you more insights to your problem.</p><p>You can download all the notebook used to create this post here: <a href="https://gist.github.com/eduardoftdo/e3d2b7ca4a06d8d86b144482d0aed5a1">https://gist.github.com/eduardoftdo/e3d2b7ca4a06d8d86b144482d0aed5a1</a></p><p>If you have any questions and would like to contact me, feel free to send a message at <a href="https://www.linkedin.com/in/eduardo-furtado/">https://www.linkedin.com/in/eduardo-furtado/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e984f8bb8ee4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-association-rules-with-categorical-data-e984f8bb8ee4">Using Association Rules with categorical data</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>