<?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 Elena Jolkver on Medium]]></title>
        <description><![CDATA[Stories by Elena Jolkver on Medium]]></description>
        <link>https://medium.com/@elena-jolkver?source=rss-d6af391a93a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vJjxhxTAHTY5bCN_8FQLRg.jpeg</url>
            <title>Stories by Elena Jolkver on Medium</title>
            <link>https://medium.com/@elena-jolkver?source=rss-d6af391a93a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:44:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elena-jolkver/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[An intuition for AUC and Harrell’s C]]></title>
            <link>https://medium.com/data-science/get-an-intuition-for-auc-and-harrells-c-18df56220969?source=rss-d6af391a93a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/18df56220969</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[concordance]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[survival-analysis]]></category>
            <category><![CDATA[model-performance]]></category>
            <dc:creator><![CDATA[Elena Jolkver]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 05:50:57 GMT</pubDate>
            <atom:updated>2023-09-18T18:27:48.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Intuition for AUC and Harrell’s C</h3><h4>A graphical approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxn2lEjWiNBNbZmUArYZWA.jpeg" /><figcaption>Photo by author</figcaption></figure><p>Everyone venturing into the realm of machine learning or predictive modeling comes across the concept of model performance testing. Textbooks usually differ only in what the reader learns first: regression with its MSE (mean standard error) or classification with a plethora of performance indicators, like accuracy, sensitivity, or precision, to name a few. While the letter can be calculated as a simple fraction of correct/incorrect predictions and is hence very intuitive, the ROC AUC can be daunting at first. Nevertheless, it is also a frequently used parameter to assess predictor quality. Let’s unpack its mechanics first to understand the nitty-gritty details.</p><h3>Get your head around the AUC first</h3><p>Let’s assume we have built a binary classifier predicting the probability of a sample belonging to a certain class. Our test dataset with known classes yielded the following results, which can be summarized in a confusion matrix and reported in more detail in a table, where the samples have been sorted by the predicted probability of being of class P (positive):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUQOT-OovNtu9MmnR3n0rg.png" /><figcaption>Confusion matrix and detailed prediction table with individual samples’ probabilities. Image by author.</figcaption></figure><p>The ROC AUC is defined as the area under the ROC (receiver operating characteristic) curve. The ROC curve is the plot of the true positive rate (TPR) against the false positive rate (FPR) [<a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">Wikipedia</a>]. The TPR (aka sensitivity) is the ratio of correctly identiefied positive cases out of all positive cases. In our case, the TPR is calculated as 4/5 (four out of five cases have been classified correctly as positive). FPR is calculated as the ratio between the number of negative cases wrongly categorized as positive (false positives) and the total number of actual negative cases. In our case, the FPR is calculated as 2/6 (two out of 6 negative cases were misclassified as positives, if we set the “positivity”-threshold at the probability of 0.5).</p><p>We can plot the ROC curve from TPR and FPR values and calculate the AUC (Area Under Curve):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EoMz7js9Z-8bha1wvmUkA.png" /><figcaption>ROC Curve based on prediction probabilities. Image by author.</figcaption></figure><p>Where did the individual TPR/FPR values for the AUC curve come from? To this end, we consider our probabilities table and calculate TPR/FPR for each sample, setting the probability, at which we consider a sample to be positive, as the one given in the table. Even when we cross the usual level of 0.5, at which samples are usually declared as “negative”, we continue to assign them as positive. Let’s follow this procedure in our example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*V1jt0xgUybzkxZ1_OnAU_Q.png" /><figcaption>Image by author</figcaption></figure><p>One sample out of five positives has been classified correctly as being positive at a threshold of 0.81, no sample has been predicted negative. We continue until we encounter the first negative example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*ltDDXhEhNPQBzhQabMgTyg.png" /><figcaption>Image by author</figcaption></figure><p>Here, our TPR stalls at the previous value (3 out of 5 positive samples have been predicted correctly), but FPR increments, we have erroneously assigned one out of six negative samples to the positive class. We continue until the very end:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*weqGMGfjRrvXDmX6Z9rNRA.png" /><figcaption>Image by author</figcaption></figure><p>Et voilà: we arrive at the complete table which is used to create the ROC curve.</p><h3>Why Harrell’s C is nothing but the AUC</h3><p>But what about Harrell’s C-index (also known as the concordance index or C-index)? Consider the particular task to predict death upon the occurrence of a particular disease, say cancer. Eventually, all patients will die, irrespective of cancer — a simple binary classifier won’t be of much help. Survival models take into account the duration until the outcome (death). The sooner the event occurs, the higher the risk of the individual to encounter the outcome. If you were to assess the quality of a survival model, you would look at the C-index (aka Concordance, aka Harrell’s C).</p><p>In order to understand the calculation of the C-index, we need to introduce two new concepts: permissible and concordant pairs. Permissible pairs are pairs of samples (say: patients) with different outcomes during observation, i.e. while the experiment was conducted, one patient of such a pair experienced the outcome, while the other was censored (i.e. has not reached the outcome yet). These permissible pairs are then analyzed for whether the individual with the higher risk score experienced the event, while the censored one has not. These cases are called concordant pairs.</p><p>Simplifying a bit, the C-index is calculated as the ratio of the number of concordant pairs to the number of permissible pairs (I omit the case of risk ties for simplicity). Let’s walk through our example, assuming, that we used a survival model which calculated the risk rather than the probability. The following table contains permissible pairs only. The column “Concordance” is set to 1, if the patient with the higher risk score experienced the event (was one of our “positive” group). The id is simply the row number from the previous table. Pay special attention to the comparison of individual 4 with 5 or 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*EYFFeA17TcZ-Ix274IN76g.png" /><figcaption>Image by author</figcaption></figure><p>This leaves us with 27 concordant pairs out of 30 permissible ones. The ratio (the simplified Harrell’s C) is C = 0.9, which suspiciously reminds us of the previously calculated AUC.</p><p>We can construct a concordance matrix that visualizes how the C statistic is computed, as suggested by <a href="https://doi.org/10.1186/s12911-019-1014-6">Carrington et al</a>. The plot shows the risk scores of actual positives vs. the risk scores of actual negatives and displays the proportion of correctly ranked pairs (green) out of all pairs (green + red) if we interpret each grid square as the representation of a sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv-cRRFmd5_DzVafIGwP6g.png" /><figcaption>Concordance matrix for the calculation of Harrell’s C. Image by author</figcaption></figure><p>The concordance matrix shows the correctly ranked pairs in concordance toward the bottom-right, incorrectly ranked pairs toward the top-left, and a border in between which exactly corresponds to the ROC curve we have seen before.</p><p>Unpacking the process of building up a ROC curve and the concordance matrix, we recognize a similarity: in either case we ranked our samples according to their probability/risk score and checked, whether the ranking corresponded to the ground truth. The higher we set the probability threshold for classification, the more false-positives we get. The lower the risk of actual positive cases, the more likely will an actual negative case be misclassified as positive. Plotting our ranked data accordingly, yielded a curve with the same shape and area, which we call AUC or Harrell’s C, depending on the context.</p><p>I hope this example helped to develop an intuition for both, the AUC and Harrell’s C.</p><h3>Acknowledgment</h3><p>The idea to compare these two parameters arose from a fruitful discussion during the Advanced Machine Learning Study Group meetup, kudos Torsten!</p><p><strong><em>Reference</em></strong><em>: Carrington, A.M., Fieguth, P.W., Qazi, H. et al. A new concordant partial AUC and partial c statistic for imbalanced data in the evaluation of machine learning algorithms. BMC Med Inform Decis Mak </em><strong><em>20</em></strong><em>, 4 (2020). </em><a href="https://doi.org/10.1186/s12911-019-1014-6"><em>https://doi.org/10.1186/s12911-019-1014-6</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18df56220969" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/get-an-intuition-for-auc-and-harrells-c-18df56220969">An intuition for AUC and Harrell’s C</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>
        <item>
            <title><![CDATA[Building classifiers with biased classes: AdaSampling comes to the rescue]]></title>
            <link>https://medium.com/data-science/building-classifiers-with-biased-classes-adasampling-comes-to-the-rescue-8212814264e3?source=rss-d6af391a93a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8212814264e3</guid>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[adasampling]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <dc:creator><![CDATA[Elena Jolkver]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 16:39:08 GMT</pubDate>
            <atom:updated>2022-07-20T16:39:08.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building classifiers with biased classes</h3><h4>AdaSampling comes to the rescue</h4><p>Leaving the world of Kaggle and entering the Real World, a data scientist is frequently (<em>read: always</em>) faced with the problem of dirty data. Besides missing values, different units, duplicates, and whatsoever, a rather common challenge for classification tasks is the noise in data labels. And while some noise problems can be cleaned up by the analyst, others are inherently noisy or imprecise by nature.</p><p>Consider the following task: predict whether a particular protein binds to a certain DNA sequence. Or another: predict what is causing the common cold. Both tasks have in common, that there is little knowledge about the negative class. There are zillions of DNA sequences and only those that happen to be analyzed and published as targets of the particular protein are known to be in the positive class. But the other unpublished sequences are not necessarily negative. They might just not have been analyzed. The same holds true for the common cold: many cases go undetected, as only a few people report having a cold. However, there is a technique that helps you with this challenge: Adaptive sampling, or AdaSampling, as proposed by <a href="https://ieeexplore.ieee.org/document/8329462">Yang</a> et al. (2019).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apyMD6bkh--T_mMG2T4lsw.png" /><figcaption>AdaSampling algorithm, a schematic example. Image by Author.</figcaption></figure><p>In a nutshell, the AdaSampling algorithm performs the following steps:<br>1. Draw a subsample from the dataset. The probability of a given positive/negative sample to be selected is equal to the probability of it being a member of the positive/negative class. <em>(In the figure, the highlighted samples have the highest probability of being members of either class and are therefore selected for modeling.)</em><br>2. Build a classifier with any underlying classification algorithm (e.g. SVM, kNN, LDA, etc.).<br>3. Based on this classification model, predict the probabilities of the samples (within the complete dataset) of being in the positive/negative class.<br>4. Repeat 1–3 until there is no change in class probabilities.</p><p>Basically, you receive a sharpened picture of your classes and get a first clue on which of your negative samples are likely not negatives. Omitting those in your training phase can greatly increase the accuracy of your model.</p><p>Let’s try it out with the AdaSampling package in R. The example dataset is about benign and malignant breast cancers.</p><pre>#install.packages(&quot;AdaSampling&quot;)<br>library(tidyverse)<br>library(AdaSampling)<br>library(caret)</pre><pre># load the example dataset<br>data(brca)<br># some cleanup of the dataset<br>brca$cla &lt;- as.factor(unlist(brca$cla)) <br>brca$nuc &lt;- as.numeric(as.character((brca$nuc))) </pre><pre>#run a PCA<br>brca.pca &lt;- prcomp(brca[,c(1:9)], center = TRUE,scale. = TRUE)<br># append PCA components to dataset<br>brca_withPCA &lt;- cbind(brca, brca.pca$x)<br># plot<br>ggplot(brca_withPCA, aes(x=PC1, y=PC2, color=cla)) +<br>  geom_point() + <br>  ggtitle(&quot;PCA of Breast Cancer Dataset&quot;) +<br>  theme_classic()</pre><p>A PCA on the original dataset looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJKCpECqgKHRAykABA0xxA.png" /><figcaption>Image by Author.</figcaption></figure><p>We actually see two nicely separating classes. We can build a “ground truth” classifier on it. I have picked an SVM and got an accuracy of 0.96 with a sensitivity of 0.91 (code below).</p><pre>#Separate test set<br>set.seed(107)<br>inTrain &lt;- createDataPartition(y = brca$cla,  p = 0.75)<br>train &lt;- brca[ inTrain$Resample1,]<br>test  &lt;- brca[-inTrain$Resample1,]</pre><pre>ctrl &lt;- trainControl(<br>  method = &quot;repeatedcv&quot;, <br>  repeats = 3,<br>  classProbs = TRUE, <br>  summaryFunction = twoClassSummary<br>)<br>model_groundTruth &lt;- train(<br>  cla ~ .,<br>  data = train,<br>  method = &quot;svmLinear&quot;, # Support Vector Machines with Linear Kernel<br>  ## Center and scale the predictors for the training<br>  preProc = c(&quot;center&quot;, &quot;scale&quot;),<br>  trControl = ctrl,<br>  metric = &quot;ROC&quot;<br>)</pre><pre>#predict<br>predicted_groundTruth &lt;- predict(model_groundTruth, newdata = test)<br>confusionMatrix(data = predicted_groundTruth, test$cla, positive=&quot;malignant&quot;)</pre><p>Nice. This is a pretty accurate classifier. Now let’s see AdaSampling in action. We are pretending that we move back in time and are at a time point when some of the now malignant cancers were diagnosed as benign. This is a more real-world scenario as not all cancers diagnosed as benign will stay so forever.</p><pre>#get the classes<br>pos &lt;- which(brca$cla == &quot;malignant&quot;)<br>neg &lt;- which(brca$cla == &quot;benign&quot;)<br>#introduce 40% noise to malignant class<br>brca.cls &lt;- sapply(X = brca$cla, FUN = function(x) {ifelse(x == &quot;benign&quot;, 0, 1)})<br>brca.cls.noisy &lt;- brca.cls<br>set.seed(1)<br>brca.cls.noisy[sample(pos, floor(length(neg) * 0.4))] &lt;- 0</pre><pre>brca$noisy_class &lt;- as.factor(brca.cls.noisy)<br>brca %&gt;% group_by(cla, noisy_class) %&gt;% tally()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*medhCaMOaS9bzEzHpUQi8g.png" /><figcaption>Image by Author.</figcaption></figure><p>We have introduced a measurement error: 95 of cancers, which will become malignant (ground truth), are now being labeled as benign. The PCA looks quite devastating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRBFLsvmghoYSO6gL3-rrA.png" /><figcaption>Image by Author.</figcaption></figure><p>Building a classifier with this data results in a model with an accuracy of 0.81, sensitivity of 0.47, and specificity of 0.99. As expected, this classifier misses a lot of potentially malignant tumors.</p><p>Now it’s time for AdaSampling. The code below shows the details. The procedure is as follows: one needs to tell the algorithm which are the positive and negative samples. Then, it acts as a wrapper around a classification algorithm (I picked kNN, but the package offers many others) and reassigns the classes. Once done, I check how the sample distribution looks like with a PCA, performed on the same features as before:</p><pre># identify positive and negative examples from the noisy dataset<br>Ps &lt;- rownames(brca)[which(brca$noisy_class == 1)]<br>Ns &lt;- rownames(brca)[which(brca$noisy_class == 0)]</pre><pre># apply AdaSampling method on the noisy data. I pick kNN, but other classification methods are available<br>brca.preds &lt;- adaSample(Ps, Ns, train.mat=brca[,1:9], test.mat=brca[,1:9], classifier = &quot;knn&quot;)<br>brca.preds &lt;- as.data.frame(brca.preds)<br>head(brca.preds)<br>brca.preds$Adaclass &lt;- as.factor(ifelse(brca.preds$P &gt; brca.preds$N, &quot;malignant&quot;, &quot;benign&quot;))<br>brca &lt;- cbind(brca, brca.preds[&quot;Adaclass&quot;])</pre><pre>#check the result with PCA first:<br>brca.pca_Ada &lt;- prcomp(brca[,c(1:9)], center = TRUE,scale. = TRUE)<br># append PCA components to dataset<br>brca_withPCA_Ada &lt;- cbind(brca, brca.pca_Ada$x)<br># plot<br>ggplot(brca_withPCA_Ada, aes(x=PC1, y=PC2, color=Adaclass)) +<br>  geom_point() + <br>  ggtitle(&quot;PCA of Breast Cancer Dataset with Noise removed by AdaSampling&quot;)+<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32Hb-zZlnT4fFvLmuM5cAA.png" /><figcaption>Image by Author.</figcaption></figure><p>It’s almost identical to the ground truth! Just for the sake of completeness, I also build a classifier with the cleaned data, which results in a model with an accuracy of 0.96, sensitivity of 0.92, and specificity of 0.99.</p><p>The classifier is as good as the one we built on the dataset without noise. I guess this is due to the dataset and the malignant tumors were easily identifiable by the provided features. In a real-world scenario, it might look different and you can never be sure how good your model actually performs until you have gathered even more true positive and negative examples. Until then, AdaSampling is yet another tool in your toolbox for enhancing your models.</p><p><strong><em>Reference</em></strong><em>: P. Yang, J. T. Ormerod, W. Liu, C. Ma, A. Y. Zomaya and J. Y. H. Yang, “AdaSampling for Positive-Unlabeled and Label Noise Learning With Bioinformatics Applications,” in IEEE Transactions on Cybernetics, vol. 49, no. 5, pp. 1932–1943, May 2019, doi: 10.1109/TCYB.2018.2816984.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8212814264e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-classifiers-with-biased-classes-adasampling-comes-to-the-rescue-8212814264e3">Building classifiers with biased classes: AdaSampling comes to the rescue</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>
        <item>
            <title><![CDATA[A tangible variant of the F value for classification evaluation]]></title>
            <link>https://medium.com/data-science/a-tangible-variant-of-the-f-value-for-classification-evaluation-8a82092e66e4?source=rss-d6af391a93a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a82092e66e4</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Elena Jolkver]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 22:25:17 GMT</pubDate>
            <atom:updated>2021-03-19T20:09:53.618Z</atom:updated>
            <content:encoded><![CDATA[<h4>Justify your model selection comprehensibly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X494Sdt2n5wRvvWL44-ETw.png" /><figcaption>Image by Author</figcaption></figure><p>Once you set out for a classification task and experiment with different classification algorithms, hyperparameter tuning or feature selection, you will need to select your favourite setup. This is by no means a trivial task and requires careful examination of your data structure and on what you want to achieve. Selecting a classifier based on accuracy might be totally inappropriate if you have imbalanced classes — the Matthews coefficient might be the better choice.</p><p>Sometimes you don’t care about the prediction of the non-class (the “0”), in which case you might decide an algorithm based on its sensitivity, i.e. its ability to detect the positive (the “1”) class. However, a super sensitive predictor might be just one always predicting “1” (as in Fig A), which you immediately recognize by its crappy precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*_dJIdfKHXlrHCFRfcGSPCw.png" /></figure><p>So, having the choice between the setup resulting in a classification given in Fig A or Fig B, which should you select? The answer might depend on your task, but a common way to balance your sensitivity with your precision is the F1 measure.</p><p>The F1 measure is a special case of the F-measure, a harmonic mean between two values. In general, the F-value is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*E63hRXS4RmpNMDzCI0GEjw.png" /></figure><p>which, in the case of n=1, turns into the well-known formula (with TP=true positives, FP= false positives, FN=false negatives, TN=true negatives):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*Gb06W85-KzqFP2HCoB7mbA.png" /></figure><p>This is a reasonable compromise between sensitivity and precision, helping you to select an algorithm which will hopefully not skrew up in production. However, once you try to grasp the meaning of the F1 value, you realize how difficult a translation into human language gets. After all, what is a harmonic mean? While you can express precision as the proportion of true positives to predicted positive cases, there is no easy interpretation of the F value.</p><p>This bothered me when arguing for an algorithm based on its F value as well as David Hand and his co-authors at the Australian National University, Canberra [1]. They proposed a slight transformation of the F value to, what they call, “F*”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*s2hkAn-dqo2H5dsrjCzytg.png" /></figure><p>F* can therefore be interpreted as the ratio of true positives over all samples being either true positive, negatives, but positive predicted as well as missed positives. Or, as the ratio of true positives over all samples except the correctly negative predicted. Or, as the ratio of true positives over all misclassified or correctly positive predicted samples. The authors also show that F and F* are tightly correlated and there is unlikely a decision made based on F, which would be made differently based on F*.</p><p>For the practitioner this means that the F value can be safely replaced by F*, gaining interpretability and delivering a more tangible story for customer reports.</p><p>[1] Hand, D.J., Christen, P. &amp; Kirielle, N. F: an interpretable transformation of the F-measure. <em>Mach Learn</em> (2021). <a href="https://doi.org/10.1007/s10994-021-05964-1">https://doi.org/10.1007/s10994-021-05964-1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a82092e66e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-tangible-variant-of-the-f-value-for-classification-evaluation-8a82092e66e4">A tangible variant of the F value for classification evaluation</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>
        <item>
            <title><![CDATA[On reading books, real books, slowly. Or why Martin Eden is worth a hundred coaching books.]]></title>
            <link>https://elena-jolkver.medium.com/on-reading-books-real-books-slowly-or-why-martin-eden-is-worth-a-hundred-coaching-books-86294a7b94ea?source=rss-d6af391a93a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/86294a7b94ea</guid>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[classical-literature]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Elena Jolkver]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 19:40:36 GMT</pubDate>
            <atom:updated>2021-02-17T19:40:36.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpspOBHtKk2bk2X4_5-U0g.jpeg" /><figcaption>Attribution: Eli Francis elifrancis, CC0, via Wikimedia Commons</figcaption></figure><p>Whenever I read yet another post where someone shares his records on reading 1–2–5 books a week I always wonder “Why?”. Other than for training grammar or vocabulary, I have no good reason to follow that practice. And don’t get me wrong — I am not questioning the importance of books, on the contrary, most of my waking time I spend reading textbooks or scientific papers on the subject I want to understand, but I never consider it “reading a book”. This is mere information gathering and the channel you use largely depends on your preference, be it youtube lectures, articles or textbooks.</p><p>The next level of books I consider are non-fiction books you read out of curiosity. And here, the question lurks again: “why rushing”? While reading a book on the history of ancient Rome you might pick up another book that enlightens an aspect you might get interested in. And you should rather follow your curiosity and let your mind go broad rather than stubbornly sticking to the end. Most likely, by that time you have forgotten your sudden interest in ancient mythology and have missed the chance to connect your islands of knowledge.</p><p>The one and only kind of books you might indeed endeavour at an incredible speed without stepping out are those of the self-improvement category. Those that pretend to coach you, but in reality are nothing but cheap popcorn for your brain. They raise some emotions while reading and are forgotten by the turning of the last page. Why? If you have ever read any of those books (or watched a self-optimizing youtube video about minimalism or getting up at 5 am or whatever the youtube algorithm suggests once you step into this rabbit hole) you are familiar with the feeling that once you start following these advices, you become a better person, an upgraded version of yourself. You are ready to do it. You start getting up at 5 am and learning a new language, or reading 5 self-improvement books a week. But what happens next? The answer to this question is elusive and this is the reason why those books are only any good while you are reading them and why self-improvement without a purpose is just as meaningless as feeling sportive after just having bought a yoga mat. The only kind of books that take you by the hand and show you consequences — are novels. Why? Because none of the non-fiction books hypothesize on what happens after you reach a certain goal.</p><p>This is the realm of fiction, this is the novelist, who lets his protagonist reach that very goal and go further. And while following his/her (mis)fortune, you can safely try out the consequences in the parallel universe, where you have already taken this self-optimizing route, while your other self stays in the warmth and coziness of your comfort zone. Let me give you an example.</p><p>Jack London portrays Martin Eden as a smart proletarian, who, due to the lack of money, never had the opportunity to get a formal education. Falling in love with an upper-class girl, he decides to catch up and to prove her his worthiness. He discovers that journals pay better fees than he could ever make working his sweat of and aims at becoming a writer. Years of austerity follow. He barely sleeps, because he must read and write; he barely eats, because he does not get published, but he stubbornly pursues his dream (I bet you hear the self-improvement authors applauding). Finally, he gets recognized and all the major journals want to print his works (even more applause). Yet is this the end? Is he happy? London negates this question. Martin has been an individualist, he pursued his self-improvement for external reasons, namely love and money. But he lost the connection to people of his former life without ever becoming part of the upper class. Instead, he realizes the shallowness, most of those people live their lives. He overshot his target and became even more knowledgeable than his fiancée. He sees no meaning in life anymore, he has no dreams, no aims, nothing to live for.</p><blockquote>Life was ill, or, rather, it had become ill — an unbearable thing.[…] When life became an aching weariness, death was ready to soothe away to everlasting sleep.</blockquote><p>And when he decides to put an end to it:</p><blockquote>Down, down, he swam till his arms and legs grew tired and hardly moved. He knew that he was deep. The pressure on his ear-drums was a pain, and there was a buzzing in his head. His endurance was faltering, but he compelled his arms and legs to drive him deeper until his will snapped and the air drove from his lungs in a great explosive rush. The bubbles rubbed and bounded like tiny balloons against his cheeks and eyes as they took their upward flight. Then came pain and strangulation. This hurt was not death, was the thought that oscillated through his reeling consciousness. Death did not hurt. It was life, the pangs of life, this awful, suffocating feeling; it was the last blow life could deal him.</blockquote><p>Does London provide an alternative version, a universe, where someone having reached his goal would not fall into frustration? For London, all that counts are the real reasons that drive a person for self-improvement. He lets another character, Brissenden, talk to Martin and formulate the real goal, which might hold a life long:</p><blockquote>You see, I’d like to see you a socialist before I’m gone. It will give you a sanction for your existence. It is the one thing that will save you in the time of disappointment that is coming to you.</blockquote><p>Now, without discussing whether socialism might indeed be the sought-after meaning of your life, you get the idea why pursuing self-improvement without the right goal might even be detrimental. Yet how often do you read about all those eventualities, collisions and misfortunes?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNhNMl1b3Ie8BFUCMBZcOA.jpeg" /></figure><p>A book like Martin Eden takes time. It takes time to be digested, to follow the protagonist and the author, who might have a completely different opinion than his characters and who argues, takes different standpoints and provides you, the reader, with food for thought. Take your time and enjoy the pleasure of deciphering the author’s ideas. Do you agree? You don’t have to. You might have your own opinion, which, questioned by the author, might get strengthened or changed, but in any case, you have to work it out. Yet the only way to do so is by giving yourself time to ponder about. A book like Martin Eden might take you one week or one month or even more. But it will be worth a dozen other books. And if this is not the true reason for reading books, real, thought-provoking books … I don’t know what else is.</p><p>Now be the luck to pick up the right book be with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86294a7b94ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[R’s Hierarchical Clustering Illustration — a piece of cake!]]></title>
            <link>https://medium.com/data-science/rs-hierarchical-clustering-illustration-a-piece-of-cake-a2406f48cbf9?source=rss-d6af391a93a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2406f48cbf9</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[hierarchical-clustering]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Elena Jolkver]]></dc:creator>
            <pubDate>Thu, 28 Jan 2021 18:07:02 GMT</pubDate>
            <atom:updated>2021-02-06T16:15:29.102Z</atom:updated>
            <content:encoded><![CDATA[<h3>R’s Hierarchical Clustering Illustration — a piece of cake!</h3><p>A common question in cluster analysis is: “Now what?”. You have plenty of methods to bring some order into your data chaos, without the need of having a pre-defined hypothesis in mind. You could use the classical kMeans, some density based methods like dbscan or hierarchical clustering, which gives you an impression of the hierarchy of clusters in a dataset. However, you are mostly not only interested in which of your samples cluster together, but also, <strong>why</strong> they do so. Only when being able to tell which sample features brought them together and which drove them apart, you get <strong>value </strong>out of your analysis. You move beyond mere description to interpretation and insights.</p><p>Yet you want to make sure that your analysis tells the story all by itself. Do not steal the show. Just provide the right figures, and the insights will be obvious. Recently, I stumbled upon a new package in R, which makes appealing hierarchical clusters a child’s play. It also has a great documentation <a href="https://cran.r-project.org/web/packages/dendextend/vignettes/dendextend.html">here</a>, so I merely provide an appetizer. You can go and explore the nitty-gritty details all by yourself.</p><p>So first we get some data (the mtcars dataset) and run a hierarchical cluster analysis. This is how the standard plot looks like:</p><figure><img alt="Image by author" src="https://cdn-images-1.medium.com/max/934/1*Ji7zrkvZGxPYb95Vq6oG3w.png" /><figcaption>Image by author</figcaption></figure><p>Now we pep it up by loading Tal Galili’s awesome dendextend package and transform the hclust object to a dendrogram. You can color the leaf labels and dendrogram lines (here by engine type), set the size of the labels by some vector (in this case by the number of cylinders) and play around with nodes.</p><figure><img alt="Image by author" src="https://cdn-images-1.medium.com/max/934/1*of3qmIk3ZIJ4t2Sb4lB8IQ.png" /><figcaption>Image by author</figcaption></figure><p>But most importantly, you can add colored bars, which represent your feature levels of the given sample. I have cut continuous variables by their quartiles to assign discrete colors, so you quickly get an impression of feature levels of a given cluster. Thus we can quickly see that the group in the middle with Merc450 series shares a common weight class (wt), rear axle ratio (drat), same number of gears and cylinders, same type of transmission and engine (am, vs), yet the cars differ in displacement and horsepower (disp, hp). Interestingly, the rear axle ratio &amp; mpg combination of the Honda Civic is so far off the Mercedes450 group, that it clusters with Toyota and Fiat, though its other parameters are comparable to Merc450. I wonder where Tesla would have been grouped to, if the dataset was renewed someday.</p><p>Here is the code to get the figures:</p><pre>library(dendextend)<br>library(colorspace) #to translate factors to colors<br>library(plotrix) #to translate hex to color</pre><pre>#run cluster analysis:<br>hccomplete &lt;- hclust(dist(mtcars), method =&quot;complete&quot;)<br>#standard plot<br>plot(hccomplete)<br>#transform the hclust object to a dendrogram<br>dend &lt;- hccomplete %&gt;% as.dendrogram<br>#get colors for factors. Continuous variables are cut by their quartiles, to which the colors are assigned<br>the_bars &lt;- cbind(unname(sapply(rainbow_hcl(length(levels(as.factor(mtcars$cyl))))[c(as.factor(mtcars$cyl))], color.id)), <br>                  unname(sapply(rainbow_hcl(length(levels(as.factor(mtcars$vs))))[c(as.factor(mtcars$vs))], color.id)), <br>                  unname(sapply(rainbow_hcl(length(levels(as.factor(mtcars$am))))[c(as.factor(mtcars$am))], color.id)), <br>                  unname(sapply(rainbow_hcl(length(levels(as.factor(mtcars$gear))))[c(as.factor(mtcars$gear))], color.id)), <br>                  unname(sapply(rainbow_hcl(length(levels(as.factor(mtcars$carb))))[c(as.factor(mtcars$carb))], color.id)),<br>                  sapply(cut(mtcars$mpg,breaks=c(0,unname(quantile(mtcars$mpg))), labels=heat_hcl(5)), color.id),<br>                  sapply(cut(mtcars$disp,breaks=c(0,unname(quantile(mtcars$disp))), labels=heat_hcl(5)), color.id),<br>                  sapply(cut(mtcars$hp,breaks=c(0,unname(quantile(mtcars$hp))), labels=heat_hcl(5)), color.id),<br>                  sapply(cut(mtcars$drat,breaks=c(0,unname(quantile(mtcars$drat))), labels=heat_hcl(5)), color.id),<br>                  sapply(cut(mtcars$wt,breaks=c(0,unname(quantile(mtcars$wt))), labels=heat_hcl(5)), color.id),<br>                  sapply(cut(mtcars$qsec,breaks=c(0,unname(quantile(mtcars$qsec))), labels=heat_hcl(5)), color.id))</pre><pre>#plot awesomely<br>par(mar = c(17,3,2,2))<br>dend %&gt;% set(&quot;branches_col&quot;, ifelse(mtcars$vs ==0, &quot;red&quot;, &quot;blue&quot;)) %&gt;% # change color of branches<br>  set(&quot;labels_col&quot;,  ifelse(mtcars$vs ==0, &quot;red&quot;, &quot;blue&quot;))%&gt;% # change color of labels<br>  set(&quot;labels_cex&quot;, mtcars$cyl/10+0.2 ) %&gt;% # Change size by number of cylinder<br>   set(&quot;nodes_pch&quot;, 19) %&gt;% set(&quot;nodes_cex&quot;, 0.8) %&gt;% set(&quot;nodes_col&quot;, 3) %&gt;% #add nodes<br>  plot(main = &quot;Hierarchical cluster dendrogramm colored by engine (vs) \nFont size by cylinder&quot;) # plot<br>colored_bars(colors = the_bars, dend = dend, rowLabels = c(&quot;cyl&quot;,&quot;vs&quot;,&quot;am&quot;,&quot;gear&quot;,&quot;carb&quot;,&quot;mpg&quot;,&quot;disp&quot;,&quot;hp&quot;,&quot;drat&quot;,&quot;wt&quot;,&quot;qsec&quot;), sort_by_labels_order = FALSE) #sort_by_labels_order = FALSE is very important, otherways you get the colors sorted by their appearance in the dataset rather than in the dendrogram</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2406f48cbf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/rs-hierarchical-clustering-illustration-a-piece-of-cake-a2406f48cbf9">R’s Hierarchical Clustering Illustration — a piece of cake!</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>
        <item>
            <title><![CDATA[Apriori Analysis in R beyond sells]]></title>
            <link>https://medium.com/data-science/apriori-analysis-in-r-beyond-sells-ffdf56c1d95c?source=rss-d6af391a93a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffdf56c1d95c</guid>
            <category><![CDATA[pattern-recognition]]></category>
            <category><![CDATA[apriori-algorithm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Elena Jolkver]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 20:58:05 GMT</pubDate>
            <atom:updated>2021-02-06T16:15:17.046Z</atom:updated>
            <content:encoded><![CDATA[<p>The apriori algorithm is frequently used in the so_called “basket_analysis” to determine whether a given item is bought more frequently in combination with other items (like the famous beer&amp;diaper example). As this is quite a niche use case, I wanted to test whether I could detect any patterns in a dataset not dealing with sells. I started off with the <strong>mushroom dataset</strong> from <a href="http://archive.ics.uci.edu/ml/datasets/Mushroom">here</a>, which contains mushroom records drawn from The Audubon Society Field Guide to North American Mushrooms, limited to 23 species of gilled mushrooms in the Agaricus and Lepiota family. The underlying hypothesis is that I will re-extract the different species based on their description. <br>By the way, one species of Agaricus is the well-known wide-spread salad/pizza/soup/*place your dish here* ingredient: the common button mushroom <em>Agaricus bisporus</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FhwJHEz1xpBCL99B.jpg" /><figcaption>source: By Darkone, CC BY-SA 2.5, <a href="https://commons.wikimedia.org/w/index.php?curid=671026">https://commons.wikimedia.org/w/index.php?curid=671026</a></figcaption></figure><p>First, we read in the datafile and get column names from the agaricus-lepiota.name file. To get the table nicely presented, I had to flip it, so you see the columns and rows swapped, but still can decipher all column names and the first few rows. The dataset contains 22 columns and 8124 rows. Performing a quick check on parameter distribution within each feature we detect that the column “veil_type” contains only one value, so we can get rid of it, as it does not provide any additional information to classify the mushrooms.</p><pre>path &lt;- &quot;my path on computer&quot;<br>df &lt;- read.table(file.path(path, &quot;agaricus-lepiota.data&quot;), sep=&quot;,&quot;)<br>names &lt;- c(&quot;edible&quot;,&quot;cap_shape&quot;, &quot;cap_surface&quot;, &quot;cap_color&quot;, &quot;bruises&quot;,&quot;odor&quot;,&quot;gill_attachment&quot;,&quot;gill_spacing&quot;, &quot;gill_size&quot;,&quot;gill_color&quot;,&quot;stalk_shape&quot;,&quot;stalk_root&quot;,&quot;stalksurface_abovering&quot;,&quot;stalksurface_belowring&quot;,&quot;stalkcolor_abovering&quot;,&quot;stalkcolor_belowring&quot;,&quot;veil_type&quot;,&quot;veil_color&quot;,&quot;ring_number&quot;,&quot;ring_type&quot;,&quot;sporeprint_color&quot;,&quot;population&quot;,&quot;habitat&quot;)<br>colnames(df) &lt;- names<br>as.data.frame(t(head(df))) #the table is flipped for demonstration purposes</pre><pre>#check, if there are columns of constant values<br>for (i in 1:ncol(df)){<br>  if(length(table(df[,i], exclude=NULL))&lt;2){<br>    print(colnames(df)[i])<br>  }<br>}<br>table(df$veil_type, exclude=NULL)<br>#veil_type has only 1 value<br>df &lt;- df[ , -which(names(df) %in% c(&quot;veil_type&quot;))]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*-3ylVx6c2B79iJHZQ0kF1Q.png" /></figure><p>Next, we load the library and transform the dataset to a form which the apriori algorithm implemented in the arules package expects.</p><pre>library(arules)<br>for (i in 1:ncol(df)){<br>  df[,i] &lt;- paste(colnames(df)[i], df[,i], sep=&quot;.&quot;)<br>}<br>## create transactions<br>fungi &lt;- as(df, &quot;transactions&quot;)</pre><p>In order to get a feeling for the algorithm, I first try to find some rules associated with edibility of the mushroom (though, as already mentioned, this is not the goal of the analysis. The strength of apriori should be its feature identification ability, irrespective of a target, as it is usually the case with common machine learning classification algorithms). The rule is a combination of features which are associated with the feature “edible” in the form “{x, y, z} =&gt; edible” (given x, y, z, the feature “edible” follows). However, I need to set a threshold on how confident I want to be about a certain rule. This can be achieved by varying different criteria:<br>The <strong>support </strong>tells us, how frequent the particular feature combination has been observed within the dataset, e.g. a support of 0.1 corresponds to 0.1 x 8124 = 812 samples, meaning that at least 812 samples comply with the rule “x&amp;y&amp;z&amp;edible”. <br>The <strong>confidence </strong>of a rule refers to the frequency of the feature combination given its left hand side: confidence ({x, y, z} =&gt; edible) = x&amp;y&amp;z&amp;edible / x&amp;y&amp;z. This relation answers the question: Of all the mushrooms samples of the dataset, that comply with the rule “x&amp;y&amp;z”, how many also comply with “x&amp;y&amp;z&amp;edible”? <br>The implemented algorithm of the arules package also allows to control for the minimal and maximal length of the rule (minlen, maxlen). Let’s have a look:</p><pre>library(tidyverse)<br>supps &lt;- c(); confs &lt;- c(); nums &lt;- c()<br>for (supp in seq(0.3, 0.7, by=0.05)){<br>  for (conf in seq(0.5, 0.9, by=0.05)){<br>    #run apriori algorithm looping over different support and confidence levels<br>    rules &lt;- apriori(fungi,parameter = list(supp = supp, conf = conf, target = &quot;rules&quot;, minlen=2,maxlen=22))<br>    #limit set of rules to ==&gt;&quot;edible&quot;<br>    rules_sub &lt;- subset(rules, subset = rhs %in% &quot;edible=edible.e&quot;)<br>    #extract results<br>    supps &lt;- c(supps,supp); confs &lt;- c(confs, conf); nums &lt;- c(nums,rules_sub@lhs@data@Dim[2])<br>  }<br>}<br>#combine results to data frame<br>results &lt;- data.frame(support=supps,confidence=confs, count=nums)<br>results %&gt;% arrange(desc(confidence)) %&gt;% head(.)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*VJHTeZ7NSubM6xDrj24L5w.png" /></figure><p>We see that 0.4 x 8124 = 3249 mushroom samples comply with two rules with a =&gt;”edible” condition with a confidence of 0.9. Not bad. Let’s have a closer look at those:</p><pre>#repeat modeling with pre-selected thresholds for support and confidence<br>rules &lt;- apriori(fungi,parameter = list(supp = 0.4, conf = 0.9, target = &quot;rules&quot;, minlen=2,maxlen=22))<br>#limit set of rules to ==&gt;&quot;edible&quot;<br>rules_sub &lt;- subset(rules, subset = rhs %in% &quot;edible=edible.e&quot;)<br>inspect(rules_sub)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*PMPq1Ll7owOWLDhNCxoKgg.png" /></figure><p>And here it is. The apriori algorithm has identified the rule that if there is no odor, the mushroom is edible. This rule has a confidence of 0.97, which means that 97% of all non-smelling mushrooms were edible (in our dataset!). The <strong>lift </strong>of &gt; 1 (which can be read as a kind of correlation between odor and edibility) tells us, that there is a positive correlation between those two features.<br>The second rule is a bit more interesting. It tells us, that there is a positive correlation between broad gills (gill_size) and a smooth stalk surface above ring with the edibility of the mushroom. At least it has been found for 94% of the broad-gill, smooth-stalk specimens of Agarici.<br>Let’s briefly check the result with a quick-and-dirty Random Forest, if we get similar features discriminating for edibility:</p><pre>library(caret)<br>table(df$edible)<br>fit_control &lt;- trainControl(method = &quot;cv&quot;,number = 10)<br>set.seed(123456)<br>rf_fit &lt;- train(as.factor(edible) ~ .,data = df,method = &quot;rf&quot;,trControl = fit_control)<br>rf_fit<br>saveRDS(rf_fit, file.path(path, &quot;fungiEdibility_RF_model.rds&quot;))<br>rf_fit &lt;- readRDS(file.path(path, &quot;fungiEdibility_RF_model.rds&quot;))<br>varImp(rf_fit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*jpIqdEBL7LomNyZ6bRybyQ.png" /></figure><p>Nice! Random Forest also selects odor as the most important feature to discriminate between edible and poisonous mushrooms. But this was not the goal of our analysis. We are still looking for the 23 different species or any interseting patterns within the dataset.</p><p>Therefore, I run the algorithm again, now looking not for rules but for frequent feature combinations. I set the minimal length of the feature set to 15.</p><pre>#run apriori<br>itemset &lt;- apriori(fungi,parameter = list(supp = 0.1, conf = 0.98,target = &quot;frequent&quot;, minlen=15,maxlen=22))<br>#get top items<br>top_items &lt;- data.frame(as(items(itemset), &quot;list&quot;))<br>top_items &lt;- cbind(as.data.frame(t(apply(top_items,2,function(x) sub(&quot;[[:alpha:]]+_?[[:alpha:]]+=&quot;, &quot;&quot;, x)))),itemset@quality)<br>#spread top items into a tidy dataframe<br>df2 &lt;- df[0,]<br>colnames(df2)<br>for (rownr in 1:nrow(top_items)){<br>  for (cols in 1:(ncol(top_items)-3)){<br>        feature &lt;- substring(top_items[rownr,cols], 1, unlist(gregexpr(&quot;\\.&quot;, top_items[rownr,cols]))-1)<br>        type &lt;- substring(top_items[rownr,cols], unlist(gregexpr(&quot;\\.&quot;, top_items[rownr,cols]))+1)<br>      for (i in 1:ncol(df2)){<br>        if(feature==colnames(df2)[i]){<br>          df2[rownr,i] &lt;- type<br>        } <br>    }<br>  }<br>}<br>#exclude columns which have never been selected by apriori <br>non_na_cols &lt;- c()<br>for (k in 1:ncol(df2)){<br>  if(sum(is.na(df2[,k]))!=nrow(df2)){<br>    non_na_cols &lt;- c(non_na_cols,colnames(df2)[k])<br>  }<br>}<br>df2[,non_na_cols]</pre><p>Here I again flip the table, so that you can read it better. I have also added the translation for the selected levels of the different features that were identified by the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*GJpnVj3ap90owWA3Qhatxw.png" /></figure><p>Interestingly, the algorithm identified patterns for edible mushrooms only, presumably because there is higher variability among the poisonous Agarici, rather tham among the edible ones. We also see, that there is a sub-feature set common to all feature sets (edible&amp;woods&amp;bruises&amp;no odor&amp;free gills&amp;close gill spacing&amp;broad gills&amp;tapering stalk&amp;bulbous root&amp;smooth stalk surface&amp;white veil&amp;one pendant ring). This representative feature set really strongly reminds me of the button mushroom. Let’s check how far we get with this description in nailing down the species. <br>The <a href="https://www.mushroomexpert.com/major_groups.html">webpage</a> offers a key to different mushroom species. Starting from the very first page, we go through the description. As we have not read anything about our mushroom growing on other mushromms (but rather solitary in woods), question 1 leads to question 2, which we answer positively (our mushroom has gills). We follow the key further: 3) not as above → 4) gills not running down the stem (our gills were free) → Gilled Mushrooms. So far, so good. The link takes us to the next <a href="https://www.mushroomexpert.com/agaricales.html">page</a>. Following the key we get: 1) with veil and not fishy → 2) spores not pink → 3) gills not yellow and not running down the stem → 4) spore print not orange → 6) spore print dark (brown, black). We have this feature in two feature sets only, but I assume if the digression to pale-spored mushrooms was of importance, it would have been picked up by the algorithm. Following the key <a href="https://www.mushroomexpert.com/gilled_dark.html">on </a>we get to (I omit here the reading of the keys, you can walk through if you wish): 1 → 3 → 12 → 21 → 26 → Agaricus. Great, the algorithm has picked up some Agaricus-common features. We read a not too optimistic statement on the webpage that “you should not expect to be able to identify every Agaricus collection you make”. And indeed, already the first two questions leave us without an answer, as the feature on flesh coloring upon slicing or Monterey cypress association was not adressed in the dataset. I guess the original key of the Audubon Society Field Guide might shed some light on this question, yet unfortunately I don’t have access to this resource. The only comfort is that the button mushroom Agaricus bisporus appears if answering “yes” to white cap color.</p><p>So, what is my <strong>takeaway </strong>from this toy analysis? The algorithm definitely picked up a feature set common to all mushrooms of the Agaricus genus. However, I would have guessed that starting with 8124 samples / 23 species = 353 samples per species, the algorithm would have picked up the feature sets common to other species. And indeed, running a quick principal component analysis on the dataset clearly shows that there are distinct clusters within the edible (green) and poisonous (red) samples, most likely corresponding to the different species.</p><pre>theme_set(theme_classic())<br>#encode factors to hot-one, as PCA works on numeric features only<br>dummy &lt;- dummyVars(&quot; ~ .&quot;, data=df, fullRank=T)<br>df_hotone &lt;- data.frame(predict(dummy, newdata = df))<br>mypca &lt;- prcomp(df_hotone) ;  myscores &lt;- mypca$x[,1:3] #scores<br>#add PCA results to table <br>df_hotone_PCA &lt;- cbind(df_hotone,myscores)<br>ggplot(df_hotone_PCA, aes(PC1,PC2))+<br>  geom_point(aes(color=factor(edibleedible.p, levels=c(&quot;1&quot;,&quot;0&quot;))))+<br>  theme(legend.position = &quot;none&quot;)+<br>  labs(title=&quot;Principal component analysis on mushroom dataset&quot;,subtitle = &quot;colored by edibility&quot;, caption = &quot;red = poisonous; green = edible&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6KlWGdM9KLoJBiJagtSJIw.png" /><figcaption>Image by author</figcaption></figure><p>This concludes this rather disappointing analysis. I guess in order to decipher the feature sets corresponding to the different species of the dataset, one needs to tune the apriori algorithm further or turn to another method. There is definitely room for improvement, so let’s pull up one’s sleeves and continue analyzing…in another story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffdf56c1d95c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/apriori-analysis-in-r-beyond-sells-ffdf56c1d95c">Apriori Analysis in R beyond sells</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>