text
stringlengths
81
47k
source
stringlengths
59
147
Question: <p>I've noticed that UMAP is often used in combination with other clustering algorithms, such as K-means, DBSCAN, HDBSCAN. However, from what I've understood, UMAP can be used for clustering tasks. So why I've noticed people using it primarily as a dimensionality reduction technique?</p> <p>Here an example of what I'm talking about: [https://medium.com/grabngoinfo/topic-modeling-with-deep-learning-using-python-bertopic-cf91f5676504][1]</p> <p>Am I getting something wrong? Can UMAP be used for clustering tasks alone? What are the benefits of using it in combination with other clustering algorithms?</p> Answer: <p>As mentioned Noe, UMAP is 100% for dimensional reduction, ONLY to group similar data and separate different ones, THEN we apply a clustering algorithm such as DBSCAN to identify those groups in the projected space.</p> <p>Multi-dimensional reduction is the most difficult part because you need to detect similarities and differences among plenty of variables and then project them in a lower dimensional space, generally in 2D.</p> <p>PCA was initially one of the first dimensional reduction algorithm (even if it is not exactly a dimensional reduction one) but it has a problem: it is linear.</p> <p>UMAP is a non-linear reduction algorithm, meaning it can detect complex correlations between features. Therefore, it uses <a href="https://en.wikipedia.org/wiki/Riemannian_manifold" rel="nofollow noreferrer">Riemannian manifolds</a> that are useful for representing complex, non-linear geometries that are difficult to capture with simple Euclidean distance measures.</p> <p>UMAP constructs a weighted graph representation of the data, where the weights between each pair of data points are determined by a distance measure that considers the geometry of the Riemannian manifold. This graph is then optimized using a gradient-based algorithm to produce a low-dimensional embedding that preserves the high-dimensional geometric structure of the data.</p> <p>More info: <a href="https://pair-code.github.io/understanding-umap/" rel="nofollow noreferrer">https://pair-code.github.io/understanding-umap/</a></p>
https://datascience.stackexchange.com/questions/120574/why-is-umap-used-in-combination-with-other-clustering-algorithm
Question: <p>I have a dataset with vectors in 2-dimensional space that form separate sequences (paths). Full data is presented below: <a href="https://i.sstatic.net/NRYF5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NRYF5.png" alt="enter image description here"></a>, while a random sample of 5 paths looks like below (please note that incontinuity in paths are natural for the data and doesn't mean missing values): <a href="https://i.sstatic.net/nZiFT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nZiFT.png" alt="enter image description here"></a> </p> <p>I would like to find similar paths, where similar would mean (in order from the most to the less prominent):</p> <ol> <li>they end up in a similar region</li> <li>they are similar in direct length (i.e. length from start to end on x axis)</li> <li>they are similar in complexity (i.e. number of vectors)</li> <li>they starts in a similar region</li> </ol> <p>What clustering algorithms are natural choice for such a setup? What are things worth to be aware while clustering paths? How can I deal with the fact, that different paths has different number of vectors? How can I represent a data to take that into account?</p> Answer: <p>Like Ricardo mentioned in his comment on your question, the main step here is finding a distance metric between paths. Then you can experiment with different clustering algorithms and see what works. </p> <p>What comes to mind is <a href="https://en.wikipedia.org/wiki/Dynamic_time_warping?oldformat=true" rel="nofollow noreferrer">dynamic time warping</a> (DTW). DTW gives you a way to find a measure of "distance" (it is actually not strictly a distance metric, but it is close) between two time series. One very useful thing is that it can be used to compare two time series that are of different lengths. </p> <p>There are many good <a href="https://jeremykun.com/2012/07/25/dynamic-time-warping/" rel="nofollow noreferrer">blog posts</a> on DTW, so I won't try to give yet another explanation of it. There are also many <a href="https://github.com/wannesm/dtaidistance" rel="nofollow noreferrer">python implementations</a> of it. And a lot of work has gone into making the algorithm very fast. DTW is a strange algorithm--in some ways very simplistic, but typically works well. Once you modify the algorithm to deal with paths, you can construct the distance matrix and use that for clustering. One common clustering algorithm that is used in conjunction with DTW is <a href="https://www.wikiwand.com/en/Spectral_clustering" rel="nofollow noreferrer">spectral clustering</a>, since the distance matrix can be used directly (instead of the matrix of data points, which we don't have here).</p>
https://datascience.stackexchange.com/questions/42166/what-clustering-algorithm-is-appropriate-for-clustering-paths
Question: <p>Is the following statement true? <a href="https://stats.stackexchange.com/q/256778">https://stats.stackexchange.com/q/256778</a></p> <blockquote> <p>The value of cosine similarity between two terms itself is not indicator whether they are similar or not.</p> </blockquote> <p>If yes then how is use of clustering algorithms like DBSCAN for word embeddings justified? From what I know DBSCAN algorithm only looks to its immediate neighbour to be included in cluster, but it seems the wrong way since maybe we need to check every word with every other word and take top ranked words.</p> Answer:
https://datascience.stackexchange.com/questions/107252/conceptual-question-about-cosine-similarity-and-clustering-algorithms-for-word-e
Question: <p>I would like to understand, how a clustering algorithm can be used (if possible) to identify naturally occurring groups within a data set, prior to building predictive models/model, and to hence improve accuracy of models/model</p> Answer: <p>In clustering the outcome variable or the response is unknown, this is why it's called clustering. Irrespective, of the fact the data being labeled or unlabelled, clustering can be applied as a data preprocessing algorithm. Essentially, you must proceed by employing the initial data preprocessing tasks (like missing value treatment, collinearity, skewness etc). Once, the data is "statistically clean", then you can apply any clustering technique. However, remember clustering requires data to be "grouped" such that data points within a group are related to each other and unrelated to other data points belonging to another group. This can be achieved only if you have a "statistically clean" data. The next important point to consider is, "how to determine the possible number of clusters". Because any clustering algorithm will divide the data points into groups oblivious of the fact whether the groups exist or not. Therefore, you will have to prove mathematically/statistically the occurrence of groups in the dataset. In literature, there exist several methods like the "Principal Component Analysis (PCA)" or the "elbow method". Once, you have determined such groups, you can then label the groups and perform predictive analytics.</p>
https://datascience.stackexchange.com/questions/28639/clustering-algorithm-prior-to-model-building
Question: <p>I currently do have a dataset of datasets and do want to cluster the data in each dataset. Therefore I want to use a clustering algorithm ...</p> <p>As such the data in each dataset is a bit special and for example it looks like so:</p> <pre><code>Datapoints Attribute1 Attribute2 Attribute3 DataPoint1 A A B DataPoint2 A C B DataPoint3 A D B DataPoint4 C A B DataPoint5 C A E ... </code></pre> <p>One can say that DataPoint1 differs in comparison to DataPoint2 by &quot;1&quot; as one of its attributes (the second one) is different. But since there is no &quot;order&quot;, DataPoint1 and DataPoint3 also differ by just &quot;1&quot; and not by a greater value - although &quot;D&quot; is later in the alphabet then &quot;C&quot;. (So these &quot;Attribute&quot;-variables are enumeration variables, not some kind of continuous variable ...)</p> <p>I'm now searching for a clustering algorithm that takes these datapoints as input and output each datapoint with the number of clusters.</p> <p>Thereby the algorithm should have the following properties:</p> <ol> <li>I do not need to tell the algorithm how much clusters are present. Thus I'm rather searching for X-Means than for K-Means.</li> <li>Since it can be that all datapoints do belong to the same cluster, the algorithm should not make the hypotisis that there are at least 2 clusters present in the dataset.</li> <li>The datasets can be big. So the algorithm should be reasonable fast.</li> <li>Also, it can be that sometimes an attribute / multiple attributes for a particular DataPoint is / are unknown. So the algorithm should take this into account as well.</li> </ol> <p>I know, I could do something like this:</p> <ol> <li>Implement an algorithm that counts the number of different attributes between two datapoints (or the number of same attributes). In case of an unknown attribute, ignore this attribute. I could then call this algorithm for each pair of datapoints in order to create a distance matrix (or a similarity matrix in case I do count the number of same attributes).</li> <li>I can then use a clustering algorithm like x-medoids clustering or similar on the distance matrix.</li> </ol> <p>But I'm wondering whether this can be improved (e.g. some kind of other algorithm to calculate the distance between two datapoints in order to better take into account when a particular attribute is unknown for a particular datapoint).</p> <p>Also, I'm wondering whether there are any clustering algorithms explicitly designed for this kind of situation (multiple enumeration variables, unknwon attributes, ...; see above).</p> Answer:
https://datascience.stackexchange.com/questions/131729/clustering-algorithms-for-datasets-with-enumerable-but-sometimes-unknown-feature
Question: <p>I have few clustering algorithms tuned having 5 cluster. I want 6th cluster if new data does not belong initial 5 cluster fall in 6th cluster.</p> <p>6th cluster [ say other category] consist of all data point which does not belong to 5 cluster.</p> <p>P.S.:- initial whatever data is give is belong those 5 cluster. so say, kmean algorithms with number cluster as 5. during inference I wanted add 6th cluster so any which does belong given cluster can put this category depending on threshold distance. I have textual data. do let me which clustering algorithms i should go with dbscan, som etc..</p> Answer: <p>Clustering doesn't work like this: for example k-means assigns an instance to the closest centroid, and since there is always a closest centroid there is a always a cluster that an instance &quot;belongs to&quot;.</p> <p>So you need a different approach if you plan to have the possibility of in instance &quot;not in any group&quot;:</p> <ul> <li>redo the clustering on the full set of instances</li> <li>apply a first step which detects outliers</li> <li>train a one-class classification model for every cluster</li> </ul>
https://datascience.stackexchange.com/questions/93264/how-to-add-other-as-one-group-to-clustering-algorithm-inference-pipeline
Question: <p>I am learning machine learning from scikit-learn and reading its docs.</p> <p>Clustering clusters groups based on the Euclidean distance and filters them by different ways ex: Gaussian distribution, or mean-shift...etc.</p> <p>But none of the clustering algorithms cluster samples based on the variation ratio.</p> <pre><code>EX: below every items has there sold numbers of everyday. Item,D1,D2 A,1,5 B,10,50 C,4,70 The variation ratio below: A:500% B:500% C:1750% </code></pre> <p>So A and B are the same group, C isn't.</p> <p>Are there any clustering algorithms that can cluster time series dataset based on variation ratio (or quantity)?</p> Answer: <ol> <li>Extract features such as variation ratio</li> <li>Cluster the extracted features instead of the raw data</li> </ol>
https://datascience.stackexchange.com/questions/44359/is-there-a-clustering-algorithm-that-can-cluster-time-series-dataset-based-on-va
Question: <p>Some methods related to manifold-learning are commonly stated as <strong>good-for-visualization</strong>, such as T-SNE and self-organizing-maps (SOM).</p> <p>I understand that when referring specifically to "visualization" means that the non-linear dimensionality reduction can provide good insights of data in its low-dimensional projection, but that most commonly this low-dimensional projection cannot be used in machine learning algorithms, since some of information of the high-dimensional structure is lost (roughly).</p> <p>However, and here the question, If "clusters" are being observed in the visualization is it acceptable to apply a clustering algorithm to the low-dimensional transformed data and analyze the clusters or groups separately?</p> <p>For example, I'm applying T-SNE to rather-high dimensional data (40 features) and obtaining this representation:</p> <p><a href="https://i.sstatic.net/X8IgS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/X8IgS.png" alt="enter image description here"></a></p> <p>Disregarding the colors you observe in the picture, I would like to apply a clustering algorithm and separate the data from the found clusters (let's say 6 or 7 clusters), and then analyze the characteristics of each cluster using the high-dimensional representation of each point.</p> <p>This is in synthesis: using the low dimensional to find clusters, and analyze (exploration) each cluster separately using the high dimensional representation. If I'm not able to do this, I don't see the actual point of visualizing in the low-dimensional space, in a practical sense.</p> <p>I understand T-SNE preserves well local structures and less accurately global structures, is this a drawback to do why I want? Is this low-dim clustering approach more suitable for other manifold learning methods?</p> <p><strong>EDIT</strong>: Probably a more direct way of asking this is: Can I use observed clusters in low dimensional representation to label or tag examples, and use these labels for discrimination using the original high dimensional representation?</p> Answer: <p>You can do anything you want in the low dimensional space, and can try to validate as well. By clustering the above, you are in effect assigning features/tags to your data points in higher dimensions. Remember, tSNE tries to preserve distances, so that points in high dimensions will remain close to each other in low dimensions. </p> <p>With that in mind, don't forget that no two instances of tSNE will be the same, which means that your clustering centers will be different each time you run tSNE.</p>
https://datascience.stackexchange.com/questions/10974/can-i-apply-clustering-algorithms-to-the-result-of-manifold-visualization-method
Question: <p>Heres the task: I have data I don't know much about. The final task is to build a classifier to classify the samples into a few categories. Some of the categories are pretty clear, we can easily use these as labels for a classifier. But I guess there are more useful categories possible, because right now <strong>most of my samples don't belong to any category</strong>. As I am no expert in the specific field, I would like to use some clustering algorithm to show possible label ideas. When using traditional clustering algorithms, they find all sorts of patterns in the data I am not interested in.</p> <p>So I am looking for a way to tell the algorithm: &quot;Hey, find some clusters in my data, but please take the existing clusters (or labeled data) into account.&quot; This should tell the clustering algorithm what I am interested in, and in what not.</p> <p><strong>Does something like this exists? Or any other idea how to solve the problem of finding additional labels?</strong></p> <p>BTW: in my case, I am doing NLP.</p> Answer: <p>You are describing <a href="https://en.wikipedia.org/wiki/Semi-supervised_learning" rel="nofollow noreferrer">semi-supervised learning</a> where the training dataset is only partially labeled.</p> <p>One common set of techniques to solve that problem is <a href="https://en.wikipedia.org/wiki/Active_learning_(machine_learning)" rel="nofollow noreferrer">active learning</a>. In active learning, there is a learning loop where the algorithm makes predictions and a human corrects those predictions.</p> <p>Pre-clustering is a specific active learning technique to address the problem you describe. The goal is to repetitively select the most representative training examples to add new labels and as well as avoiding repeatedly labeling samples in same cluster. &quot;<a href="https://icml.cc/Conferences/2004/proceedings/papers/94.pdf" rel="nofollow noreferrer">Active Learning Using Pre-clustering</a>&quot; by Nguyen and Smeulders goes into greater detail.</p>
https://datascience.stackexchange.com/questions/84711/is-there-a-clustering-algorithm-which-accepts-some-clusters-as-input-and-outputs
Question: <p>I have a problem of clustering huge amount of sentences into groups by their meanings. This is similar to a problem when you have lots of sentences and want to group them by their meanings.</p> <p>What algorithms are suggested to do this? I don't know number of clusters in advance (and as more data is coming clusters can change as well), what features are normally used to represent each sentence?</p> <p>I'm trying now the simplest features with just list of words and distance between sentences defined as:</p> <p><span class="math-container">$|A \cup B$</span> \ <span class="math-container">$A \cap B|$</span>/<span class="math-container">$|A \cup B|$</span></p> <p>(A and B are corresponding sets of words in sentence A and B)</p> <p>Does it make sense at all?</p> <p>I'm trying to apply <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_mean_shift.html#example-cluster-plot-mean-shift-py" rel="nofollow noreferrer">Mean-Shift</a> algorithm from scikit library to this distance, as it does not require number of clusters in advance.</p> <p>If anyone will advise better methods/approaches for the problem - it will be very much appreciated as I'm still new to the topic.</p> Answer: <p>Check the <strong><a href="http://www-nlp.stanford.edu/software" rel="nofollow noreferrer">Stanford NLP Group</a></strong>'s open source software, in particular, <strong><a href="http://www-nlp.stanford.edu/software/classifier.shtml" rel="nofollow noreferrer">Stanford Classifier</a></strong>. The software is written in <code>Java</code>, which will likely delight you, but also has bindings for some other languages. Note, the <em>licensing</em> - if you plan to use their code in commercial products, you have to acquire commercial license.</p> <p>Another interesting set of open source libraries, IMHO suitable for this task and much more, is <strong><a href="http://select.cs.cmu.edu/code/graphlab" rel="nofollow noreferrer">parallel framework for machine learning GraphLab</a></strong>, which includes <strong><a href="http://select.cs.cmu.edu/code/graphlab/clustering.html" rel="nofollow noreferrer">clustering library</a></strong>, implementing various clustering algorithms. It is especially suitable for <strong>very large volume of data</strong> (like you have), as it implements <code>MapReduce</code> model and, thus, supports <em>multicore</em> and <em>multiprocessor</em> <strong>parallel processing</strong>.</p> <p>You most likely are aware of the following, but I will mention it just in case. <strong><a href="http://www.nltk.org" rel="nofollow noreferrer">Natural Language Toolkit (NLTK)</a></strong> for <code>Python</code> contains modules for clustering/classifying/categorizing text. Check the relevant chapter in the <a href="http://www.nltk.org/book/ch06.html" rel="nofollow noreferrer">NLTK Book</a>.</p> <p><strong>UPDATE:</strong></p> <p>Speaking of <strong>algorithms</strong>, it seems that you've tried most of the ones from <code>scikit-learn</code>, such as illustrated in <a href="http://scikit-learn.org/stable/auto_examples/applications/topics_extraction_with_nmf.html" rel="nofollow noreferrer">this</a> topic extraction example. However, you may find useful other libraries, which implement a wide variety of <em>clustering algorithms</em>, including <em>Non-Negative Matrix Factorization (NMF)</em>. One of such libraries is <strong><a href="https://code.google.com/p/pymf" rel="nofollow noreferrer">Python Matrix Factorization (PyMF)</a></strong> (<a href="https://github.com/nils-werner/pymf" rel="nofollow noreferrer">source code</a>). Another, even more interesting, library, also Python-based, is <strong><a href="http://nimfa.biolab.si" rel="nofollow noreferrer">NIMFA</a></strong>, which implements various <em>NMF algorithms</em>. Here's a <a href="http://jmlr.org/papers/volume13/zitnik12a/zitnik12a.pdf" rel="nofollow noreferrer">research paper</a>, describing <code>NIMFA</code>. <a href="http://nimfa.biolab.si/nimfa.examples.documents.html" rel="nofollow noreferrer">Here's</a> an example from its documentation, which presents the solution for very similar text processing problem of <em>topic clustering</em>.</p>
https://datascience.stackexchange.com/questions/979/algorithms-for-text-clustering
Question: <p>A client would like to sort out his filesystem (~ 1,000,000,000 files), which has been fed by numerous workers over the years, each with their own unknown naming convention, e.g.:</p> <ul> <li>[DATE]-[CLIENT]-[FILENAME]</li> <li>[TYPE]-[CLIENT].[DATE][FILENAME]</li> <li>...</li> </ul> <p>Here are four examples (out of ~1,000,000,000 files) to make things clearer:</p> <p>JPM_TPD0001662_2009124012302000451.pdf</p> <p>JPMF_STA_1712010832_18001_LUX_approval.pdf</p> <p>CHACN05CTRP_00111.001.pdf</p> <p>CHACN63CJO1_00018.001.pdf</p> <p>The purpose is to find out patterns in the naming conventions, but I can't use regular expressions, since the conventions are unknown a priori.</p> <p>I was wondering whether there was a kind of clustering algorithm to be able to group files according to their naming conventions.</p> <p>Any K-Mean philosophy applied to strings?</p> Answer: <p>For those interested in a solution for similar problems, I found a solution with these steps:</p> <ol> <li><p>Splitting the filenames on "_", generating n strings</p></li> <li><p>Taking the length of each string</p></li> <li><p>Running KMeans (optimal K using Gap Statistics)</p></li> <li><p>Taking one sample per cluster and reverse-engineering it to a generic regex, via a customized function</p></li> </ol> <p>In practice, here is an example of 10 files:</p> <p><a href="https://i.sstatic.net/naUfc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/naUfc.png" alt="enter image description here"></a></p> <p><a href="https://i.sstatic.net/DIuvH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DIuvH.png" alt="enter image description here"></a></p> <p>File 0 splits on "<em>" into groups of lengths 3, 10 and 23 respectively. File 3 splits on "</em>" into groups of lengths 11 and 13 respectively. File 5 splits on "_" into groups of lengths 4, 3, 10, 5, 3 and 12 respectively.</p> <p>Files 0, 1 and 2 belong to the same cluster and have identical naming convention. Files 3, 4, 6, 7, 8 and 9 belong to the same cluster and have identical naming convention. File 5 belongs to another cluster and has yet another naming convention.</p>
https://datascience.stackexchange.com/questions/28022/clustering-algorithm-to-sort-filenames
Question: <p>I'm currently trying to use cluster analysis as a tool for time-series aggregation for a project of mine. The dataset is high-dimensional (386-d), so no chance in assessing the cluster validity visually.</p> <p>I'm using three different clustering algorithms (k-means++, k-medoids PAM, fuzzy c-means) to find representative periods. As I do not know how many periods (thus, how many centers/medoids k) are present in the dataset, I want to use an internal cluster validity index (cvi) for it. (Basic procedure: run the clustering with multiple k's and plot the cvi against the k; choose highest/lowest k dependent on cvi optimum). </p> <p>Let's stick with k-means as an example. It is non-deterministic, thus I initiate it multiple times with varying starting points. It then tries to reduce the intra cluster variance. The result with the lowest intra cluster variance of the various initiations with the same k is then kept.</p> <p>My question is: should the cluster validity index that I use consider the intra cluster variance as a cohesion measure? So to speak: should the cvi use the objective function of the clustering algorithm as a measure to assess "goodness" of clustering?</p> <p>On the one hand I think, that this would be a good idea, as it can assess, where the clustering algorithm was "most successfull" in its objective function. On the other hand I think, that for a good clustering it shouldn't depend on the same (cohesion) measure. Thus, using the same measure would increase the likelihood of identifying a "bad" clustering, that might represent an unnatural cluster, drawn from random points.</p> <p>What's "the truth" here?</p> Answer: <p>It's standard to use, e.g., Silhouette to assess the quality of clusterings, that were obtained with other methods.</p> <p>I'm not a big fan of this (people always think they would get the "optimal" result this way, but they don't), but it's all over literature. Logically, you are trying to maximizing Silhouette and use the other algorithms as sampling procedure for possible results.</p>
https://datascience.stackexchange.com/questions/52766/should-a-cluster-validity-index-contain-the-same-measures-as-the-clustering-al
Question: <p>I am trying to find clusters in some data with high noise (see plot below, data <a href="https://pastebin.com/asADpJ0Y" rel="nofollow noreferrer">here</a>).</p> <p><a href="https://i.sstatic.net/GMnpj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GMnpj.png" alt="enter image description here" /></a></p> <p>I tried using DBSCAN which sort of worked, but it required quite a bit of manually tuning the input parameters to find the clusters properly. Are there any other good clustering algorithms for dealing with this kind of data?</p> <p>Some considerations:</p> <ul> <li><p>I am using Julia to do my data processing.</p> </li> <li><p>The data has periodic boundary conditions in both directions.</p> </li> <li><p>The number of clusters is known a priori.</p> </li> <li><p>I am planning to process many datasets in this way, so it should run relatively fast and not require <em>too</em> much manual fiddling.</p> </li> </ul> <p>Thanks!</p> Answer: <p>It could be interesting to reduce noise (=smoothing) as much as possible before applying a clustering algorithm.</p> <p>Furthermore, periodic boundaries that have too many values may alter results, and that's why it could be a good option to simplify values when it is possible.</p> <p>If non of the previous options are possible, you could apply point density measures to just keep the zones with high density.</p> <p>Therefore, you can apply a grid of hexagons to just take hexagons with a high density of points, or kernel density estimation.</p> <p>See also:</p> <p><a href="https://juliapackages.com/p/hexagons" rel="nofollow noreferrer">https://juliapackages.com/p/hexagons</a></p> <p><a href="https://github.com/JuliaStats/KernelDensity.jl" rel="nofollow noreferrer">https://github.com/JuliaStats/KernelDensity.jl</a></p>
https://datascience.stackexchange.com/questions/113940/looking-for-a-clustering-algorithm-for-highly-noisy-data
Question: <p>I am trying to implement k-means clustering algorithm, but I am confused about calculating the distance and update(move) cluster centroids. For example, let's say that I have 2 features. One of them is <code>weight={2,4,6,8,11,14,21}</code> and the other one is <code>height={4,6,7,8,9,12,14}</code>. So, in the coordinate system my points are <code>x1={2,4},x2={4,6},x3={6,7}</code> and so on. Then, I initialize the cluster centroids randomly, doesn't matter how many there are for now, but they have coordinates too. Let's say <code>μ1={4,2}</code>. At this point, I understand how do I calculate distance with Euclidean distance.</p> <p><a href="https://i.sstatic.net/73EAw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/73EAw.png" alt="enter image description here"></a></p> <p>My code for calculating distance:</p> <pre><code>def get_distance(x1,x2,s1,s2): return np.sqrt(np.power(s1-x1,2)+np.power(s2-x2,2)) </code></pre> <p>Now I get a distance.</p> <p>My first question is how cluster assignment step(first step in loop) will know which centroid assign to c(i).I mean,am I supposed to look at each centroid for understand which sample(x(i)) is close to it and then I should assign centroid to c(i), right?</p> <p>My second question, let's say I got distances and I have c(1,2..,n) array now. Second step in algorithm which is called move(update) centroid step, we are calculate μ. According to formula, this μ is the average of points assigned to clusters so for example μ1=[x(3) + x(4) + x(6)] / 3. However, here our μ was a point in coordinate system, right? I mean, μ1 was {4,2}. How can this be possible? It's a point not a variable. It has coordinates. Well, if it will become a variable let's say μ1=5, how can I subtract ||x(i)-μ|| then? x is a coordinate.</p> <p>My last question is very simple. For this example, I have two features weight and height. What is the maximum number of features that we can use in k-mean? Is it possible to use k-mean algorithms for many many features? For instance, my first feature is height and the second is weight and the third is width fourth and so on.</p> <p>I hope, I explained my problem clearly. If not, sorry for the bad English. I think these three questions are independent questions, so you can answer one of them.</p> <p>Thanks.</p> Answer: <p>Wikipedia says: "Assign each observation to the cluster whose mean yields the least within-cluster sum of squares (WCSS)"</p> <p>I think in your case, this is translatable to: $c_i$ is assigned to the closest centroid by euclidean distance.</p> <p>For your second question, the centroid should $\mu$ should have the same number of dimensions as each training point $x_i$. They are both points in the co-ordinate system.</p> <p>You can use a high number of features with K-means, for example, text analytics might reduce a corpora of news articles to 10,000+ dimensions. Depending on the package you use these might be represented as a sparse matrix.</p>
https://datascience.stackexchange.com/questions/13200/k-means-clustering-algorithm-problems
Question: <p>I have a database that has information such as Latitude, longitude, plus other information such as sightseeing locations, restaurants and shopping centers, if it's rural or suburb,... It also has grids and centroids for each grid on the map. I need to cluster the area based on similarities, so when someone is driving, they can visit the locations. I have also added information such as zip code and name of the city and county. What clustering algorithm or models is suggested, so that apart from similarities, it can keep closeness of grids into consideration? Thanks in advance</p> Answer: <p>It seems to me there won't be 1 exact best fit algorithm for your case, at least how you framed your question currently. You could load your data into a software kit specifically meant for analysing graph data like Neo4j or Gephi keeping the lat., lon., grid and centroid info and then evaluate how the data clusters when applying different clustering / layouting algorithms (e.g. Force Atlas 2) for each of your different criterias individually to get a better feel for the goal you have and how your features each contribute to that goal.</p> <p>A good starting point for clustering is generally to try k-Means as a first approach.</p> <p>If you really need to apply a multi-criteria clustering algorithm, <a href="https://www.researchgate.net/publication/24056238_Direct_multicriteria_clustering_algorithms/citations" rel="nofollow noreferrer">this paper</a> could serve as a good read.</p>
https://datascience.stackexchange.com/questions/114367/best-clustering-algorithm-or-model-for-clustering-areas-on-map
Question: <p>I have a dataframe with 2 columns of numerical values. I want to apply a clustering algorithm to put all the entries into the same group, which have a relatively small distance to the other entries. But which clustering algorithm can I use, although I do not know how many groups will be formed? It would be ideal if there is a parameter to determine the maximum distance allowed. And if there isn't such an algorithm, maybe it would be really helpful to come up with some intuitions, how such an algorithm can be implemented by myself. Thanks a lot!! :)</p> <p>The data could look like this:</p> <pre><code>a,b 20,30 19,31 10,10 9,8 12,11 31,11 32,11 </code></pre> Answer: <p>I'd suggest looking at <a href="https://en.wikipedia.org/wiki/Hierarchical_clustering" rel="nofollow noreferrer">hierarchical clustering</a>:</p> <ul> <li>It's simple so you could implement and tune your own version</li> <li>It lets you decide at which level you want to stop grouping elements together, so you could have a maximum distance.</li> </ul> <p>Be careful however that this approach can sometimes lead to unexpected/non-intuitive clusters.</p>
https://datascience.stackexchange.com/questions/66140/clustering-algorithm-which-does-not-require-to-tell-the-number-of-clusters
Question: <p>I need to find a good clustering for this data using sci-kit. </p> <p><a href="https://i.sstatic.net/AZnRG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AZnRG.png" alt="enter image description here"></a></p> <p>KNN is not appropriate as it creates blobs although these data are linearly separated. </p> <pre><code>import hypertools as hyp hyp.plot(tocluster,'o', n_clusters=10) </code></pre> <p><a href="https://i.sstatic.net/K0Lkt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/K0Lkt.png" alt="enter image description here"></a></p> Answer: <p>I'd rather not rely on clustering (clearly, DBSCAN would be the first method to try).</p> <p>Instead, I'd look for a <em>projection</em> that removes the correlation (x - y maybe?), then define a grid to separate the data.</p>
https://datascience.stackexchange.com/questions/19443/appropriate-clustering-algorithm
Question: <p>I'm looking for a clustering algorithm that will make cluster depending on a orientation. The DBSCAN algorithm cluster points based on a constant radius :</p> <p><a href="https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/DBSCAN-Illustration.svg/800px-DBSCAN-Illustration.svg.png" rel="nofollow noreferrer">https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/DBSCAN-Illustration.svg/800px-DBSCAN-Illustration.svg.png</a></p> <p>Is there a implementation of DBSCAN that is based on &quot;ellipse instead of circle&quot; ?</p> <h1>EDIT: MY SOLUTION</h1> <p>Ok so my solution was to work on my data set. I had a set of 2D points and I wanted to favor the definition of clusters depending of a given orientation.</p> <p>My solution was to center my set of point on the origin of the coordinate system, rotate them by the orientation you want and apply this vector field on the set of point : X(x, y) = (x-x*a, y) , where a is the factor that determine if the orientation should matter a lot or not (a ∈ [0, 1]) .</p> <p>Then apply the DBSCAN of this modified dataset.</p> <p>I hope I was clear enough, don't hesitate to ask me if it's not the case.</p> Answer: <p>If I remember correctly, non-negative matrix factorization (NMF) can be used as a clustering approach that can recover clusters that are along vectors, for example. It may work for your dataset. It factors a data matrix <span class="math-container">$D \in \mathbb{R}^{m * n}$</span> into two matrices <span class="math-container">$W \in \mathbb{R}^{m*k}$</span> and <span class="math-container">$H \in \mathbb{R}^{k * n}$</span>. Effectively, <span class="math-container">$W$</span> contains the weights that are applied to each vector in <span class="math-container">$H$</span> to reconstruct the original data; one way of using this method is to interpret the <span class="math-container">$n$</span>-dimensional vectors in <span class="math-container">$H$</span> as clusters (these vectors would be the 'directions' that your data is along) and the <span class="math-container">$k$</span>-dimensional vectors in <span class="math-container">$W$</span> as the data-example-wise affinities for the different clusters. One method to cluster with this process is to simply place each of the <span class="math-container">$m$</span> data examples into the cluster with the index of the highest value in the <span class="math-container">$W$</span> vector. </p> <p>There are implementations in several standard libraries, including sklearn, so it should be relatively easy to try it out. Good luck, and welcome to the site!</p>
https://datascience.stackexchange.com/questions/41520/is-there-an-oriented-clustering-algorithm
Question: <p>I am performing extensive customer segmentation analysis and so far implemented Gaussian Mixture Models, K-Means, and Hierarchical Clustering. For the most part, the algorithms agree on the structure of the clusters and well as the number (7-8). I would like to know if there is a common method to either...</p> <ul> <li>compare similarity between clusters. Can you apply Adjusted Rand Index to two different clusterings of the same data (k-means clusters vs gmm)? I was under the impression ARI is used in instances where you know the <em>truth</em> of the data.</li> <li>Find the common clusters within the clusterings. If all of the algorithms say one cluster is defined by high spending, then is there a way to determine the best centroid(s) to use for a "Master" cluster? Is it common to cluster the cluster results?</li> </ul> Answer: <p>If you just want to see how similar the clustering is between 2 algorithms, using the sklearn.metrics.adjusted_rand_score() function is a good starting point. This will work for unsupervised learning, no need for a label.</p> <p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.adjusted_rand_score.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.metrics.adjusted_rand_score.html</a></p> <p>Or are you looking at choosing the best combined grouping overall? I think "clustering the cluster" results is not a common approach, however there are a few articles online on how this could be done. But I don't know of any packages that will do this for you. One idea is to create a new column for each algorithm with the grouping chosen and then do some comparisions or calculations on these columns to get a final composite clustering.</p>
https://datascience.stackexchange.com/questions/75923/what-methods-are-available-to-evaluate-similarity-between-different-clustering-a
Question: <p>I'm looking for a clustering algorithm that clusters objects, by using their pairwise distances, without needing to calculate all pairwise distances.</p> <p><strong>Normally pairwise clustering is done like this:</strong> (see <a href="https://datascience.stackexchange.com/questions/701/clustering-pair-wise-distance-dataset">here</a>)</p> <ol> <li>Compute full distance matrix between all pairwise combination of objects</li> <li>Assuming that the distances there are non-euclidean, one might use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html" rel="noreferrer">Spectral Clustering</a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AffinityPropagation.html" rel="noreferrer">Affinity propagation</a> on the distance matrix and retrieve the clustering results.</li> </ol> <p><strong>Here comes the however:</strong> </p> <p>Computing the full distance matrix for all pairwise combination of objects is computationally very expensive. So my though was, whether there are some clustering algorithms that only do lookups on a subset of the pairwise distances, so it is not necessary to compute the full matrix?</p> <p>I know Spectral Clustering works also on sparse matrices, but since it is theoretically possible to compute all pairwise distances, which ones should be left out?</p> <p>Exited to hear your ideas, thanks!</p> Answer: <p>Well, one may argue that DBSCAN is based on all pairwise distances, but it uses data indexing to avoid computing all of them using geometric bounds.</p> <p>And there are other examples if you browse through literature.</p> <p>For example, the classic CLARA method is an approximation to PAM that avoids computing all pairwise distances.</p> <p>And there are many more such techniques. </p>
https://datascience.stackexchange.com/questions/46950/are-there-algorithms-for-clustering-objects-with-pairwise-distances-without-com
Question: <p>I use the DCC algorithm to cluster some data. The whole algorithm is available here, but shortly it is:</p> <ol> <li>construct mkNN graph of the data points (the connected components of it are the clusters).</li> <li>pretrain an Autoencoder for data dimension-reduction.</li> <li>train the Autoencoder witn it's objective wih another objective of the clustering which tries to reduce the distance between the dimension-reducted data points.</li> <li>the final connected components of the becoming close points(if close enough (by a threshhold) they remain connected, if they moved far from each other - the edge is gone and some others appear and e.t.c) are the clusters.</li> </ol> <p><a href="https://github.com/shahsohil/DCC" rel="nofollow noreferrer">full algorithm with link to the article</a></p> <p><a href="https://i.sstatic.net/wngz3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wngz3.png" alt="objective" /></a></p> <p><a href="https://i.sstatic.net/dy872.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dy872.png" alt="algorithm" /></a></p> <p>Could you possibly guess why am I getting the most of the data in the first 0-index cluster (consistently, with tuning all of the hyperparameters) ? The data has good potential for a very good clustering as I can see from the tSNE visualization of the output. But the clustering isn't good. I thought maybe to enlarge the k parameter of the mKNN graph construction, but it didn't work for that, just reduces the whole amount of clusters, but the data samples continue to clash into one cluster.</p> <p>Any suggestion and theoretical discussion is welcomed.</p> Answer:
https://datascience.stackexchange.com/questions/82847/deep-continious-clustering-algorithm-just-one-output-cluster
Question: <p>I have done some research on clustering algorithms since for my goal is to cluster noisy data and identify outliers or small clusters as anomalies. I consider my data noisy because of my main feautures can have quite varying values. Therefore, my focus has been on density based algorithms with quite some success.</p> <p>However, I am unable to grasp the idea of cluster comparison in such algorithms since the notion of cluster centers cannot be properly defined.</p> <p>My dataset constists of network flows and I split the dataset in subsets based on an identifier. After applying clustering on each subset I want to be able to compare the clusters that are created on each subset so that I can compare the subsets themselves in some context.</p> <p>Would appreciate some help from data scientist gurus on how to approach the concept of cluster comparison or cluster center in such algorithms.</p> <p>Thanks all!</p> Answer: <p>You can either use the medoid, you can sometimes compute a centroid (and just ignore that it may be outside of the cluster), or you can do pairwise comparisons and take the average of that rather than comparing centers.</p>
https://datascience.stackexchange.com/questions/20471/notion-of-cluster-centers-and-cluster-comparison-in-density-based-algorithms
Question: <p>I have a survey where each question is related to a different 'shopper' type (there are 5 types so 5 questions). Each question is either binary (True/False) or scale based.</p> <p>IE:</p> <pre><code>1. Do you like to shop at our physical location store ? (True/False) 2. Do our discounts entice you to shop more? a. no b. maybe c. yes </code></pre> <p>For each response I convert the answer choice to a numerical value. So True becomes 1, answer choice 2C becomes 3 etc. </p> <p>At this point, I am clueless as too what clustering algorithm to use so I can create clusters for each of the 'shopper' types and measures each individual survey response submitted to determine a single cluster closet to the responses given and label the response as that cluster.</p> <p>IE. This individual that submitted the survey response is <code>'location conscience shopper type'</code></p> <p>Open to any new method of analysis not just clustering</p> Answer: <p>Since they are categorical variables, I would cluster them using the <strong>k-medoids clustering method</strong>. Before applying this method, one-hot encode all the predictors.</p> <p>See a tutorial here: <a href="https://towardsdatascience.com/k-medoids-clustering-on-iris-data-set-1931bf781e05" rel="nofollow noreferrer">https://towardsdatascience.com/k-medoids-clustering-on-iris-data-set-1931bf781e05</a></p> <p>Sklearn has an implementation: <a href="https://scikit-learn-extra.readthedocs.io/en/latest/generated/sklearn_extra.cluster.KMedoids.html" rel="nofollow noreferrer">https://scikit-learn-extra.readthedocs.io/en/latest/generated/sklearn_extra.cluster.KMedoids.html</a></p>
https://datascience.stackexchange.com/questions/65925/best-clustering-algorithm-to-identify-clusters-and-determine-the-closet-cluster
Question: <p>I'm having a hard time getting kmeans to cluster data effectively. It fails to segment data well even for a simple attribute with 5 categories. I'm aware of DBSCAN, Hierarchical Clustering and GMM. However, just wanted to know if there's any way (visual or otherwise) to narrow down the clustering algorithm which might work on the dataset in question, before I start to write the code for each of these algorithms.</p> <p>Thanks in advance.</p> Answer: <p>No.</p> <p>Clustering is an explorative technique, it is subjective what is good, and the best clusters are those that are "interpretable but unexpected", a property that you cannot quantity with statistics. So it is a trial-and-error <em>task</em>.</p> <p>Furthermore, <strong>data preparation is much more important than the choice of clustering algorithm</strong>. On badly prepared data, none will work.</p> <p>Last but not least, <strong>categoricial data is a huge problem</strong>. It lacks detail for most clustering approaches - treating this as binary variables is much too coarse and tends to produce bad solutions (such as tiny "clusters" and trivial splits on a single variable). This is likely a problem of the data, not the algorithm. Similar issues can be seen with integer attributes or any other attribute that has only very few discrete levels (including Likert-like-scale questionnaires). Methods such as k-modes exist for categoricial data, but often don't produce better results either...</p>
https://datascience.stackexchange.com/questions/56638/is-there-any-method-to-determine-which-clustering-algorithm-to-use-on-a-particul
Question: <p>I'm looking for something like K-Means for dividing solid polygons into regions. K-Means clusters discrete points. But I want to cluster (that is, partition) the points of solid polygons.<a href="https://i.sstatic.net/43RD0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/43RD0.png" alt="expected polygon clustering"></a></p> <p>I don't see any problems with implementing K-Means extension for this case but I want be sure before reinventing the wheel.</p> <p>So questions:</p> <ol> <li>Are there any algorithms for solid polygon clustering?</li> <li>Are there any implementations (preferably in javascript)?</li> </ol> <p>I looked at GIS clustering but everything I found is about polygon clustering for zooming. And a polygon is a convex hull of geo markers and deeply inside it is about clustering discrete points.</p> Answer: <p>Finally I just implemented solution as I planned and described it in <a href="https://medium.com/@trechkalov/reinventing-wheel-naive-way-to-wireless-sensor-network-coverage-optimization-de59868c787b" rel="nofollow noreferrer">Medium post</a>. This is &quot;K-Means for solid polygons&quot;. I made a playground on my <a href="https://ntsdk.github.io/sensorClustering/" rel="nofollow noreferrer">github.io</a>.</p> <p>A bit more details of solid clustering approach.</p> <p><a href="https://en.wikipedia.org/wiki/K-means_clustering" rel="nofollow noreferrer">K-Means complexity</a> is <em>O(nkdi)</em> or <em>O(nk)</em> per iteration without <em>d</em>,</p> <ul> <li><em>n</em> is the number of <em>d</em>-dimensional vectors (to be clustered)</li> <li><em>k</em> the number of clusters</li> <li><em>i</em> the number of iterations needed until convergence.</li> </ul> <p><strong>Complexity estimation of solid clustering</strong></p> <p>Suppose that clustered polygon has no self-intersections.</p> <ul> <li><em>k</em> - number of clusters</li> <li><em>m</em> - number of points in clustered polygon (to not mix with K-Means <em>n</em>).</li> </ul> <p>Step complexity estimations</p> <ol> <li><p>Building Voronoi diagram for <em>k</em> centers with <a href="https://en.wikipedia.org/wiki/Fortune%27s_algorithm" rel="nofollow noreferrer">Fortune's algorithm</a>: <em>O(k log(k))</em>. Expected that you have centers and cells as result.</p> </li> <li><p>Intersect each Voronoi cell with clustered polygon. I use algorithm from <a href="https://www.npmjs.com/package/polygon-clipping" rel="nofollow noreferrer">polygon-clipping</a> package.</p> </li> </ol> <p>From description:</p> <blockquote> <p>&quot;The Martinez-Rueda-Feito polygon clipping algorithm is used to compute the result in <em>O((n+k) log(n))</em> time, where n is the total number of edges in all polygons involved and k is the number of intersections between edges.&quot;</p> </blockquote> <p>Total number of edges for us is <em>m</em> and edges in Voronoi cell <em>Tmp</em>. In complex polygon case <em>m &gt;&gt; Tmp</em>. I don't know how to estimate number of intersections but I think with big <em>m</em> it can be ignored.</p> <p>So full estimation of this step <em>O(m log(m) k)</em>.</p> <ol start="3"> <li>Complexities of polygon area and center of weight are <em>O(m)</em>.</li> </ol> <p>What is the number of polygon points estimation?</p> <p>In worst case one Voronoi cell polygon has <em>(k-1)</em> edges. Clustered polygon has <em>m</em> edges. As I can imagine in the worst case intersection of the worst Voronoi cell and the worst polygon will produce <em>3n/2</em> edges polygon. As a result the upper boundary of this step is <em>O(nk)</em>.</p> <ol start="4"> <li>Centers of weight are new centers - move to step 1.</li> </ol> <p>Final complexity estimation is <em>O(k log(k) + m log(m) k + m k) =&gt; O(m log(m) k)</em> per iteration.</p> <p><strong>What does it mean?</strong></p> <p>If we want to solve the same problem of solid polygon clustering with K-Means then we need to discretize original polygon to K-Means points.</p> <ol> <li><p>K-Means result will be less accurate.</p> </li> <li><p>If <em>n &gt;&gt; m log(m)</em> then K-Means will be slower than solid clustering.</p> </li> </ol> <p><strong>Interesting points</strong></p> <ol> <li><p>K-Means includes density as part of clustering process. Some points may be heavier than other. Solid clustering ignores density so weights of all clustered points are equal.</p> </li> <li><p>We can see bottleneck effect in solid clustering. Clustering tries to spread cluster centers to have equal density. But cluster center can't jump out of its polygon so it slowly moves from dense area to spatial. In certain conditions we can see the same effect in K-Means.</p> </li> </ol> <p><a href="https://i.sstatic.net/T5LHC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/T5LHC.png" alt="enter image description here" /></a></p> <ol start="3"> <li>I think this bottleneck problem may be significantly reduced with center jumps - jump center of the smallest cluster to the biggest one.</li> </ol> <p><strong>UPD March 2022:</strong> <a href="https://github.com/sr-2020/maps-n-magic/tree/solid-clustering-demo2" rel="nofollow noreferrer">Sources</a> of the playground.</p>
https://datascience.stackexchange.com/questions/56565/are-there-any-algorithms-for-solid-polygon-clustering
Question: <p>Does anyone could explain in details how heap structure works in Cluster Algorithm?</p> <p>I am planning to code CURE in Matlab (Clustering using representatives) but, at first, the paper mentions that all points of datasets are considerered as clusters and heap helps to merge new clusters and I do not know how exactly this data structure works in this algo.</p> <p>Thanks for your support.</p> Answer: <p>A heap works in clustering the same way it works outside of clustering.</p> <p>It's purpose is to efficiently find the minimum or maximum of a set, remove it, then find the next.</p> <p>Efficient implementations of heaps in scripting languages may be impossible. For good performance, you usually need low-level memory access to avoid copying.</p>
https://datascience.stackexchange.com/questions/15116/built-a-heap-in-cluster-algorithm
Question: <p>I'm analyzing the GDELT dataset and I want to determine thematic clusters. Simplifying considerably, GDELT parses news articles and extracts events. As part of that, it recognizes, let's say, 250 "themes" and tags each "event" it records in a column a semi-colon separated list of all themes identified in the article.</p> <p>With that preamble, I've extracted, for 2016, a list of approximately 350,000 semi-colon separated theme lists, such as these two:</p> <ul> <li>TAX_FNCACT;TAX_FNCACT_QUEEN;CRISISLEX_T11_UPDATESSYMPATHY;CRISISLEX_CRISISLEXREC;MILITARY;TAX_MILITARY_TITLE;TAX_MILITARY_TITLE_SOLDIER;TAX_FNCACT_SOLDIER;USPEC_POLITICS_GENERAL1;WB_1458_HEALTH_PROMOTION_AND_DISEASE_PREVENTION;WB_1462_WATER_SANITATION_AND_HYGIENE;WB_635_PUBLIC_HEALTH;WB_621_HEALTH_NUTRITION_AND_POPULATION;MARITIME_INCIDENT;MARITIME;MANMADE_DISASTER_IMPLIED;</li> <li>CRISISLEX_CRISISLEXREC;EDUCATION;SOC_POINTSOFINTEREST;SOC_POINTSOFINTEREST_COLLEGE;TAX_FNCACT;TAX_FNCACT_MAN;TAX_ECON_PRICE;SOC_POINTSOFINTEREST_UNIVERSITY;TAX_FNCACT_JUDGES;TAX_FNCACT_CHILD;LEGISLATION;EPU_POLICY;EPU_POLICY_LAW;TAX_FNCACT_CHILDREN;WB_470_EDUCATION;</li> </ul> <p>As you can see, both of these lists both contain "TAX_FNACT" and "CRISISLEX_CRISISLEXREC". Thus, "TAX_FNACT;CRISISLEX_CRISISLEXREC" is a 2-item cluster. A better understanding of GDELT informs us that it isn't a particularly useful cluster, but it is one nevertheless.</p> <p>What I'd like to do, ideally, is compose a dictionary of lists. The key for the dictionary is the number of items in the cluster and value is a list of tuples of all theme clusters with that "key" number of elements paired with the number of times that cluster appeared. This ideal algorithm would run until it identified the largest cluster.</p> <p>Does an algorithm already exist that I can use for this purpose and if so, what is it named? If I had to guess, I would imagine we've created something to extract x-item clusters and then I would just loop from 2->? until I don't get any results.</p> Answer:
https://datascience.stackexchange.com/questions/17109/seeking-appropriate-clustering-algorithm
Question: <p>I've a list of 1,300 news events, represented by only three terms coming from running LDA topic model on thousands of tweets. Here's some of them as an example:</p> <pre><code>['manchester,bony,city', 'attack,claims,responsibility', 'police,officers,nypd', 'goal,arsenal,liverpool', 'test,pakistan,sunday', 'obama,ukraine,merkel', ...] </code></pre> <p>I need to group them in more general domains (Politics, Sport, Health, Economy, etc.).</p> <p>Which kind of clustering algorithms could I use (in Python)?</p> <p>Or maybe, can I use LDA topic model, even if I don't have documents but only three words?</p> Answer: <p>Some creative post-processing can be done. For instance applying <a href="https://en.wikipedia.org/wiki/Named-entity_recognition" rel="nofollow noreferrer">Named Entity Recognition</a> and simplify some parts (<strong>Manchester</strong> is a <strong>City</strong>). Using Knowledge Graph Analysis also gives some meta-info e.g. mapping your word to Wikipedia graph or using DBpedia may help you to recognize Named Entitiy categories (<strong><a href="http://dbpedia.org/page/Barack_Obama" rel="nofollow noreferrer">Obama</a></strong> and <strong><a href="http://dbpedia.org/page/Angela_Merkel" rel="nofollow noreferrer">Merkel</a></strong> are politicians and NER does not necessarily capture their profession).</p> <p>Note that the combination of named entity recognition and knowledge-base (Wikipedia, DBpedia, etc.) mapping is called <a href="https://en.wikipedia.org/wiki/Entity_linking" rel="nofollow noreferrer">Entity Linking</a>.</p> <p>Regardless of statistical learning for NLP techniques, all structures above are actually <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)" rel="nofollow noreferrer">graphs</a> so they can <a href="https://github.com/gsi-upm/sematch" rel="nofollow noreferrer">give you also the semantic similarity measure</a> based on which you can use other clustering algorithms like <a href="https://en.wikipedia.org/wiki/Spectral_clustering" rel="nofollow noreferrer">Spectral Clustering</a> and go to a semantically higher level of clustering.</p> <p>Hope it helps :)</p>
https://datascience.stackexchange.com/questions/28711/cluster-algorithm-to-group-events-in-more-general-domains
Question: <p>I'm relatively new to cluster analysis, and I'm exploring options for general-purpose, non-hierarchical, strict partitioning of data based on a pre-computed <span class="math-container">$N\times N$</span> pairwise similarity matrix. The matrix must be computable from an arbitrary user-specified (i.e., non-canned) similarity metric.</p> <p>Which established methods satisfy the above criteria?</p> <p>I've read up a bit on the clustering algorithms <a href="https://scikit-learn.org/stable/modules/clustering.html" rel="nofollow noreferrer">included in Scikit-learn</a>, but I've failed to spot any so far that exactly match my description, though I might be overlooking something.</p> Answer:
https://datascience.stackexchange.com/questions/112186/which-clustering-partitioning-algorithms-can-operate-on-arbitrary-pairwise-simil
Question: <p>There are many metrics to evaluate clustering algorithm like Calinski-Harabaz Index, Dunn index, Rand index, etc. Are there any advantage of using Dunn index over other metrics for evaluating clustering algorithm (K-means in particular)? If yes, what are the advantages and disadvantages?</p> Answer: <p>They will often give the same preferences.</p> <p>Do not forget that these are largely <strong>heuristics</strong>. They won't have much advantages over one another. That is why there are so many.</p> <p>As a guideline, look at the definitions. Choose that index, whose equation is most relevant for your problem. (Yes, you <em>do</em> need to understand what they do. Clustering is hard, it is easy to get meaningless results by just looking at the code and scores and forgetting the underlying math.)</p>
https://datascience.stackexchange.com/questions/27978/what-is-the-advantage-of-using-dunn-index-over-other-metrics-for-evaluating-clus
Question: <p>I'm trying to figure out how much complexity I can get away with and am looking for model recommendations.</p> <p>I have transactional data on hand - the features being customer id, customer balance, transaction amount, transaction date/time, receiver id (possibly a company), company_type (if a company).</p> <p>So I would like to represent this as a graph - nodes being entities (customers and companies) and edges being transactions.</p> <p>So the nodes have features (balance, other customer information) for both customer nodes and company nodes (company type is the only feature for companies) and the edges have features (amount and time). Note that most edges (transactions) are between customers and companies, some are between customers only.</p> <p>So this is a time evolving (mostly) heterogeneous graph with both node and edge features!</p> <p>I would like to know what kind of algorithms are at hand here. I am thinking of clustering algorithms (i.e, trying to isolate the 'consumer base' for each company, etc) or link prediction (for recommending stores to customers). But I am struggling to consider all of these features at once.</p> <p>So far I am losing the time dimension and instead creating a transaction frequency instead as a new edge weight on transactions. Then I am losing the heterogeneous aspect and just creating one node type with a categorical feature for customer/company.</p> <p>Now I was thinking of running something like k-clique algorithm on this for clustering.</p> <p>This should work but is pretty basic and I was hoping for something cooler like a Temporal-Graphical Convolutional Network.</p> <p>If anyone has any recommendation on what to use or what to look at here, that would be great!</p> Answer:
https://datascience.stackexchange.com/questions/124702/graph-clustering-algorithms-when-both-nodes-and-edges-have-features-numerical
Question: <p>Lets give an example <code>X: 1 2 3 4 5 Y: .9 .91 .92 .93 .94 Z: 20 36 999 211 M. 4000 3456 1 0</code></p> <p>When I have such dataset, Which clustering algorithm to choose ? Also, How to interpret the results after clustering ? Meaning: How to feed 4D dataset into cluster.</p> <p>I found DBSCAN available on internet for 2D with which plot is possible. Since my dataset is 4 D and varies ILLOGICALLY...I am afraid to feed this to Algorithm</p> <p>`</p> <pre><code>import pdb import matplotlib.pyplot as plt from numpy.random import rand from numpy import square, sqrt def regionQuery(P, eps, D): neighbourPts = [] for point in D: #print point if sqrt(square(P[1] - point[1]) + square(P[2] - point[2]))&lt;eps: neighbourPts.append(point) return neighbourPts def DBSCAN(D, eps, MinPts): noise = [] visited = [] C = [] c_n = -1 for point in D: visited.append(point) #marking point as visited # print point neighbourPts = regionQuery(point, eps, D) if len(neighbourPts) &lt; MinPts: noise.append(point) else: C.append([]) c_n+=1 expandCluster(point, neighbourPts, C, c_n,eps, MinPts, D, visited) print("no. of clusters: " , len(C) ) print("length of noise:", len(noise)) for cluster in C: col =[rand(1),rand(1),rand(1)] #print(cluster) plt.scatter([i[1] for i in cluster],[i[2] for i in cluster],color=col) plt.show() def expandCluster(P, neighbourPts, C, c_n,eps, MinPts, D, visited): C[c_n].append(P) for point in neighbourPts: if point not in visited: visited.append(point) neighbourPts_2 = regionQuery(point, eps, D) if len(neighbourPts_2) &gt;= MinPts: neighbourPts += neighbourPts_2 if point not in (i for i in C): C[c_n].append(point) eps =20#input("enter eps") x=200*rand(10) y=200*rand(10) l=[] for i in range(10): l.append([i,x[i],y[i]]) #pdb.set_trace() DBSCAN(l,eps,1) </code></pre> <p>` </p> Answer: <p>DBSCAN is not limited to 2d (apparently you only found very bad implementations) and can be used with correlation distance, too. </p> <p>But mostly, you need to focus on preprocessing.</p> <p>If you intend to do correlation anyway, you should consider to z normalize your input data, I.e. <code>x'= (x - mean(x))/stddev(x)</code></p>
https://datascience.stackexchange.com/questions/17997/which-clustering-algorithm-to-use-for-unique-4dimension-dataset-before-feeding-t
Question: <p>For vanilla K-Means clustering algorithm I know that the time complexity is:</p> <blockquote> <p>Time complexity: O(tknm),</p> </blockquote> <p>where n is the number of data points, k is the number of clusters, and t is the number of iterations, m is the dimensionality of the vectors. </p> <p>So, when I studied about Mini-batch K-Means to make the algorithm converge faster, I wanted to find out what is the Space &amp; Time complexity of it? </p> <p>Essentially so that I understand well, how much we are optimizing over vanilla K-Means.</p> Answer: <p>Infinite.</p> <p>Mini-batch k-means never converges, you need to use an iteration limit or similar heuristic, and you can never guarantee to have found a local optimum.</p> <p>In essence, mini-batch k-means is:</p> <ol> <li>draw a random sample</li> <li>perform one iteration of k-means using this sample</li> <li>repeat</li> </ol> <p>Assuming that your sample size is N, 2 takes O(k N m t) time.</p>
https://datascience.stackexchange.com/questions/19042/what-is-the-space-time-complexity-of-mini-batch-k-means-clustering-algorithm
Question: <p>I am trying to implement the Brown Clustering Algorithm.</p> <p><strong>Paper details: "Class-Based n-gram Models of Natural Language" by Brown et al</strong></p> <p>The algorithm is supposed to in <code>O(|V|k^2)</code> where <code>|V|</code> is the size of the vocabulary and k is the number of clusters. I am unable to implement it this efficiently. In fact, the best I can manage is <code>O(|V|k^3)</code> which is too slow. My current implementation for the main part of the algorithm is as follows:</p> <pre><code>for w = number of clusters + 1 to |V| { word = next most frequent word in the corpus assign word to a new cluster initialize MaxQuality to 0 initialize ArgMax vector to (0,0) for i = 0 to number of clusters - 1 { for j = i to number of clusters { Quality = Mutual Information if we merge cluster i and cluster j if Quality &gt; MaxQuality { MaxQuality = Quality ArgMax = (i,j) } } } } </code></pre> <p>I compute quality as follows:</p> <pre><code>1. Before entering the second loop compute the pre-merge quality i.e. quality before doing any merges. 2. Every time a cluster-pair merge step is considered: i. assign quality := pre-merge quality ii. quality = quality - any terms in the mutual information equation that contain cluster i or cluster j (pre-merge) iii. quality = quality + any terms in the mutual information equation that contain (cluster i U cluster j) (post-merge) </code></pre> <p>In my implementation, the first loop has approx |V| iterations, the second and third loop approx k iterations each. To compute quality at each step requires approx a further k iterations. In total it runs in <code>(|V|k^3)</code> time.</p> <p>How do you get it to run in <code>(|V|k^2)</code>?</p> Answer: <p>I have managed to resolve this. There is an excellent and thorough explanation of the optimization steps in the following thesis: <a href="http://cs.stanford.edu/~pliang/papers/meng-thesis.pdf" rel="nofollow">Semi-Supervised Learning for Natural Language by Percy Liang</a>.</p> <p>My mistake was trying to update the quality for all potential clusters pairs. Instead, you should initialize a table with the quality changes of doing each merge. Use this table to find the best merge, and the update the relevant terms that make up the table entries.</p>
https://datascience.stackexchange.com/questions/896/how-to-implement-brown-clustering-algorithm-in-ovk2
Question: <p>I have a very limited background in data science and dataset processing and I was hoping I could get some help here. I am doing some work that requires clustering certain data points having <span class="math-container">$(x, y)$</span> position values and associated weight <span class="math-container">$W_i$</span> for each point.</p> <p>I started with looking at k-means clustering since I know how many bins or k clusters the data needs to be divided into but I also have an additional criteria regarding the sum of weights <span class="math-container">$W_i$</span> in each cluster being less than/equal to a value <span class="math-container">$W_{max}$</span>.</p> <p>I need to essentially cluster the points along k different <span class="math-container">$y=C_i$</span> lines on XY plane such that the sum of weights for points along each line is less than/equal to <span class="math-container">$W_{max}$</span>. Are there any constrained clustering algorithms that do this. It would a massive help if someone could point me to any open source C++ data science libraries that can help me achieve this.</p> Answer: <p>Modify existing algorithms as necessary.</p> <p>Tutorial example: <a href="https://elki-project.github.io/tutorial/same-size_k_means" rel="nofollow noreferrer">https://elki-project.github.io/tutorial/same-size_k_means</a></p> <p>This should also work if the desired clusters don't have the same weight sum as far as I can tell.</p>
https://datascience.stackexchange.com/questions/50933/looking-for-an-algorithm-which-does-max-sum-clustering
Question: <p>I've a dataset and I want to implement K-Means, Fuzzy C Means, Gaussian Mixture Model, Spectral Graph. After that, I want to see the clusters that I get from different methods. What is the proper way to do that? Or should I only stick one algorithm and try to maximize correctness of that clustering?</p> Answer: <p>Have a look at the scikit learn API, they have a <a href="https://scikit-learn.org/stable/modules/clustering.html" rel="nofollow noreferrer">section</a> dedicated to this topic.</p> <p>If you want to go further, have a look at chapter 3 &quot;Unsupervised Learning and Preprocessing&quot; of the book <strong>Introduction to Machine Learning with Python: A Guide for Data Scientists</strong>, there is a section on clustering methods (they also mention the evaluation of clustering methods which is very insightful)</p>
https://datascience.stackexchange.com/questions/81804/how-to-apply-multiple-clustering-algorithms-to-same-dataset-and-make-comparison
Question: <p>I am working with a mixed data set, corresponding to TV consumption data, with the aim of reducing the number of features to only those relevant to detect TV consumption patterns (or consumption groups) using clustering.</p> <p>The dataset is composed of about 20 dimensions and 2.000.000 samples for 1 day of consumption. I have access to the data of up to 3 years of consumption, so I can exploit up to ~1 billion data. My idea is to start working with only a few days of consumption (and therefore a few million data).</p> <p>3 dimensions are of continuous/numerical type (the date-time of consumption, the duration...) and the remaining dimensions are of discrete/categorical type, with features with binary options (e.g. whether the programme is live or not) or with multiple and even hundreds of options (e.g. name of the programme, theme, type of device, etc). For this reason, I am trying to implement a clustering algorithm with Python that can deal with mixed data.</p> <p>Since I suspect that there are many dimensions that might be irrelevant to my study, I would like to reduce the number of features. To do so, I have thought of applying some clustering algorithm and check that, by removing a given feature, the clustering results are not affected.</p> <p>However, I don't know what metric I should calculate or use to evaluate the clustering results and the effect of removing one of the attributes.</p> <p>At the moment I have applied the K-prototypes algorithm which is based on K-means but for mixed data. It is easy to implement in Python (<a href="https://antonsruberts.github.io/kproto-audience/" rel="nofollow noreferrer">https://antonsruberts.github.io/kproto-audience/</a>). However, it only returns the cluster labels, the centroid coordinates and the cost (defined as the sum of the distance of all points to their respective centroids). Therefore, I do not know how to interpret the results or how to study the effect of the features.</p> <p>I would like to know if my approach to the problem is correct and what metric I should use to evaluate the clustering results and reduce the number of dimensions, as well as if there are other easily implemented algorithms in Python (for clustering or unsupervised feature selection) capable of dealing with the type of data I have.</p> Answer: <p>Some common techniques to reduce number of features:</p> <ul> <li><p>Missing Values Ratio. Data columns with too many missing values are unlikely to carry much useful information. Thus data columns with number of missing values greater than a given threshold can be removed. The higher the threshold, the more aggressive the reduction.</p> </li> <li><p>Low Variance Filter. Similarly to the previous technique, data columns with little changes in the data carry little information. Thus all data columns with variance lower than a given threshold are removed. A word of caution: variance is range dependent; therefore normalization is required before applying this technique.</p> </li> <li><p>Random Forests / Ensemble Trees. Decision Tree Ensembles, also referred to as random forests, are useful for feature selection in addition to being effective classifiers. <strong>Personally I will prefer this method</strong> as it is easy to implement. Example use is given in the kernel --&gt; <a href="https://www.kaggle.com/prashant111/xgboost-k-fold-cv-feature-importance?scriptVersionId=48823316&amp;cellId=74" rel="nofollow noreferrer">https://www.kaggle.com/prashant111/xgboost-k-fold-cv-feature-importance?scriptVersionId=48823316&amp;cellId=74</a></p> </li> <li><p>High Correlation Filter. Data columns with very similar trends are also likely to carry very similar information. In this case, only one of them will suffice to feed the machine learning model. Here we calculate the correlation coefficient between numerical columns and between nominal columns as the Pearson’s Product Moment Coefficient and the Pearson’s chi square value respectively. Pairs of columns with correlation coefficient higher than a threshold are reduced to only one. A word of caution: correlation is scale sensitive; therefore column normalization is required for a meaningful correlation comparison.</p> </li> </ul> <p>Refer : <a href="https://www.kdnuggets.com/2015/05/7-methods-data-dimensionality-reduction.html" rel="nofollow noreferrer">https://www.kdnuggets.com/2015/05/7-methods-data-dimensionality-reduction.html</a></p>
https://datascience.stackexchange.com/questions/93912/how-can-i-reduce-the-number-of-dimensions-using-a-clustering-algorithm-in-a-mixe
Question: <p>I have a large labeled dataset with 29 classes. Is is possible to use a clustering algorithm (like k-means) in this dataset, or it's not possible since clustering algorithms are unsupervised ? </p> Answer: <p>You can do many things:</p> <ul> <li>Forget about the labels: just use the features that are not labels and cluster along those features using the k-means algorithm (or another).</li> <li>Forget about the features: this is the dummiest way of clustering. Cluster the data in 29 clusters according to the labels that they have. If you want less clusters, you can compute the centroids of the classes and use them to join clusters of different labels.</li> <li>Use everything: create a categorical variable refering to the class that every example belongs to. Then, with this new variable and all the features perform a classical clustering algorithm.</li> </ul> <p>The way to proceed depends on if you want to use the labels or not, and how much importance you want them to have.</p>
https://datascience.stackexchange.com/questions/31975/clustering-a-labeled-data-set
Question: <p>We are trying to run J48 on a classified data set. Our class attribute has two possible values ( 0,1) when running J48 the tree terminates at the very first node and doesnt process any further.</p> <p>Instead of considering (0- false) as the starting point of J48. How can we consider running J48 by selecting (1-true) as the starting point of the tree?</p> <p>Any suggestion will be greatly appreciated.</p> Answer: <p>I am assuming that you have only 1 attribute (numeric). What you can do is </p> <ol> <li>modify the .arff file and set 0s to 1 and 1s to 0.</li> <li>Then you can again run j48 classifier and visualise the decision tree.</li> </ol> <p>It would give you inverted result. Also, try watching this video.<a href="https://www.youtube.com/watch?v=l7R9NHqvI0Y" rel="nofollow">WEKA on MOOC</a></p>
https://datascience.stackexchange.com/questions/6316/weka-class-attribute-suggestion
Question: <p>i create a decision tree model using c4.5 algorithm. After create the model, i evaluate model using 10 fold cross validation and classify model using test data to get accuracy. And then I run prune tree with REP. </p> <p>My question is what data should i use to compare accuracy (after prune and before prune) to decide to remove the leaf? and from where i get the accuracy? using cross validation or classify test data?</p> Answer: <p>The reduce error pruning strategy works in the following way:</p> <ol> <li>Train a tree on a training data set</li> <li>Fit a pruning data set (which is different than the training data set) to the tree. What you will have is the tree as was learned at step one, but for each node you will have some instances from the pruning data set.</li> <li>Prune each node from the tree if the misclassification error computed for the instances from the pruned data set is not larger than the original misclassification error rate computed on the training data. For example, suppose that you do a binary classification and you build a tree from a training data set. Now you fit data from the pruning data set and some instances arrives in a given non-leaf node. Suppose that at that node arrives $2$ positive instances and $8$ negative instances. This gives an error rate of $0.2$. Now from that node the instances are split given to the criteria already learned into two children node, one will have $2$ positive instances and $2$ negative instances, and in the other child node goes the other $6$ negative instances. The cumulative error on children is also $0.2$. This means that going further with the split would make no sense, since the data varies a lot. That means you can actually cut the child nodes and make the original non-leaf node a leaf node. </li> </ol> <p>The point of using fresh data (pruning data set) is to check if the split is useful or the noise from data covers the signal given by the split. </p> <p>To evaluate the performance of both models, before and after pruning, you need another <strong>different</strong> data set, named validation data. To see way you have to understand that pruning is actually also part of extended training. The only difference than usual learning is that in training with REM you learn how to extend using some data and you learn how to unlearn using some other data. </p> <p>If you use the same data from training to do pruning you simply do not progress (you can stop early). To use for pruning the data set for testing will invalidate you model selection criteria, since it will almost always be the case that the pruning tree performs better (original tree learns from training data set, pruned tree learn from both). I dare to say that if you would like to asset the prediction error, you will have to use a different data set, or envelope everything in a cross validation. </p>
https://datascience.stackexchange.com/questions/10115/pruning-tree-using-rep
Question: <p>Suppose we use a decision tree to predict if a bank customer can pay back a credit. So it is a two class classification problem. Now we can make two mistakes:</p> <ul> <li>$\alpha$ error: The customer can back the credit, but we predict he can't.</li> <li>$\beta$ error: The customer can't pay back the credit, but we predict he can.</li> </ul> <p>Now we know that $\beta$ errors are 123.4 times as expensive as $\alpha$ errors. But we only have a given set of data. In this set we have $n_1=10000$ customers who paid back the credit and $n_2 = 100$ customers who didn't.</p> <p>How can the training of the decision tree be adjusted to account for the fact that $\beta$ errors are more expensive?</p> <p>(Note: This is a theoretical question to learn about decision trees. I know about other classifiers like neural networks and I know of ensembles. However, I only want to know about decision trees here.)</p> Answer: <p>Theoretically, decision tree algorithms specify the feature as well as the threshold that maximize the separation between classes at each node. This can be done by solving optimization problem related to the entropy at the children nodes. You can modify this optimization problem by including the miss- classification costs you have in the optimization problem so the algorithm will be biased toward the most expensive class </p>
https://datascience.stackexchange.com/questions/11379/how-can-decision-trees-be-tuned-for-non-symmetrical-loss
Question: <p>I'm doing some ADA boosting with Decision stumps and in inducing a binary classifying decision stump, i'm finding both leaf nodes to have a positive value. Can this be the case? Is this possible?</p> Answer: <p>What is the overall response rate? If it's low (even 15-20%) it may be difficult to find decision stumps that contain one leaf with > 50% response! </p> <p>You could consider oversampling or changing cutoff probability, but I think if your using only 2 leaf trees, your model is bound to struggle.</p>
https://datascience.stackexchange.com/questions/11752/decision-stumps-with-same-value-leaf-nodes
Question: <p>For example I have the following data structure:</p> <pre><code>user: Chris age: 32 income: 60.000 basket value: 45 </code></pre> <p>I want predict the basket value, and my features are the age and income.</p> <p>With a linear regression I get a regression function as the result of the fitting for example: $$y = 0.5x + 0.785$$</p> <p>Now I can use the function for prediction.</p> <p>What is the form of the result of the fitting by regression decision tree? Is it also a function?</p> Answer: <p>Yes. It is also a function, but not an affine transformation of the input but a relatively complex sum of products of indicator functions of the input. Usually, this function is represented by the fitted tree and not as a formula.</p> <p>So e.g. if you learn a tree of depth one and the split is at age 40 with mean response of 80 if age &lt; 40 and mean response of 100 if age $\ge$ 40, then the function could look like $$ \hat f(\text{age}, \text{income}) = 80 \cdot {\mathbf 1}\{\text{age} &lt; 40\} + 100 \cdot {\mathbf 1}\{\text{age} \ge 40\} $$ You can maybe imagine how long the formula is if the depth is 7...</p>
https://datascience.stackexchange.com/questions/24167/forecasting-how-decision-tree-work
Question: <p>I am reading the gini index definition for decision tree: </p> <pre><code>Gini impurity is a measure of how often a randomly chosen element from the set would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset. </code></pre> <p>This seems to be the same as misclassification. Is Gini index just a fancy name for misclassification? Or is there really some subtle difference? Thanks!</p> Answer: <blockquote> <p>Is Gini index just a fancy name for misclassification?</p> </blockquote> <p>No.</p> <p>Note that Gini index definition doesn't involve predicted values, and also it involves some probabilities, which are not dependent on classifier.</p> <p>Also in context of decision trees, Gini impurity corresponds to <strong>each region</strong>, and is not a single value, such as missclassification rate (technically you could also count missclassification rate per region, but then you'd also ).</p> <p>See <a href="https://github.com/lambdaofgod/stackexchange/blob/master/datascience/Difference%20between%20impurity%20and%20misclassificaton.ipynb" rel="nofollow noreferrer">this notebook</a> for a concrete example.</p>
https://datascience.stackexchange.com/questions/31535/difference-between-impurity-and-misclassificaton
Question: <p>See5 / C5.0 is Data Mining Tools available from <a href="https://www.rulequest.com/see5-info.html" rel="nofollow noreferrer">rulequest</a></p> <p>I want to compile C50 for Linux, preferably for CentOS 6.x, but I am unable to compile. I have also tried on Ubuntu, but not success there as well. </p> <p>I have downloaded C50.tgz from <a href="https://www.rulequest.com/GPL/C50.tgz" rel="nofollow noreferrer">C5.0 Release 2.07 GPL Edition</a> After extracting when I run ./Makefile it gives below error on Ubuntu18</p> <pre><code>./Makefile: line 9: CC: command not found ./Makefile: line 10: CFLAGS: command not found ./Makefile: line 11: S: command not found ./Makefile: line 11: LFLAGS: command not found ./Makefile: line 12: SHELL: command not found ./Makefile: line 19: src: command not found ./Makefile: line 48: obj: command not found ./Makefile: line 59: all:: command not found cat defns.i global.c c50.c construct.c formtree.c info.c discr.c contin.c subset.c prune.c p-thresh.c trees.c siftrules.c ruletree.c rules.c getdata.c implicitatt.c mcost.c confmat.c sort.c update.c attwinnow.c classify.c formrules.c getnames.c modelfiles.c utility.c xval.c\ | egrep -v 'defns.i|extern.i' &gt;c50gt.c make: /bin/csh: Command not found Makefile:75: recipe for target 'c5.0' failed make: *** [c5.0] Error 127 ./Makefile: line 61: CC: command not found ./Makefile: line 61: LFLAGS: command not found ./Makefile: line 61: -o: command not found ./Makefile: line 67: obj: command not found ./Makefile: line 67: c5.0dbg:: command not found ./Makefile: line 68: CC: command not found ./Makefile: line 68: obj: command not found ./Makefile: line 68: -g: command not found ./Makefile: line 74: src: command not found ./Makefile: line 74: c5.0:: command not found ./Makefile: line 75: src: command not found ./Makefile: line 77: CC: command not found ./Makefile: line 77: LFLAGS: command not found ./Makefile: line 77: -O3: command not found strip: 'c5.0': No such file ./Makefile: line 82: obj: command not found ./Makefile: line 85: .c.o:: command not found ./Makefile: line 86: syntax error near unexpected token `newline' ./Makefile: line 86: ` <span class="math-container">$(CC) $</span>(CFLAGS) -c $&lt;' </code></pre> <p>If I run make command, it gives below error. </p> <pre><code>make c5.0 make: /bin/csh: Command not found Makefile:60: recipe for target 'all' failed make: *** [all] Error 127 </code></pre> <p>gcc version is:</p> <pre><code>gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 </code></pre> Answer: <p>After extracting <code>C50.tgz</code> file, give execution rights to <code>Makefile</code>.</p> <pre><code>chmod +x Makefile </code></pre> <p>Then install csh</p> <pre><code>sudo apt install csh </code></pre> <p>Run below command to check if csh is install and check csh version (if installed)</p> <pre><code>dpkg -l csh </code></pre> <p>It should show output like below.</p> <pre><code>Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-==============================-====================-====================-================================================================== ii csh 20110502-3 amd64 Shell with C-like syntax </code></pre> <p>Now run below command.</p> <pre><code>./Makefile </code></pre> <p>It should give output like below. (Ignore the warning messages).</p> <pre><code>./Makefile: line 9: CC: command not found ./Makefile: line 10: CFLAGS: command not found ./Makefile: line 11: S: command not found ./Makefile: line 11: LFLAGS: command not found ./Makefile: line 12: SHELL: command not found ./Makefile: line 19: src: command not found ./Makefile: line 48: obj: command not found ./Makefile: line 59: all:: command not found cat defns.i global.c c50.c construct.c formtree.c info.c discr.c contin.c subset.c prune.c p-thresh.c trees.c siftrules.c ruletree.c rules.c g etdata.c implicitatt.c mcost.c confmat.c sort.c update.c attwinnow.c classify.c formrules.c getnames.c modelfiles.c utility.c xval.c\ | egrep -v 'defns.i|extern.i' &gt;c50gt.c gcc -ffloat-store -O3 -o c5.0 c50gt.c -lm c50gt.c: In function ‘ListAttsUsed’: c50gt.c:14025:12: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] Att = (Attribute) DefSVal(D[e]); ^ c50gt.c: In function ‘Error’: c50gt.c:15561:17: warning: format not a string literal and no format arguments [-Wformat-security] fprintf(Of, Buffer); ^~~~~~ strip c5.0 rm c50gt.c ./Makefile: line 61: CC: command not found ./Makefile: line 61: LFLAGS: command not found ./Makefile: line 61: -o: command not found ./Makefile: line 67: obj: command not found ./Makefile: line 67: c5.0dbg:: command not found ./Makefile: line 68: CC: command not found ./Makefile: line 68: obj: command not found ./Makefile: line 68: -g: command not found ./Makefile: line 74: src: command not found ./Makefile: line 74: c5.0:: command not found ./Makefile: line 75: src: command not found ./Makefile: line 77: CC: command not found ./Makefile: line 77: LFLAGS: command not found ./Makefile: line 77: -O3: command not found ./Makefile: line 82: obj: command not found ./Makefile: line 85: .c.o:: command not found ./Makefile: line 86: syntax error near unexpected token `newline' ./Makefile: line 86: ` <span class="math-container">$(CC) $</span>(CFLAGS) -c $&lt;' </code></pre> <p>You will see a new file <code>c5.0*</code> Check command line options with below command.</p> <pre><code>./c5.0 -h </code></pre> <p>it should show below output.</p> <pre><code>C5.0 [Release 2.07 GPL Edition] Fri Mar 15 17:43:39 2019 ------------------------------- Options: -f &lt;filestem&gt; application filestem -r use rule-based classifiers -u &lt;bands&gt; order rules by utility in bands -w invoke attribute winnowing -b invoke boosting -t &lt;trials&gt; number of boosting trials -p use soft thresholds -e focus on errors (ignore costs file) -s find subset tests for discrete atts -g do not use global tree pruning -m &lt;cases&gt; restrict allowable splits -c &lt;percent&gt; confidence level (CF) for pruning -S &lt;percent&gt; training sample percentage -X &lt;folds&gt; cross-validate -I &lt;integer&gt; random seed for sampling and cross-validation -h print this message </code></pre> <p>Now C50 is ready to be used. Here is a sample command(assuming sampledata.data and sampledata.names files exists in the same folder).</p> <pre><code>./c5.0 -r -f sampledata </code></pre> <p>After successful execution of the command, sampledata.rules will be generated in the same folder.</p> <p>See full tutorial from <a href="https://www.rulequest.com/see5-unix.html" rel="nofollow noreferrer">here</a></p>
https://datascience.stackexchange.com/questions/47309/compile-see5-c50-gpl-edition
Question: <p>I've been fiddling with weka's J48 decision tree implementation (C4.5). My goal is to implement cost complexity prunning using weakest link cut method. Basically my algorithm iteratively prunes the tree creating trees with fewer nodes from the previous ones (<span class="math-container">$ T_0 &gt; T_1 &gt; T_2 &gt;...&gt;T_N$</span>).</p> <p>My goal now is how do I find that <span class="math-container">$N$</span> from <span class="math-container">$T_N$</span> meaning how many times should I prune the tree. The algorithm seems to prune pretty aggressively, few iterations too much and it will be completely prunned.</p> <p>For now I'm using the stop condition regarding the complexity factor and I stop the prunning when <span class="math-container">$\alpha \gt 0.001$</span> (from <span class="math-container">$R(t) = R(t) + \alpha|T|$</span>) . This works pretty well for the two datasets I've tested so far but I wouldn't bet my money on it.</p> Answer:
https://datascience.stackexchange.com/questions/48789/number-of-iterations-for-minimal-cost-complexity-prunning
Question: <p>Say I have AttributeA that can take values A1, A2, A3, AttributeB that can take values B1, B2, B3, etc. and I know ahead of time that my classification table looks like</p> <p>AttributeA | AttributeB | AttributeC | Classification</p> <p>A1 | B1 | anything | Class 1</p> <p>anything | B2 | anything | Class 2</p> <p>A3 | B1 | C2 | Class 3</p> <p>A2 | anything | C3 | Class 4</p> <p>...</p> <p>I'm curious how I would modify a decision tree to handle attributes that can take on any value. One idea I had was to change single rules with "anything" into multiple rules where every possible value of that attribute is explicitly stated. For instance, the rule A1 | B1 | anything | Class 1 could be changed into the three rules:</p> <p>A1 | B1 | C1 | Class 1</p> <p>A1 | B1 | C2 | Class 1</p> <p>A1 | B1 | C3 | Class 1</p> <p>I'm sure this would work, but I'd like to see if there are any existing decision tree implementations that can handle "anything" or "does not matter" entries. </p> Answer: <p>I think your description of anything matches the idea of missing values. Basically by stating that a value could take any value you say that you do not know the value. In standard Breiman description of CART or random forests there is a way to handle missing values. If you use Python stack, however, the implementations does not allow missing values. If that is the case one surrogate would be a different new value for categorical data. For numerical continuous variables I don’t know something better than imputing with average, but it is not quite the same thing.</p>
https://datascience.stackexchange.com/questions/55862/how-should-a-decision-tree-handle-an-attribute-that-can-be-anything
Question: <p>I have a data set with ordinal features.Each feature might have 6 to 7 levels. Based on my search for R if you have ordinal data, rpart treats ordinal and nominal differently. <a href="https://stats.stackexchange.com/questions/94502/decision-tree-splitting-factor-variables">https://stats.stackexchange.com/questions/94502/decision-tree-splitting-factor-variables</a></p> <p>But now I'm implementing the decision tree with Python and there nothing comparable to rpart to handle ordinal data. It seems Python sklearn does not handle categorical data well and I have to use one hot encoding. In this case, the order of level like level 1 to level 2 to level3......to level 6 will just disappear.</p> <p><a href="https://stackoverflow.com/questions/38108832/passing-categorical-data-to-sklearn-decision-tree">https://stackoverflow.com/questions/38108832/passing-categorical-data-to-sklearn-decision-tree</a></p> <p>Any suggestions? Thanks.</p> Answer: <p>Ordinal variables are treated exactly the same as numerical variables by decision trees. (And so, you might as well encode them as consecutive integers.)</p> <p>As for (unordered) categorical variables, LightGBM (and maybe H2O's GBM?) supports the optimal <code>rpart</code>-style splits [using the response-ordering trick when suitable, else trying all splits when not too expensive]. If you want a single decision tree, just set hyperparameters accordingly.</p> <p>See also:<br> <a href="https://datascience.stackexchange.com/q/52066/55122">Why decision tree needs categorical variable to be encoded?</a><br> <a href="https://datascience.stackexchange.com/q/36303/55122">Ordinal Attributes in a Decision Tree</a></p>
https://datascience.stackexchange.com/questions/58745/ordinal-features-to-decision-tree-in-python
Question: <p>Decision tree functions are discontinuous functions of the predictors. Have continuous decision trees with smooth transitions been studied? For example, a decision tree in two variables</p> <pre><code>f(x1,x2) = c1 if x1 &lt; t1 and x2 &lt; t2 c2 if x1 &lt; t1 and x2 &gt;= t2 c3 if x1 &gt;= t1 and x2 &lt; t3 c4 if x1 &gt;= t1 and x2 &gt;= t3 </code></pre> <p>could be replaced by</p> <pre><code> f(x1,x2) = c1*lg(t1-x1)*lg(t2-x2) + c2*lg(t1-x1)*lg(x2-t2) + c3*lg(x1-t1)*lg(t3-x2) + c4*lg(x1-t1)*lg(x2-t3) </code></pre> <p>where lg is the logistic function.</p> Answer:
https://datascience.stackexchange.com/questions/61382/continuous-decision-trees-using-logistic-functions
Question: <p>I'm working through a decision tree by hand to learn it. From my research, I have found the following three ways of determining which variables to split on:</p> <ol> <li>Minimum remaining values - The variable with the fewest legal values is chosen</li> <li>Degree heuristic - The variable with the most constraints on remaining values</li> <li>Least Constraining value - The variable that rules out the fewest remaining values in the remaining variables</li> </ol> <p>Do I have these right? What are some other ways of determining the splits?</p> Answer: <p>You might have mixed up CSP (Constrained Satisfaction Problem) search trees and decision trees:</p> <p><strong>CSP search trees</strong></p> <p>'Minimum remaining values', 'Degree Heuristic' and 'Least Constraining Value' are used to solve CSPs and not in decision trees (i.e. we are talking symbolic AI here and not a sub-symbolic AI method like decision trees). </p> <p>However, as far as I know the 'least constraining value' approach is not used to select a variable but after having selected one to choose the order to inspect its values. </p> <p>So it could go rather like this:</p> <pre><code>1. Choose a variable applying 'minimum remaining values' 2. If step 1 fails select a variable applying the 'degree heuristic' 3. For the selected variable select its values ordered according to 'least constraining value' </code></pre> <p>Besides the ones you mentioned you could go the really simple route: just pick 'the next' variable or pick randomly. </p> <p>Also see section 6.3.1 in 'Artificial Intelligence: A Modern Approach' by Russel and Norvig.</p> <p><strong>Decision trees</strong></p> <p>In contrast decision trees are a machine learning method. Here you usually choose the best splits for the tree using a greedy algorithm providing the biggest ad-hoc gain (see below list for how to define 'gain'). Typical criteria for the greedy split are:</p> <p>Classification</p> <ul> <li>Information gain (based on entropy)</li> <li>Gini score </li> <li>Classification error (usually not used when building the tree)</li> </ul> <p>Regression</p> <ul> <li>Squared error</li> </ul> <p>Also see sections 9.2.2 and 9.2.3 in 'The Elements of statistical learning' by Hastie, Tibshirani and Friedman. </p>
https://datascience.stackexchange.com/questions/63253/what-are-the-ways-to-identify-a-good-attribute-test-while-constructing-a-decisio
Question: <p>Vague condition: "NumGoals >= 1.23" </p> <p>Preferred condition: "NumGoals > 1".</p> <p>Switched normalization off.</p> <p>Code:</p> <pre><code>from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier, plot_tree import matplotlib.pyplot as plt import numpy as np iris = load_iris() clf = DecisionTreeClassifier() clf = clf.fit(np.array(iris.data, dtype=int), iris.target) plot_tree(clf) plt.show() </code></pre> <p>Possible to treat integers as integers?</p> Answer:
https://datascience.stackexchange.com/questions/64450/decisiontreeclassifier-integer-conditions-integer-outcome-variable
Question: <p>If we have numeric variable, decision trees will use <code>&lt;</code> and <code>&gt;</code> comparisons as splitting criteria. Lets consider this case : If our target variable is <code>1</code> for even numeric value, and <code>0</code> for odd numeric value. How to deal with this type of variables? How to even identify these type of variables if we have <strong>large number of variables</strong>? Is there any specific names for these type of variables?</p> Answer: <p>I would call this bad feature engineering, I'm afraid: as the designer of a ML system, one is supposed to analyze their data and find the best way to make the ML system perform as well as possible. In this case by adding a simple feature <code>x % 2</code> for every instance the decision tree can perform perfectly.</p> <p>[added] Even in the case of a more complex pattern, if there are such "clusters" of numerical values then there must be a logical explanation why this happens, i.e. something which depends on the task that an expert in this problem can analyze and understand. In most real cases this implies that there are some hidden/intermediate variables, and designing the system so that it represents these variables is key. In other words, the numeric variable is not directly semantically relevant for predicting the response variable, because the assumption when using numeric values is that their order matters (here the numeric value behaves more like a categorical variable).</p>
https://datascience.stackexchange.com/questions/71678/numeric-variables-in-decision-trees
Question: <p>I would like to use algorithm ID3 in order to find a decision tree of my <a href="https://www.kaggle.com/rtatman/chocolate-bar-ratings" rel="nofollow noreferrer">dataset</a>. I would like to see which of the attributes and values lead to the different value of rating (1&lt;= x &lt;= 5). Do you think it is possible to do it? I got stucked but I don't know if it is because it is not a possible thing to do or it is my fault as a beginner. Can you give me some advise or hints please?</p> Answer: <p>You can see this dataset as a regression problem and not a classification one. The label is ordered, so predicting 2.8 is not a mistake, it is just that it is close to 3 (satisfactory but not there).</p> <p>I can suggest to start with a regression tree and then round the results to have integers.</p> <p>Also you can consider this a multiclassification task, but as a starter I would go with regression. </p>
https://datascience.stackexchange.com/questions/74675/decision-tree-on-big-categorical-dataset
Question: <p>I am trying to create a prediction model by using a decision tree with Turicreate. While my problem does involve numbers, it also involves strings and ultimately I want it to return the string 'true/false'. Are Turicreate decision trees able to process strings as input and output?</p> Answer: <p>I'm not familiar with the package, but <a href="https://apple.github.io/turicreate/docs/userguide/supervised-learning/linear-regression.html" rel="nofollow noreferrer">the documentation</a> suggests that strings as input will be handled internally by dummy-encoding (with a reference level). The linked section is for linear regression, but is linked to from the <a href="https://apple.github.io/turicreate/docs/userguide/supervised-learning/decision_tree_classifier.html#advanced-features" rel="nofollow noreferrer">Advanced Features section</a> of the decision tree page, so I assume that applies.</p>
https://datascience.stackexchange.com/questions/87391/strings-features-in-turicreate-decision-tree
Question: <p>Standard decision tree algorithms, such as ID3 and C4.5, have a brute force approach for choosing the cut point in a continuous feature. Every single value is tested as a possible cut point. (By tested I mean that e.g. the Information gain is calculated at every possible value.)</p> <p>With many continuous features and a lot of data (hence many values for each feature) this apporach seems very inefficient!</p> <p>I'm assuming finding a better way to do this is a hot topic in Machine Learning. In fact my Google Scholar search revealed some alternative approaches. Such as discretizing with k-means. Then there seem to be a lot of papers that tackle specific problems in specific domains.</p> <p><strong>But is there a recent review paper, blog post or book that gives an overview on common apporaches for discretization?</strong> I couldn't find one...</p> <p>Or else, maybe one of you is an expert on the topic and willing to write up a small overview. That would be tremendously helpful!</p> Answer: <p>No, you probably don't want to try all possible cut points in a serious implementation. That's how we describe it in simple introductions to ID3, because it's easier to understand, but it's typically not how it is actually implemented, because it is slow. In particular, if there are $n$ data points, then you'll need to test $n-1$ candidate thresholds; using the naive algorithm to calculate the information gain of each of those candidate thresholds takes $O(n)$ time per candidate, for a total of $O(n^2)$ time.</p> <p>In practice, there are optimizations that speed this up significantly:</p> <ol> <li><p>Don't try all possible thresholds. Instead, pick a random sample of 1000 candidate thresholds (chosen uniformly at random out of the set of $n-1$ candidate thresholds), calculate the information gain for each, and choose the best one.</p></li> <li><p>Use dynamic programming to efficiently compute the information gain of all $n-1$ splits, in total of $O(n)$ time, by reusing computation. The algorithm is pretty straightforward to derive.</p></li> </ol>
https://datascience.stackexchange.com/questions/18156/how-to-better-discretize-continuous-data-in-decision-trees
Question: <p>Computational vs intuitionistic or expert-based information gain in decision trees?</p> <p>This confuses me.</p> <p>Plenty of literature on how information gain can be used when it's calculated computationally. But what if there's a competing sense of &quot;intuitionistic (or expert-based) information importance&quot;? That is, the researcher has an intution about relative importances and this may not actually be conveyed in the training set. Or some of it may be lost by the model.</p> <p>If one'd use computational methods to infer good split points, then it's possible that these match the training set, but not necessarily the intuition.</p> <p>It's also possible that the intuitional approach would later prove inaccurate in some sense, if new observations would come that display computational information gains that suggest readjusting intuitionistic bounds.</p> <p>So is there some middle-ground to combine these two views?</p> Answer: <p>The core principle in supervised machine learning is that the training data is a representative sample of the true distribution (i.e. the possibly infinite full set of instances that could happen).</p> <p>Under this assumption, the intuition and the numerical information gain (or other statistical measure) are expected to be more or less in agreement, because if they disagree it can only mean that:</p> <ul> <li>Either the intuition was wrong, because if a feature is intuitively important then there should be evidence of that in the data.</li> <li>Or the data is not a proper representative subset of the true distribution (insufficient or noisy training data).</li> </ul> <p>But it's important to keep in mind that a dataset is never perfect and that an intuition is, well, just an intuition. So for example it would be common that the top 3 features A,B,C according to intuition are not exactly the top 3 features according to IG, it might be something reasonably close like B,D,E,A,C for instance.</p> <p>If the data doesn't match the intuition at all, it's worth investigating why. However in general it would be a bad idea to overrule the computed IG value and force the use of &quot;intuitively strong&quot; features, because this is clearly not optimal according to the data.</p>
https://datascience.stackexchange.com/questions/97725/computational-vs-intuitionistic-or-expert-based-information-gain-in-decision-tre
Question: <p>I want to implement my own version of the CART Decision Tree from scrach (to learn how it works) but I have some trouble with the Gini Index, used to express the purity of a dataset.</p> <p>More precisely, I don't understand how Gini Index is supposed to work in the case of a regression tree.</p> <p>The few descriptions I could find describe it as : </p> <pre><code>gini_index = 1 - sum_for_each_class(probability_of_the_class²) </code></pre> <p>Where probability_of_the_class is just the number of element from a class divided by the total number of elements.</p> <p>But I can't use this definition in the case of regression where I have continuous variables.</p> <p>Is there something I misunderstood here ?</p> Answer: <p>In regression trees, sum of squared error (<strong>SSE</strong>) is the criterion for tree split. The first split is based on the feature/predictor and its values in your training set that yields the <strong>lowest SSE</strong> value. And then so on for the further splits.</p>
https://datascience.stackexchange.com/questions/35672/gini-index-in-regression-decision-tree
Question: <p>I was trying to find the original CART paper. I found papers like <a href="https://www.researchgate.net/publication/227658748_Classification_and_Regression_Trees" rel="nofollow noreferrer">https://www.researchgate.net/publication/227658748_Classification_and_Regression_Trees</a> which experimented on CART but was unable to find the original one. Could someone guide me where to find it?</p> Answer:
https://datascience.stackexchange.com/questions/106614/where-can-i-find-the-original-cartclassification-and-regression-trees-publishe
Question: <p>Imagine a set of products in a store, with all the different attributes assigned to them - some of these hierarchical (e.g. categories), and some not (e.g. brand), but none of them continuous (if that is even important here). For each product, we know how much (in money-value) we've sold last year, and how much we sold this year. The sum of all of the differences in these sales is equal to the difference in total sales between the two years.</p> <p>What we're interested in is finding some &quot;nice&quot; rules which describe the biggest sales-change-driving sets of products. For example: &quot;Smartphones have dropped in sales by 10% (\$123456)&quot;, &quot;Apple products increased in sales by 20% (\$31234)&quot;, etc. In other words, an end user is interested in learning &quot;what's driving our sales up and down&quot; in some easily consumable format. Hierarchical attributes should be taken into account here, as well as the combination of &quot;orthogonal&quot; attributes.</p> <p>My question is not about forming those &quot;sentences&quot;, but in general about how to find those structured &quot;rules&quot;. Additionally, how to best identify composite rules, like &quot;Smartphones are dropping in sales, apart from Apple smartphones which are growing&quot;.</p> <p>A very important additional question is how to balance relative and absolute change of these rules. Are there some best-practice approaches on how to deal with this tradeoff?</p> <p>A somewhat naive approach would be to build a decision tree for sales-change prediction (either relative or absolute) for each product, and then use that tree as a foundation for rules, or maybe just &quot;plot&quot; the tree itself and present to the end user.</p> <p>All ideas, even ones very remote to the main question, are very welcome!</p> Answer: <p>I think ML is not needed here, as it is an SQL (or at least pandas) exercise. Namely, you have change in sales for each of the lowest level labels. You also have hierarchical relationship between labels Smartphones -&gt; Apple Smartphones -&gt; iPhone 2. So you basically need to aggregate from lower to higher label levels and look at some higher label levels you care about. Sort them from low to high by the amount you worked out, and those are your rules. There might be some rare, but expensive stuff, so might be worth weighting it by number of sales|valume|other important metric, but that is about it.</p>
https://datascience.stackexchange.com/questions/110370/identifying-subsets-of-values-significant-to-the-total-sum
Question: <p>After training and testing the decision tree model, it always gives me the same outcome on any given data. Im talking about a binary classification yes or no. Basically when I do predict(fit_model, newdata=new_data) I always get no regardless the data I give. The model is quite simple and I can compute the outcome even by just looking at the tree. That's why if I give a certain combination of data, I would expect the outcome being yes by looking at the tree, but it still gives me no. Why that happens and how would I solve this issue? Thanks</p> Answer:
https://datascience.stackexchange.com/questions/111697/decision-tree-question-in-r
Question: <p>There are numerous ways to induce an oblique decision tree in the decision tree induction domain, such as using a support vector machine to determine the best hyper-plane. However, is it possible to generate an oblique decision tree for regression? I discovered that the majority of existing literature has omitted this issue. By the way, is there an open-source machine learning tool that already includes an oblique tree for regression?</p> Answer:
https://datascience.stackexchange.com/questions/93520/how-to-implement-an-oblique-decision-tree-for-regression
Question: <p>I'm new to data science field and interested in performing prediction using clickstream data. In <a href="https://quinonero.net/Publications/predicting-clicks-facebook.pdf" rel="nofollow noreferrer">Practical Lessons from Predicting Clicks on Ads at Facebook</a> paper section 3.1, a method called Decision Tree Feature Transforms confused me a lot. After searching around, there is no website / book / paper describing about this method. Can anyone give me link references describing this method in detail?</p> Answer: <p>What the article mentions is random tree embeddings.</p> <p>This is a kind of unsupervised feature extraction method based on random trees.</p> <p>In python you can find the Scikit-learn implementation.</p> <p>From the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomTreesEmbedding.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Transform your features into a higher dimensional, sparse space. Then train a linear model on these features.</p> </blockquote> <blockquote> <p>First fit an ensemble of trees (totally random trees, a random forest, or gradient boosted trees) on the training set. Then each leaf of each tree in the ensemble is assigned a fixed arbitrary feature index in a new feature space.</p> </blockquote> <blockquote> <p>These leaf indices are then encoded in a one-hot fashion. Each sample goes through the decisions of each tree of the ensemble and ends up in one leaf per tree. The sample is encoded by setting feature values for these leaves to 1 and the other feature values to 0. The resulting transformer has then learned a supervised, sparse, high-dimensional categorical embedding of the data.</p> </blockquote> <p>You may also find these references very helpful:</p> <ol> <li><p><a href="https://gdmarmerola.github.io/forest-embeddings/" rel="nofollow noreferrer">https://gdmarmerola.github.io/forest-embeddings/</a></p> </li> <li><p><a href="https://blog.davidvassallo.me/2019/08/06/3-uses-for-random-decision-trees-forests-you-maybe-didnt-know-about/" rel="nofollow noreferrer">https://blog.davidvassallo.me/2019/08/06/3-uses-for-random-decision-trees-forests-you-maybe-didnt-know-about/</a></p> </li> </ol>
https://datascience.stackexchange.com/questions/94322/tree-based-feature-transformation
Question: <p>For neural networks we have the <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem" rel="noreferrer">universal approximation theorem</a> which states that neural networks can approximate any continuous function on a compact subset of $R^n$.</p> <p>Is there a similar result for gradient boosted trees? It seems reasonable since you can keep adding more branches, but I cannot find any formal discussion of the subject.</p> <p>EDIT: My question seems very similar to <a href="https://datascience.stackexchange.com/questions/9406/can-regression-trees-predict-continuously?rq=1"> Can regression trees predict continuously?</a>, though maybe not asking exactly the same thing. But see that question for relevant discussion.</p> Answer: <p>Yes - create a region for each data point (i.e., memorize the training data).</p> <p>Thus it is possible for gradient boosted trees fit any training data, but it would have limited generalization to new data.</p>
https://datascience.stackexchange.com/questions/32796/can-gradient-boosted-trees-fit-any-function
Question: <p>I am looking through decision trees, and I do not understand what makes each of these methods different. Could someone explain clearly what the difference between these is? Thank you.</p> Answer: <p>As I understand it, all three want to minimize the false classified data points in your data set. (Logically, if you look for what decision trees are used)</p> <p>But each of them comes from another side to this problem.</p> <p><strong>gini impurity wants "better as random"</strong></p> <p>It compares the "I label random data with random labels" against the labeling after possible split by decision tree (Wish is, that you can split the tree with better outcome than "random random random")</p> <p><strong>information gain wants small trees</strong> </p> <p>It uses knowledge from information theory. It models the difference between "good" and "bad" split with criteria "simple/small trees preferred". As a result of this, it want to split the data in a way, that the daughters are "pure as possible".</p> <p>For the chi-square ... I have found two things: CHAID, a (seemingly complex) decision tree technique and the chi square to prune decision trees after their building.</p> <p>The <strong>chi square in general</strong> has its roots in biological statistics. It gives a characteristic number how the observed distribution conform with the null hypothesis one have about this distribution. (Biology have to act like this a lot. "I observe something, I search for an explanation, I form a hypothesis, I probe if this is statistical confirmable")</p> <p>For formulas please look in Wikipedia and other sources.</p>
https://datascience.stackexchange.com/questions/48560/what-is-the-differences-in-the-gini-index-chi-square-and-information-gain-spli
Question: <p>There are common ways to split a tree in decision trees and all their variants:</p> <ul> <li>Gini Index</li> <li>Entropy</li> <li>Misclassification</li> </ul> <p>Why there is not a method which uses directly AUC or accuracy (or whichever the modeler need) to split the nodes.</p> <p>Is it because of common use, or there is a mathematical explanation for it?</p> Answer: <p>On accuracy:<br> <a href="https://datascience.stackexchange.com/questions/14433/why-we-use-information-gain-over-accuracy-as-splitting-criterion-in-decision-tre">Why we use information gain over accuracy as splitting criterion in decision tree?</a></p> <p>AUC has been explored; it seems to work well, but is slower:<br> <a href="https://www.semanticscholar.org/paper/Learning-Decision-Trees-Using-the-Area-Under-the-Ferri-Flach/46e40f487e555277033f188778d6c5c05df8daa4" rel="nofollow noreferrer">https://www.semanticscholar.org/paper/Learning-Decision-Trees-Using-the-Area-Under-the-Ferri-Flach/46e40f487e555277033f188778d6c5c05df8daa4</a><br> <a href="http://proceedings.mlr.press/v7/doetsch09.html" rel="nofollow noreferrer">http://proceedings.mlr.press/v7/doetsch09.html</a> </p>
https://datascience.stackexchange.com/questions/51039/why-is-not-auc-or-other-metrics-used-for-splitting-nodes-in-decision-trees
Question: <p>If I come across decision trees, it is a binary tree with predicates internal nodes. How often do we use m-ary decision trees? Is there any combination of m-ary and binary decision tree, e.g. first level of the tree is binary and second level of the tree consists of m-ary? Same question arises for Random Forest.</p> Answer:
https://datascience.stackexchange.com/questions/62151/how-often-do-we-use-m-ary-decision-trees
Question: <p>According to this post, the time on a 24-hour clock should be decomposed into separate periodic components:</p> <p><a href="https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/" rel="nofollow noreferrer">https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/</a></p> <p>before feeding it into an extratrees algorithm, as 24-hour clock numbers are not ordinal (1 comes right after 24...).</p> <p>My question is, when using decision tree algos, is this necessary? </p> <p>My lay understanding is that tree algos work in feature space, are non-linear, and perform arbitrary splits, hence this is an unnecessary operation?</p> Answer:
https://datascience.stackexchange.com/questions/72965/do-i-need-to-transform-time-with-sin-cos-if-im-using-decision-tree-algorithms
Question: <p>To introduce, I am a novice in ML techniques. I recently had to write a <code>scikit-learn</code> based decision tree classifier to train on a real dataset. Someone suggested me that I must run mu model several thousand times and plot the accuracies on a graph. Here's the rub: I manually ran it around 20 -30 times and every time it gave the same accuracy (for both <code>gini</code> and <code>entropy</code> base). Is that wrong? Should it show slight variations every time? </p> Answer: <p>The scikit-learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html" rel="nofollow noreferrer">DecisionTreeClassifier</a> takes a parameter called <code>random_state</code>. If this is set to an integer, your model should produce the same results every time.</p> <p>The person suggesting you run the model many times would be correct, assuming you allow for no set random state. This means the results should be slightly different every time, because there is some random selection going on in the algorithm. Here is an example from <a href="https://github.com/scikit-learn/scikit-learn/blob/14031f65d144e3966113d3daec836e443c6d7a5b/sklearn/tree/_splitter.pyx" rel="nofollow noreferrer">the splitter classes</a>:</p> <pre><code># Draw a feature at random f_j = rand_int(n_drawn_constants, f_i - n_found_constants, random_state) </code></pre> <p>If are are not setting that random state (or any other kind of random seed), I am not sure off the top of my head, why or how the results would always be identical.</p>
https://datascience.stackexchange.com/questions/37389/does-running-a-decision-tree-classifier-several-times-help
Question: <p>Could you please explain what the hypothesis space for decision tree learning look like?</p> <p>And what is the cardinality of this space?</p> Answer: <p>As per Tom Mitchell's,</p> <p>".....For example, consider the space of hypotheses that could in principle be output by the above checkers learner. This <strong>hypothesis space consists of all evaluation functions that can be represented by some choice of values for the weights</strong> wo through w6. <strong>The learner's task is thus to search through this vast space to locate the hypothesis that is most consistent with the available training examples</strong>....."</p> <p>Hence , Basically all possible combination of distinct trees makes the hypothesis space. </p> <p>Lets say if you have chosen to represent your function to be a linear line then all possible linear lines which go through the data (given input, output) makes up your hypothesis space.</p> <p>Each tree= Single hypothesis , that says this tree shall best fit my data and predict the correct results</p> <p>therefore combination of all such possible tress= hypothesis space.</p> <p>Here is the snippet of PPT from <a href="https://people.eecs.berkeley.edu/~russell/classes/cs194/f11/lectures/CS194%20Fall%202011%20Lecture%2008.pdf" rel="nofollow noreferrer">lecture</a> </p> <p><a href="https://i.sstatic.net/EjCx5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EjCx5.png" alt="enter image description here"></a></p>
https://datascience.stackexchange.com/questions/73941/what-is-the-hypothesis-space-of-decision-tree-learning
Question: <p>I'm trying to follow the suggested outline form implementing ID3</p> <pre><code># Step 1- Calculate MC (Message Conveyed) for the given dataset (let us call it file TF) in reference to the class attribute # MC(TF) = -p1*log2(p1) - p2*log2(p2) # For n classes MC(TF) = -p1log2(p1) - p2*log2(p2)-...-pn*log2(pn) # The probabilities are approximated by relative frequencies. # Step 2- Calculate Gain for every attribute in the training set . # Loop 1: # For each attribute (Aj) Do: # Consider the attribute is a node from which k branches are emanating, # where k is the number of unique values in the attribute # Temporarily, split the file TF into K new files based on the unique values in the attribute Aj. # Let us call these new files F1, . . ., Fk # Total =0; # Loop 2 # for each new file Fi Do: # Calculate MC for the file and call it MC(Fi). # Calculate weight for file Fi and call it Weight(Fi) Weight(Fi) = |Fi|/|TF| # Calculate the weighted MC (WMC) for file Fi # WMC(Fi) = Weight(Fi) * MC(Fi) # Total = Total + MC(Fi) # End of loop 2 # Calculate Gain of Aj # Gain(Aj) = MC(TF) – Total; # End of Loop 1 # The attribute with the highest gain is the winner. # Permanently split the file TF into K new files based on the K unique values of the winner attribute. # Remove the winner attribute from all new K files. # Now you have the root of the tree (the winner attribute) and this tree has k leaves, and each leaf has its own dataset. # Step 3- Examine dataset of each leaf. # If the attribute class has the same value for all the records in the leaf’s dataset, then mark the leaf as “no split” else mark it as “split”. # Step 4- For each leaf’s dataset that is marked “Split” Do. # The dataset become the new TF TF = leaf’s dataset # Go to Step 1; </code></pre> <p>The code that I have written for this program is written as follows:</p> <pre><code>from numpy.core.defchararray import count import pandas as pd import numpy as np import numpy as np from math import ceil, floor, log2 from sklearn.decomposition import PCA from numpy import linalg as LA from sklearn.tree import DecisionTreeClassifier from sklearn.naive_bayes import GaussianNB def calculate_metrics(tp, tn, fn, p, n, fp): # calculate the accuracy, error rate, sensitivity, specificity, and precision for the selected classifier in reference to the corresponding test set. accuracy = tp + tn /(p+n) error_rate = fp + fn /(p + n) sensitivity = tp/ p precision = tp/ (tp+fp) specificity = tn/n display_metrics(accuracy, error_rate, sensitivity, precision, specificity) def display_metrics(accuracy, error_rate, sensitivity, precision, specificity): print(f'Accuracy: {accuracy}, Error_rate:{error_rate}, Sensitivity:{sensitivity}, Precision:{precision}, specificity:{specificity}') def mc(columnName,training_set): column = training_set[columnName] probs = column.value_counts(normalize=True) messageConveyed = -1*np.sum(np.log2(probs)*probs) # print(f'mc {messageConveyed}') return messageConveyed def isUnique(s): a = s.to_numpy() # s.values (pandas&lt;0.24) return (a[0] == a).all() def ID3(root,training_set,test_set): if(root == &quot;&quot;): # Step 1- Calculate MC (Message Conveyed) for the given data set in reference to the class attribute print(f'Step 1- Calculate MC (Message Conveyed) for the given data set in reference to the class attribute') # MC = -p1*log2(p1) - p2*log2(p2) # For n classes MC = -p1log2(p1) - p2*log2(p2)-...-pn*log2(pn) # For each column calculate the gain. numberOfColumns = 0 mcDictionary = {} print('***********************************') print('For each column calculate the gain.') for (columnName, columnData) in training_set.iteritems(): messageConveyed = mc(columnName,training_set) mcDictionary.update({columnName:round(messageConveyed)}) numberOfColumns+=1 print('***********************************') print(f'numberOfColumns {numberOfColumns}') print(f'mcDictionary {mcDictionary}') # The column with the highest gain is the root. print(f'The column with the highest gain is the root.') values = mcDictionary.values() max_value = max(values) print(f'The max value is {max_value}') # print(f'The max value, {max_value}, is associated with column {columnWithMaximumInformationGain}') val_list = list(values) columnWithMaximumInformationGain = list(mcDictionary.keys())[list(mcDictionary.values()).index(max_value)] print(f'The max value, {max_value}, is associated with column {columnWithMaximumInformationGain}') # select the max value from the gain array # this is the new root root = columnWithMaximumInformationGain print(f'root is {root}') print(&quot;******************************************&quot;) print(&quot;************** ROOT ******************&quot;) print(f&quot;TF is {root}**********************&quot;) print(&quot;******************************************&quot;) print(f'isUnique = {isUnique(training_set[root])}') if(isUnique(training_set[root])): return # Step 2 - Repeat for every attribute print(f'Step 2 - Repeat for every attribute') # Loop 1 attribute = &quot;&quot; maximum = 0 for (F, columnData) in training_set.iteritems(): print(f'processing attribute {F}') # Loop 2 Total = 0 uniques = training_set[F].unique() for k in uniques: print(f'processing branch {k} for {F}') # Calculate MC for column messageConveyed = mc(F,training_set) # Calculate the weight for F F_D = training_set[F].count() TF_D = training_set[root].count() weight = F_D/TF_D total = weight*messageConveyed gain = mcDictionary[root] - total if(gain &gt; maximum): attribute = F maximum = gain print(f&quot;gain: {gain} for {F}&quot;) print(f'attribute {attribute} has the max gain of {gain}') print(f'removing {attribute}') root = attribute print(f'new root {root} has branches {training_set[root].unique()}') print(f'root is {root}') print(&quot;******************************************&quot;) print(&quot;************** ROOT ******************&quot;) print(f&quot;TF is {root}**********************&quot;) print(&quot;******************************************&quot;) unique_values = training_set[root].unique() datasets = [] for unique_value in unique_values: print(f'processing for file : {unique_value} ') df_1 = training_set[training_set[attribute] &gt; unique_value] df_2 = training_set[training_set[attribute] &lt; unique_value] datasets.append(df_1) datasets.append(df_2) del training_set[attribute] # Step 3 - Examine dataset of each leaf print(f'Step 3 - Examine dataset of each leaf') print(f'number of datasets {len(datasets)}') print(&quot;*****************&quot;) print(&quot;printing datasets&quot;) print(&quot;*****************&quot;) splits = {} all_values_same = False for df in datasets: print(f'Step 4 - for {attribute} dataset check is marked &quot;split&quot;') if(df[attribute].is_unique): print(f'all values are the same no split') all_values_same = True else: print(f'values are not unique perform split') all_values_same = False splits.update({&quot;split&quot;:df}) if(not all_values_same): for split in splits: ID3(root,split.get(&quot;split&quot;),test_set) else: ID3(root,training_set,test_set) print(&quot;*****************&quot;) # use the training set to predict the test set. # use the Assignment 2--Training set to extract rules and test the quality of the extracted rules against the Assignment 2-- Test set for ID3. test_set = pd.read_csv(&quot;Assignment 2--Test set for ID3.csv&quot;) training_set = pd.read_csv(&quot;Assignment 2--Training set for ID3.csv&quot;) print('***********************************') print('TRAINING SET') print(training_set) print('***********************************') print('***********************************') print('TEST SET') print(test_set) print('***********************************') print(f'test_set: {test_set}') print(f'training_set: {training_set}') def BayesClassifier(training_set,test_set): # use the assignment 2-- training set for Bayes as the training set to classify the records of the assignment 2 test set for bayes X = test_set.values Y = training_set.values clf = GaussianNB() clf.fit(X, Y) # prompt user to select either ID3 or Bayes classifier. selection = &quot;ID3&quot; #= input(&quot;Please enter your selection for either ID3 or Bayes classification: &quot;) threshold = 0.9 #= input(&quot;Please enter a threshold: &quot;) g = 0.05 #= input(&quot;Please enter a value for g: &quot;) root = &quot;&quot; if(selection == &quot;ID3&quot;): ID3(root,training_set,test_set) if(selection == &quot;Bayes&quot;): BayesClassifier(training_set,test_set) </code></pre> <p>The goal of this program is to classify the training data in a decision tree like so</p> <pre><code> Veriety / \ Volume Location </code></pre> <p>ect..</p> <p>The dataset for this program are the following: Assignment 2--Training set for ID3.csv</p> <pre><code>Venue,color,Model,Category,Location,weight,Veriety,Material,Volume 2,6,4,4,4,2,2,1,1 1,2,4,4,4,1,6,2,6 1,5,4,4,4,1,2,1,6 2,4,4,4,4,2,6,1,4 1,4,4,4,4,1,2,2,2 2,4,3,3,3,2,1,1,1 1,5,2,1,4,1,6,2,6 1,2,3,3,3,1,2,1,6 2,6,4,4,4,2,3,1,1 1,4,4,4,4,1,2,1,6 1,5,4,4,4,1,2,1,4 1,4,5,5,5,1,6,2,4 2,5,4,4,4,2,3,1,1 1,5,5,5,5,1,6,2,5 2,6,5,5,5,2,2,1,4 </code></pre> <p>Assingment 2-- Test set for ID3.csv</p> <pre><code>Venue,color,Model,Category,Location,weight,Veriety,Material,Volume 1,6,4,4,4,1,1,1,6 2,5,4,4,4,2,6,1,1 1,6,2,1,4,1,4,2,4 1,6,2,1,4,1,2,1,2 2,6,5,5,5,2,2,1,2 1,5,4,4,4,1,6,2,2 1,3,3,3,3,1,6,2,2 1,5,2,1,1,1,2,1,2 1,4,4,4,1,1,5,3,6 1,4,4,4,4,1,6,4,6 </code></pre> <p>I would sincerely appreciate any help with this. I do not have a clear understanding of what the end result of the program should be. If I could understand the process I'd be able to work through the program.</p> Answer: <p>Ok so let's start with the basics:</p> <ul> <li>ID3 is a decision tree learning algorithm. This is supervised learning, which means that every data point (or instance) has some features <span class="math-container">$x$</span> and a label (or class) <span class="math-container">$y$</span>. The goal is to train a model from some labelled dataset (data which has both <span class="math-container">$x$</span> and <span class="math-container">$y$</span> provided) so that the model can later predict the label <span class="math-container">$y$</span> for any new instance <span class="math-container">$x$</span>.</li> <li>A <a href="https://towardsdatascience.com/a-beginners-guide-to-decision-tree-classification-6d3209353ea" rel="nofollow noreferrer">decision tree</a> represents a &quot;decision process&quot; as a tree: starting from the root, every node represents a question about the input features <span class="math-container">$x$</span>. By answering the questions one by one and following the path of the answers we end up with the final decision (the label). ID3 is an algorithm which builds such a decision tree from some training data. So the output of ID3 is a full decision tree. It can be represented as a list of nodes, where each node has exactly one condition about one feature and points to two other nodes depending on the answer (is the condition true or false).</li> <li>The ID3 process is recursive, it builds nodes one after the other, from the root (top) to the leaves (bottom). Every time it starts by looking at all the available features in order to select the most informative one (the one which helps the most to decide the label) at the current stage. To do that it calculates a statistical measure (for example MC here) on the current subset of data, i.e. the one obtained after filtering according to the previous nodes we went through. Technically the subset is obtained by splitting the current data at every node after selecting the condition, i.e. it's as if each node has a particular subset of training data assigned to it: the root has the full dataset, then each node filters the subset they receives, until the leaves where there's no need to split anymore.</li> </ul> <p>Hope this helps clarifying the general idea.</p>
https://datascience.stackexchange.com/questions/104516/how-to-implement-id3
Question: <p>For example, a drug prediction problem using a decision tree. I trained the decision tree model and would like to predict using new data.</p> <p>For example:</p> <pre><code>patient, Attr1, Attr2, Attr3, .., Label 002 90.0 8.0 98.0 ... ? ===&gt; predict drug A </code></pre> <p>How can I calculate the confidence or probability of the prediction result of drug A?</p> Answer: <p>What data mining package do you use?</p> <p>In sklearn, the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.predict_proba" rel="nofollow noreferrer">DecisionTreeClassifier</a> can give you probabilities, but you have to use things like <code>max_depth</code> in order to truncate the tree. The probabilities that it returns is <span class="math-container">$P=n_A/(n_A+n_B)$</span>, that is, the number of observations of class A that have been &quot;captured&quot; by that leaf over the entire number of observations captured by that leaf (during training). But again, you must prune or truncate your decision tree, because otherwise the decision tree grows until <span class="math-container">$n=1$</span> in each leaf and so <span class="math-container">$P=1$</span>.</p> <p>That being said, I think you want to use something like a random forest. In a random forest, multiple decision trees are trained, by using different resamples of your data. In the end, probabilities can be calculated by the proportion of decision trees which vote for each class. This I think is a much more robust approach to estimate probabilities than using individual decision trees.</p> <p>But random forests are not interpretable, so if interpertability is a requirement, use the decision tree like I mentioned. You can use grid search to maximize the ROC AUC score by changing hyperparameters such as maximum depth to find whatever decision tree gives the most reliable probabilities.</p>
https://datascience.stackexchange.com/questions/11171/decision-tree-how-to-understand-or-calculate-the-probability-confidence-of-pred
Question: <p>I am curious if ordinal features are treated differently from categorical features in decision tree, I am interested in both cases where target is categorical or continuous.</p> <p>If there is a difference, could you anybody point to good source with explanation and any packages (R or Python) supporting it?</p> Answer: <p>As per my knowledge, it doesn't matter for a decision tree model whether the features are ordinal or categorical. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features. Decision trees describe patterns by using a list of attributes.</p> <p>For a more detailed explanation, I am providing here some links which you will find helpful for such queries.<br> <a href="http://www.ibm.com/support/knowledgecenter/SS3RA7_17.0.0/clementine/nodes_treebuilding.html" rel="nofollow">http://www.ibm.com/support/knowledgecenter/SS3RA7_17.0.0/clementine/nodes_treebuilding.html</a> </p> <p><a href="http://scikit-learn.org/stable/modules/tree.html" rel="nofollow">http://scikit-learn.org/stable/modules/tree.html</a></p> <p><a href="http://www.ryerson.ca/~rmichon/mkt700/SPSS/Creating%20Decision%20Trees.htm" rel="nofollow">http://www.ryerson.ca/~rmichon/mkt700/SPSS/Creating%20Decision%20Trees.htm</a></p>
https://datascience.stackexchange.com/questions/14025/ordinal-feature-in-decision-tree
Question: <p>Can anybody please explain the affect of multicollinearity on Decision Tree algorithms (Classification and regression). I have done some searching but was not able to find the right answer as some say it affects it and others say it doesn't.</p> Answer: <p>Desicion trees make no assumptions on relationships between features. It just constructs splits on single features that improves classification, based on an impurity measure like Gini or entropy. If features A, B are heavily correlated, no /little information can be gained from splitting on B after having split on A. So it would typically get ignored in favor of C.</p> <p>Of course a single decision tree is very vulnerable to overfitting, so one must either limit depth, prune heavily or preferly average many using an ensemble. Such overfitting problems get worse with many features and possibly also with co-variance but this problem occurs independently from multicolinearity.</p> <p>While training and predictive power is relatively robust to multicollinearity, feature importance scores will be heavily influenced. So take this into account when trying to interpret the model.</p>
https://datascience.stackexchange.com/questions/31402/multicollinearity-in-decision-tree
Question: <p>Is it possible to do hard-coded decision tree on some variables and random forest / something on the remaining ones?</p> <p>The situation seems that for some variables it's possible to draw strong empirical assumptions, but for others their &quot;relative importance&quot; seems more random.</p> <p>So e.g.</p> <p>Researcher is certain that splitting X1 &gt; 5 and X2 &lt; 3 gives best information, since they are empirically sound splits e.g. based on stakeholder views. And X1, X2 are more important than X3, X4, X5, since X3, X4, X5 are redundant, if X1 or X2 don't exist.</p> <p>Thus the model could essentially be based on X1, X2 only , but X3, X4, X5 should add explanatory power. Yet their relative importances are not known. Using the decision tree to them might be prone to model inaccuracies due to random forest or something perhaps offering better reduction in overfitting etc.</p> Answer: <p>You could use stacking ensemble learning where one of the &quot;learners&quot; is the expert written decision tree. The meta learner will then apply the relevant weight to the expert model such that accuracy is maximized.</p>
https://datascience.stackexchange.com/questions/97748/is-it-possible-to-do-hard-coded-decision-tree-on-some-variables-and-random-fores
Question: <p>I read in a blog that the decision tree has this disadvantage:</p> <blockquote> <p>Not fit for continuous variables</p> </blockquote> <p>If this is true, then why?</p> Answer: <p><strong>Continuos Variable in training data (X)</strong> If you look at decision trees they try to split data based on categories in case of categorical data and based on threholds in case of continuous data. Now to split on continuous data it randomly tries to create BINs and calculate the entropy/ Gain etc whatever you have chosen. This implies that Decision Trees is able to use contnuous variable for training and their is no disadvanatge except it can take a little bit more time to train due to preocess of Bin creation and finding best split on the Bin.</p> <p><strong>Continuos Variable in target (X)</strong> Decision trees works well for regression problem but now objective is not to find splits which give maximum information gain but which reduces variance amongs onservation withing the same leaf nodes.</p> <p><strong>Based on my understanding, In general Decison Trees has been modified to work well with both continuous and categorical data</strong></p>
https://datascience.stackexchange.com/questions/31491/disadvantage-of-decision-tree
Question: <p>I am interested in finding out how decision trees chose the order in which they split. I understand that splitting is based in information gain. The attribute with the lowest information gain is chosen as the root node.</p> <p>If I had a data set with columns:</p> <ol> <li>credit standing</li> <li>age</li> <li>income,</li> <li>marriage status</li> </ol> <p>and I was interested in finding out what determines a person to have a good or bad credit status, Am I correct in saying, I calculate entropy and information gain for each of these categorical attributes against the independent attribute i.e what I am investigating (credit standing), and that the calculation with the lowest information gain is chosen as the root node.</p> <p>For example, if this root node (first split) was Age, Is the entropy and information gain of Age (the new independent attribute) against the remaining attributes (marriage status and income) calculated, and the calculation with the lowest information gain is then chosen as the second split node, and so on?</p> <p>ie.</p> <p>information gain:</p> <pre><code>credit standing vs age = 0.01 credit standing vs status = 0.1 credit standing vs income = 0.2 </code></pre> <p>Age is chosen as root (first split) node.</p> <p>then, information gain:</p> <pre><code>age vs status = 0.2 age vs income = 0.1 </code></pre> <p>income is chosen as second split node.</p> <p>Am I understanding this correctly?</p> Answer: <p>Here in your Scenario you need to select the one with more <strong>Information Gain</strong> rather than the least one and the process goes on till you reach the last feature/last node.</p> <p>Go through <a href="https://web.cecs.pdx.edu/%7Emperkows/CLASS_ROBOTICS/FEBR26-2004/ROBOT-DECISION-TREE/robot-navigation-using-decision-trees-1.pdf" rel="nofollow noreferrer">These</a> <a href="http://www.ee.pdx.edu/%7Emperkows/CLASS_ROBOTICS/FEBR26-2004/ROBOT-DECISION-TREE/ics320Part3.DecisionTreeLearning.ppt" rel="nofollow noreferrer">Links</a>. I think your doing it vice versa, I agree with <a href="https://datascience.stackexchange.com/users/381/emre">Emre</a>.</p> <p>In the <a href="http://www.ee.pdx.edu/%7Emperkows/CLASS_ROBOTICS/FEBR26-2004/ROBOT-DECISION-TREE/ics320Part3.DecisionTreeLearning.ppt" rel="nofollow noreferrer">link</a> it was explained with an example to decide whether to play tennis or not.</p>
https://datascience.stackexchange.com/questions/24831/decision-tree-ordering
Question: <p>We are working on a physiological marker predictor using hospital patient data. We use a boosted decision tree-type algorithm, which seems to be very sensitive to the noise in the training data. Would it be fair to say the NN's are less sensitive to noisy data than decision trees?</p> Answer: <p>It is not fair to say that Decision Trees are more sensitive to noise in the data comparing to NN.</p> <p>It really depends on your model type (DT, NN, SVM, ... etc) and <strong>the model complexity</strong>. in general, complex models have higher tendency to overfit (overfitting == sensitive to noise in the data). You can adjust the parameters of the DT, for example the max depth and see if this is affecting your results.</p> <p>If you are training a classifier, try to use random forest, random forest are known to be very resistance to noise (overfitting).</p> <p>If you give the NN more capacity, more layers and wider layers, the network will also overfit and become sensitive to noise <strong>if you train for a long time</strong>.</p> <p><strong>Please note:</strong> DT training stops based on specific criteria that controls the model size. based on these parameters, e.g., the max depth, the model can overfit, training will take longer time.</p> <p>NN training stops based on training parameters, for example, the number of iterations, the stopping criteria, and not the complexity. To overfit, you will need to have both complex model and train for a long time. If the model is not sensitive to noise, it can be because, it is not complex enough or training for few number of iterations.</p>
https://datascience.stackexchange.com/questions/119907/noisy-data-robustness-nn-vs-decision-tree
Question: <p>I have a dataset with 20 features(columns that is). I create a few models pairs with a subset of these parameters.</p> <p>For example: If I have 6 columns (named A, B, C, D, E, F) with 10k lines of data, one of model in the pair will have (A, B, C) with all 10k lines of data and the other (A, B, C) with maybe say 6k lines of data. Yet another pair will have the parameters (B, C, E), however, the number of lines is always fixed at 10k and 6k.</p> <p>I am limited to using a sci-kit learn's decision tree and this cannot be changed. I use the following function to calculate my features:</p> <pre><code>model = clf_gini.best_estimator_ print(model.feature_importances_) </code></pre> <p>My question is: **Is there any formal, programmatic way to compare feature importance across model pairs using sci-kit, other than intuition? Also, does it make sense to compare to models trained on some similar some different parameters? **</p> <p>Please let me know if the question is ambiguous, I will clarify.</p> Answer: <p>This may not be the answer you are hoping for (I can't leave a comment because my reputation is too low) but I believe feature importance in Sci-Kit Learn is derived from the average depth at which each feature appears. I don't know of any built-in functions in Sci-Kit Learn but perhaps you could scale the feature importance using the depth of the tree and the number of features?</p> <p>This article may help with developing a comparative measure of feature importance: <a href="https://medium.com/the-artificial-impostor/feature-importance-measures-for-tree-models-part-i-47f187c1a2c3" rel="nofollow noreferrer">https://medium.com/the-artificial-impostor/feature-importance-measures-for-tree-models-part-i-47f187c1a2c3</a>.</p>
https://datascience.stackexchange.com/questions/37660/comparing-parameter-importance-across-models
Question: <p>I read <a href="https://www.researchgate.net/post/How_to_compute_impurity_using_Gini_Index" rel="nofollow noreferrer">https://www.researchgate.net/post/How_to_compute_impurity_using_Gini_Index</a></p> <p>I understand why choosing smallest gini index, but how do I come up with different candidate splits in the first place? How does R come up with the splits? Take the iris data as an instance:</p> <pre><code>plot(iris$Sepal.Length, col=iris$Species, pch=20) </code></pre> <p><a href="https://i.sstatic.net/ZSQsd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZSQsd.png" alt="enter image description here"></a></p> <p>How do I determine where I want to draw the horizontal line to separate each class? I can draw infinitely amount of lines and then compare their gini index, but practically, it will not work.</p> Answer:
https://datascience.stackexchange.com/questions/32129/how-to-come-up-with-the-splitting-point-in-a-decision-tree
Question: <p>in figure B), there are leaves (gray boxes) with 3 values, for example, the leftmost leaf has 19.3 (28/8.7%) as its values, the 3 values are (19.3, 28, and 8.7%). </p> <p>19.3 is the average value of the instances that reach that leaf 28 is the number of instances (out of the 209 total instances) what does the 8.7% mean?</p> <p>thanks</p> <p><a href="https://i.sstatic.net/XnnQ6.png" rel="nofollow noreferrer">!</a>]<a href="https://i.sstatic.net/XnnQ6.png" rel="nofollow noreferrer">1</a></p> Answer:
https://datascience.stackexchange.com/questions/58842/what-do-the-percentages-in-the-leaves-of-a-decision-tree-represent
Question: <p>Consider the following Decision table : <a href="https://i.sstatic.net/jknFz.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jknFz.jpg" alt="enter image description here"></a></p> <p>The following is the reduction process of this table : <a href="https://i.sstatic.net/OzaxQ.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OzaxQ.jpg" alt="enter image description here"></a></p> <p><a href="https://i.sstatic.net/iSgi1.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iSgi1.jpg" alt="enter image description here"></a></p> <p>The above table is the reduced table. But my question why we can't reduce further rule number 3 and 4 Since they differs only in A ? And Also rule number 1&amp;5&amp;7 should has don't care at the condition B ?</p> Answer:
https://datascience.stackexchange.com/questions/66352/decision-table-reduction
Question: <p>I have the following binary Decision Tree:</p> <p><a href="https://i.sstatic.net/YopbR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YopbR.png" alt="enter image description here" /></a></p> <p>Can you please explain how can I report this tree to a person who only understands probabilities?</p> <blockquote> <p>If <strong>ca=1</strong> and <strong>cp_4.0=1</strong>, what’s the probability of <strong>Yes HD</strong>?</p> </blockquote> Answer: <p>While you can calculate the underlying class probabilities from the Gini index (for binary classification), it'll be more straightforward to calculate it from the &quot;value&quot; line in each box. This line simply represents the number of samples that belong in each node, split by the target variable, so you can use this count to calculate a probability.</p> <p>In the bottom-most node, for example, you have value = [4, 55], indicating that among 59 samples which belong in that node (samples that have ca &gt; 0.5 and cp_4.0 &gt; 0.5), 4 are No HD and 55 are Yes HD. Therefore, the probability of Yes HD in that node is 55/59.</p> <p>The Gini index is a measure of how &quot;pure&quot; a node is - as this number gets closer to 0, probability values will become more extreme (closer to 0 or 1), indicating that the decision tree is doing a better job of discriminating the target variable.</p>
https://datascience.stackexchange.com/questions/82102/using-gini-index-how-to-calculate-the-probability-of-correctly-classifying-a-ne
Question: <p>My decision tree entropy is coming more than 1 when I'm calculating it manually. Not sure if there's some calculation error.</p> <p>Trying it on the <a href="https://archive.ics.uci.edu/ml/datasets/iris" rel="nofollow noreferrer">Iris dataset</a>.</p> <p>If I split on sepal length at 6.5 cm, my split looks like this <a href="https://i.sstatic.net/IQ3E6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IQ3E6.png" alt="enter image description here" /></a></p> <p>Now I'm calculating entropy with this formula with the following code below. The problem is that I'm getting entropy values &gt; 1 <a href="https://i.sstatic.net/G261h.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/G261h.png" alt="enter image description here" /></a></p> <p>The labels to the left of the split look like this</p> <pre><code> array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])) </code></pre> <p>The labels to the right look like this</p> <pre><code> array([1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])) </code></pre> <p>The code I'm using to calculate entropy is this</p> <pre><code> def entropy(labels): #This function calculates entropy according to the formula posted above uniques = np.unique(labels,return_counts=True) unique_probs = uniques[1]/sum(uniques[1]) entropy = sum(unique_probs *-np.log2(unique_probs)) return entropy def overall_entropy(split): count_below, count_above = len(split['below'][0]), len(split['above'][0]) #split is a dictionary that has 2 values below and above with the X and y arrays. This line just calculates the total length on the values prob_below, prob_above = count_below / (count_below + count_above), count_above / (count_below + count_above) overall_entropy = prob_below * entropy(split['below'][1]) + prob_above * entropy(split['above'][1]) #This line calculates total entropy of the split by combining individual entropies below and above the split return overall_entropy </code></pre> <p>For this particular split, my entropy comes out to be 1.4, which should not be possible. I'm not sure where I'm making a mistake. Please help</p> <p>I'm posting how the variable <code>split</code> looks on a subset of the data in case it's confusing <a href="https://i.sstatic.net/InhUm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/InhUm.png" alt="enter image description here" /></a></p> Answer:
https://datascience.stackexchange.com/questions/107647/getting-entropy-in-decision-trees-more-than-1
Question: <p>I'm confused by an example I have come across on entropy.</p> <p>In a decision tree, we have after a split on some particular feature, the following subset of our training data. What is the resultant entropy of the target feature in this set?</p> <p><a href="https://i.sstatic.net/VL6iT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VL6iT.png" alt="enter image description here" /></a></p> <p>I thought for feature A the result would be:</p> <p>-65/121(log2(65/121)-56/121 log2(56/121)</p> <p>But that doesn't match the answer provided.</p> Answer:
https://datascience.stackexchange.com/questions/109821/resultant-entropy-of-the-target-feature-example
Question: <p><a href="https://i.sstatic.net/76Ot9.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/76Ot9.jpg" alt="enter image description here" /></a></p> <p>how can I apply decision tree classification to get malnutrition status(target variables are wasting, stunting,overweight,underweight)</p> Answer: <p>Answer: You need to convert your target column into numbers first. You can try the following:</p> <pre><code>df['status'] = df['status'].map({'wasting': 0, 'stunting': 1, 'overweight': 2, 'underweight': 3}) </code></pre> <p>After this you can run your Decision tree and you will get the df['status'] in number format. And then you can convert it back to strings using the following:</p> <pre><code>reverse_mapping = {0: 'wasting', 1: 'stunting', 2: 'overweight', 3: 'underweight'} df['status'] = df['status'].map(reverse_mapping) </code></pre>
https://datascience.stackexchange.com/questions/122304/decision-tree-classification-code-for-categorical-data
Question: <p>I came across the concept of <em>Information Gain</em> in decision trees.</p> <p><a href="https://i.sstatic.net/zAFkb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zAFkb.png" alt="IG" /></a></p> <p>Where <span class="math-container">$I(D_p)$</span> is the information of the parent node and <span class="math-container">$I(D_{\text{left}})$</span> &amp; <span class="math-container">$I(D_{\text{right}})$</span> the information for the respective children.</p> <p>While I think I understand the concept clearly, the name makes me a bit confused. So from information theory, we say that &quot;information&quot; could be interpreted as &quot;surprise/randomness&quot;. In this case, <em>Information Gain</em> is actually the amount of <em>Information</em> we lose, not <em>gaining</em>, as higher gain indicates less randomness/information.</p> <p>What do you think?</p> Answer: <p>Surprise and randomness aren't the same thing. A signal that contains more surprising information is more informationally valuable than one that contains less surprising information, but that has nothing to do with randomness. This links to the concept of information entropy, which is what I think the cause of the confusion is here. Information entropy is a measure of the uncertainty in a variable's possible outcomes. A variable with a high degree of informational entropy is more likely to return &quot;surprising&quot; information, but it's not inherently &quot;surprising&quot;, just highly variable. A lot of non-surprising outcomes are possible alongside the surprising ones. This isn't a measure of how surprising a particular outcome is, but rather of how many possible outcomes can happen. Information Gain reduces Information Entropy by giving you more information about the possible values that variable can take. So if Alice and Bob are both standing outside a building, and I ask where they are each going to go next, there are hundreds of possible options, or a lot of informational entropy. If Bob is blocking the building's only entrance though, then I know Alice can't enter the building. Information about Bob's position has told me something that constrains what Alice can do. This is Information Gain. I have more information about Alice, not less, because of what I saw Bob doing, but the content of that additional information derives from the fact that I now know Alice is capable of doing fewer things, which could be spun as <em>Alice</em> containing &quot;less information&quot;, in a certain sense, but that's not particularly useful.</p>
https://datascience.stackexchange.com/questions/126120/why-is-it-called-information-gain-and-not-information-loss
Question: <p>I read that decision trees (I am using scikit-learn's classifier) are robust to outlier. Does that mean that I will not have any side-effect if I choose not to remove my outliers? </p> Answer: <p>Yes. Because decision trees divide items by lines, so it does not difference how far is a point from lines.</p> <p><a href="https://i.sstatic.net/OBSfq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OBSfq.png" alt="enter image description here"></a></p>
https://datascience.stackexchange.com/questions/37394/are-decision-trees-robust-to-outliers
Question: <p>I asked this in a reply to an answer to another of my questions; but I think this merits its own question since I couldn't find an answer, and it's a pretty interesting question on its own.</p> <p>Suppose we construct a decision tree for classification based on the Gini impurity function. Can we prove that the weighted average of the Gini impurities of children nodes is always les than or equal to the Gini impurity of the parent node?</p> <p>More precisely:</p> <p>Let <span class="math-container">$G(S)=\displaystyle\sum_i p_i(1-p_i)$</span>, where <span class="math-container">$S$</span> is a finite nonempty set of points with known classification, <span class="math-container">$p_i$</span> is the proportion of points in <span class="math-container">$S$</span> with classification <span class="math-container">$i$</span>, and the sum is taken over all classes. In the special case of binary classification, this simplifies to <span class="math-container">$G(S)=2p(1-p)$</span>, where <span class="math-container">$p$</span> is the proportion of one of the classes.</p> <p>Assume that every point <span class="math-container">$x$</span> has a feature <span class="math-container">$f$</span>. Denote the value of this feature by <span class="math-container">$x(f)$</span>. A splitting of <span class="math-container">$S$</span> is defined as a partition of <span class="math-container">$S$</span> into <span class="math-container">$\{S_{left}, S_{right} \}$</span>, where <span class="math-container">$S_{left} = \{x \in S : x(f) \leq c \}$</span> and <span class="math-container">$S_{right} = \{x \in S: x(f) &gt; c \}$</span>. We require both of these sets to be nonempty.</p> <p>A splitting is called good if</p> <p><span class="math-container">$$\frac{|S_{left}|}{|S|} G(S_{left}) + \frac{|S_{right}|}{|S|} G(S_{right}) \leq G(S).$$</span></p> <ol> <li>Must there always exist at least one good splitting?</li> <li>Must all splittings be good?</li> </ol> Answer: <p>I think I've got a proof. Any node can be identified with the vector (p_1,...,p_k) that gives the proportion of points with each classification. The Gini impurity function can then be viewed as a function from R^k to R. The weighted average of the proportions of points in S_left and S_right belonging to a certain class is equal to the proportion of points in S belonging to that class. Thus the inequality is just stating that the Gini impurity function is concave. But that is true; its matrix of second derivatives is just a diagonal matrix whose diagonal entries are all -1.</p>
https://datascience.stackexchange.com/questions/94004/proof-that-gini-impurity-in-a-decision-tree-is-monotone-decreasing
Question: <p>What exactly is the difference between model-based boosting and gradient boosting? For an intro to model-based boosting see <a href="https://cran.r-project.org/web/packages/mboost/vignettes/mboost_tutorial.pdf" rel="nofollow noreferrer">https://cran.r-project.org/web/packages/mboost/vignettes/mboost_tutorial.pdf</a> It seems to me that both terms are equivalent. However, both are used in various literature...</p> Answer: <p>Gradient Boosting is fitting a base learner <span class="math-container">$f_{i}(X)$</span> to the gradient of the loss function of an existing model <span class="math-container">$F_{i-1}(X)$</span> i.e. find base learner <span class="math-container">$f_i$</span> which minimises <span class="math-container">$L(-g_i, f_t(x_i))$</span> where <span class="math-container">$g_i$</span> is the gradient of <span class="math-container">$L(y_i,\hat{y}_i)$</span> with respect to <span class="math-container">$\hat{y}=F_{i-1}(X)$</span> at the current iteration <span class="math-container">$i$</span>. Effectively it's gradient descent in function space.</p> <p>Component wise boosting schemes such as that used by <code>mboost</code> have a list of base learners of which one is selected at each step, i.e.</p> <pre><code>form2 &lt;- y ~ bols(x1) + bols(x2) + bols(x1, by = x2, intercept = FALSE) + bspatial(x1, x2, knots = 12, center = TRUE, df = 1) </code></pre> <p>Specifies 4 possible base learners, <code>bols(x1)</code>, <code>bols(x2)</code>, <code>bols(x1,by=x2)</code> and <code>bspatial(x1,x2)</code>, all of which are regression splines.</p> <p>More generally gradient boosted decision trees fits a tree at each step. So the base learners are arguably more complex.</p> <p>I believe the terms model based and functional are equivalent and both <span class="math-container">`</span>mboost' and GBDT are examples.</p>
https://datascience.stackexchange.com/questions/55128/difference-between-model-based-boosting-and-gradient-boosting
Question: <p>How is AdaBoost different from a Gradient Boosting algorithm since both of them use a Boosting technique?</p> <p>I could not figure out actual difference between these both algorithms from a theory point of view.</p> Answer: <p>Both AdaBoost and Gradient Boosting build weak learners in a sequential fashion. Originally, AdaBoost was designed in such a way that at every step the sample distribution was adapted to put more weight on misclassified samples and less weight on correctly classified samples. The final prediction is a weighted average of all the weak learners, where more weight is placed on stronger learners.</p> <p>Later, it was discovered that AdaBoost can also be expressed in terms of the more general framework of additive models with a particular loss function (the exponential loss). See e.g. Chapter 10 in <a href="https://web.stanford.edu/%7Ehastie/ElemStatLearn/printings/ESLII_print12.pdf" rel="noreferrer">(Hastie) ESL</a>.</p> <p>Additive modeling tries to solve the following problem for a given loss function <span class="math-container">$L$</span>:</p> <p><span class="math-container">$ \min_{\alpha_{n=1:N},\beta_{n=1:N}} L\left(y, \sum_{n=1}^N \alpha_n f(x,\beta_n) \right)$</span></p> <p>where <span class="math-container">$f$</span> could be decision tree stumps. Since the sum inside the loss function makes life difficult, the expression can be approximated in a linear fashion, effectively allowing to move the sum in front of the loss function iteratively minimizing one subproblem at a time:</p> <p><span class="math-container">$ \min_{\alpha_n,\beta_n} L\left(y, f_{n-1}((x) + \alpha_n f_n(x,\beta_n) \right)$</span></p> <p>For arbitrary loss functions this is still a tricky problem, so we can further approximate this by applying a steepest descent with line search, i.e. we update <span class="math-container">$f_n$</span> by taking a step into the direction of the negative gradient.</p> <p>In order to avoid overfitting on the gradient, the gradient is approximated with a new weak learner. This gives you the gradient boosting algorithm:</p> <ol> <li>Start with a constant model <span class="math-container">$f_0$</span></li> <li>Fit a weak learner <span class="math-container">$h_n$</span> to the negative gradient of the loss function w.r.t. <span class="math-container">$f_{n-1}$</span></li> <li>Take a step <span class="math-container">$\gamma$</span> so that <span class="math-container">$f_n= f_{n-1} + \gamma h_n$</span> minimizes the loss <span class="math-container">$L\left(y, f_n(x) \right)$</span></li> </ol> <p>The main differences, therefore, are that Gradient Boosting is a generic algorithm to find approximate solutions to the additive modeling problem, while AdaBoost can be seen as a special case with a particular loss function. Hence, Gradient Boosting is much more flexible.</p> <p>On the other hand, AdaBoost can be interpreted from a much more intuitive perspective and can be implemented without the reference to gradients by reweighting the training samples based on classifications from previous learners.</p> <p>See also <a href="https://stats.stackexchange.com/q/164233/127417">this question</a> for some further references (quote):</p> <blockquote> <ul> <li>In Gradient Boosting, ‘shortcomings’ (of existing weak learners) are identified by gradients.</li> <li>In Adaboost, ‘shortcomings’ are identified by high-weight data points.</li> </ul> </blockquote>
https://datascience.stackexchange.com/questions/39193/adaboost-vs-gradient-boosting
Question: <p>I understand boosting is a sequential learning technique and it use the prediction from previous model as a dataset for new model ,after adding weight to the misclassified data points. The point which was not clear how the weights are added for misclassified ones and diminished for the correctly classified ones. It would be great if veterans can help me to understand this</p> <p>Thanks in advance</p> Answer: <p>Actually, it depends on the boosting algorithm you used. </p> <p>In the original boosting algorithm (Schapire 1990), three classifiers are used (say <span class="math-container">$C_1$</span>, <span class="math-container">$C_2$</span> and <span class="math-container">$C_3$</span>). The training dataset is randomly divided into three subsets, <span class="math-container">$D_1$</span>, <span class="math-container">$D_2$</span> and <span class="math-container">$D_3$</span>. The training process is as follow: </p> <ol> <li><p>Train <span class="math-container">$C_1$</span> using <span class="math-container">$D_1$</span>, and use <span class="math-container">$D_2$</span> to test <span class="math-container">$C_1$</span></p></li> <li><p>The instances in <span class="math-container">$D_2$</span> which misclassified by <span class="math-container">$C_1$</span> (say m instances) are taken as training data for <span class="math-container">$C_2$</span> along with m instances that are correctly classified by <span class="math-container">$C_1$</span></p></li> <li><p>Train <span class="math-container">$C_2$</span> using the 2*m instances taken from step 2</p></li> <li><p>use <span class="math-container">$D_3$</span> to test both <span class="math-container">$C_1$</span> and <span class="math-container">$C_2$</span></p></li> <li><p>Train <span class="math-container">$C_3$</span> on the instances that <span class="math-container">$C_1$</span> and <span class="math-container">$C_2$</span> disagree with each other (namely, the instances that <span class="math-container">$C_1$</span> and <span class="math-container">$C_2$</span> predicted differently)</p></li> </ol> <hr> <p>For Adaboost, the training subsets are selected by sampling from the whole training set with probabilities. </p> <p>At the beginning of running the algorithm, the probabilities are uniform. After a classifier is trained and tested, the probabilities of each successfully classified instances are decreased. Then, all the probabilities are normalized after adjustment. The next classifier is trained using dataset sampled with the adjusted probabilities. </p> <p>reference: <a href="https://mitpress.mit.edu/books/machine-learning" rel="nofollow noreferrer">Ethem Alpaydin: Machine Learning</a></p>
https://datascience.stackexchange.com/questions/61333/ensemble-techniques-boosting
Question: <p>I have a classification problem. In gradient tree boosting I read that-<br> 1. Initially a weak learner is fitted on the entire training dataset.<br> 2. Output of each training row is obtained. In my case it will be {0,1}. 3. Now, the second classifier will train on the residual of the prediction i.e {initial prediction - final prediction}.<br> My doubt is it seems very odd to calculate the residual in case of classification problems while it is ok when I look at residual calculation in case of mse.<br> So, what is actually happening in case of categorical target variable. How is the residual being calculated and which loss function is that fitted into?</p> <p>Thanks in advance.</p> Answer: <p>My layman's understanding is that binary classification is usually calculated using the <em>logit</em> transform.</p> <p>I believe then that the residuals are the difference between the response and the predicted probabilities and the default metric for this application is the Area-Under-Curve (AUC).</p>
https://datascience.stackexchange.com/questions/32952/gradient-tree-boosting
Question: <p>In your algorithms, when you use Gradient Boosting, do you prefer RandomSearchCV or GridSearchCV in order to optimize your hyperparameters ?</p> <p>Thanks for sharing your experience.</p> Answer: <p>I think it depends on the size of your multi dimensional grid. If it is small, then you can afford to be exhaustive and do a grid search. But if it is very large, and your computation time for a grid search extends too much, then definitely go to a random search. In fact, with random search one can explore larger regions than with grid search, and that is an advantage.</p> <p>In any case, for hyperparameters search there are two keys: </p> <ol> <li>Monitor it while it is running, so that you can stop it when you are happy with the results. This is specially important for random search.</li> <li>Split your data in three, train, cross validation and test. Evaluate the hyperparameter search in the cv set. Once finished, rank them by their performance there, and then take the best point and re-evaluate in test. It may happen that you do what is called "overfitting to cv set", in which case the performance in test set will deteriorate significantly vs the performance in cv set. If that happens, try with the second best, third best etc until the performance in test set is good. But take into account that the more points you take from the ranking, the higher the chance of "overfitting to test set".</li> </ol> <p>Once you find the best regions, you can do either perform a more constrained there with either grid search or random search again.</p> <p>Another option, which tends to work very well, is <strong>bayesian optimisation</strong>. Here the library that you use is important. In Python, after trying several which gave different problems, the best I found was skopt: <a href="https://scikit-optimize.github.io/" rel="nofollow noreferrer">https://scikit-optimize.github.io/</a></p>
https://datascience.stackexchange.com/questions/46120/gradient-boosting-randomsearchcv-or-gridsearchcv
Question: <p>Can someone exactly tell me how does boosting as implemented by LightGBM or XGBoost work in real case scenerio. Like I know it splits tree leaf wise instead of level wise, which will contribute to global average not just the loss of branch which will help it learn lower error rate faster than level wise tree.</p> <p>But I cannot understand completely until I see some real example, I have tried to look at so many articles and videos but everywhere it's theoretical. If someone can share some smal working example or any article that would be really helpful.</p> <p>Thank you so much.</p> Answer: <p>I think what you actually ask is &quot;how does boosting work&quot;. LightGBM or XGBoost are implementations of boosting algorithms.</p> <p>I like the article by Bühlmann and Hothorn. They provide a very good overview of boosting options.</p> <blockquote> <p>P. Bühlmann, T. Hothorn (2007), &quot;<a href="https://arxiv.org/pdf/0804.2752.pdf" rel="nofollow noreferrer">Boosting Algorithms: Regularization, Prediction and Model Fitting</a>&quot;, Statistical Science 22(4), p. 477-505.</p> </blockquote> <p>In essence, you try to repeatetly &quot;explain&quot; the residual error when you do boosting. When you do so, you come closer to a solution little by little, even in case each single attempt to explain the residual is &quot;weak&quot;.</p> <p>You may also have the benefit, that by repeatetly trying to explain the residual, boosting may discover interesting aspects in the data (you kind of try to learn slow). This works well with <em>tree-based</em> models and with some random element (&quot;stochastic&quot; gradient boosting), e.g. by leaving out some explanatory variables or parts of the rows in the train set.</p> <p>Here you also have kind of a similarity to random forests, where &quot;bagging&quot; and randomization is key. In tree-based boosting, &quot;shallow&quot; decision trees are grown (usually with &quot;only&quot; four to eight splits or so) to repeatetly explain the residual and to achieve a good fit to some data.</p> <p>I implemented &quot;linear&quot; boosting from the paper linked above (from Section 3.3 p. 483, Bühlman/Horthon) in R, <a href="https://github.com/Bixi81/R-ml/blob/master/l2_boosting.R" rel="nofollow noreferrer">you can find the code here</a>.</p> <p>The main steps are (repeatedly):</p> <ul> <li>Get the residual from the current estimator</li> <li>Fit the residual and predict</li> <li>Update the loss</li> </ul> <p>You may try to replace the linear model in the &quot;fit&quot; part in the code below by a shallow tree and see what happens.</p> <hr /> <pre><code># Boosting (p. 483, Sec. 3.3, L2-Boosting) for (n in seq(1:maxiter)){ # I) Get residual if(n==1){f=f0} # initialize in first step u=y-f # get residual from estimation # II) Fit residual / predict, I use ridge (alpha=0) reg = glmnet(x,u,alpha=0, lambda=2) g = predict(reg, newx=x, type=&quot;link&quot;) # III) Update f f=f+nu*g # Print feedback cat(paste0(&quot;Step: &quot;, n,&quot; SSR: &quot;, sum(u^2), &quot;\n&quot; )) # Save SSR/iter to list ssrlist[[n]] &lt;- sum(u^2) bstep[[n]] &lt;- n # Early stopping rule if(sum(u^2)&lt;es){break} } </code></pre>
https://datascience.stackexchange.com/questions/106267/example-for-boosting
Question: <p>Since boosting is sequential, does that mean we cannot use multi-processing or multi-threading to speed it up? If my computer has multiple CPU cores, is there anyway to utilized these extra resources in boosting?</p> Answer: <p>You can estimate in parallel each of the weak learners. For example, searching for optimal splits in 'weak' decision trees can be streamlined by utilizing large number of cores.</p>
https://datascience.stackexchange.com/questions/44123/can-parallel-computing-be-utilized-for-boosting
Question: <p>I have been working on ensemble learning and I came across this doubt that unlike other ensemble learning algorithms like voting classifier a can we only use one classifier with boosting.</p> Answer: <p>Boosting typically only use one algorithm as it's base learner (almost exclusively decision trees). However, you could use a mixed set of algorithms as your base learners.</p> <p>Something like this:</p> <pre><code>Boosting round 0: Add decision tree Boosting round 1: Add neural network Boosting round 2: Add KNN Boosting round 3: Add decision tree ... </code></pre> <p>The reason you only see boosting using the same algorithm is probably just because it works better. I speculate that the diversity that comes from using several algorithms shine more when they are trained in parallel and combined. In boosting the base learners are trained in a sequence.</p>
https://datascience.stackexchange.com/questions/56098/can-we-use-boosting-algorithms-like-adaboost-and-gradient-boosting-with-only-one
Question: <p>I have some questions I don't really understand regarding the Gradient Boosting algorithm with Decision Trees:</p> <ul> <li><p>Does the initial value matter as <span class="math-container">$\hat{y}$</span> or could you pick any, f.e between 0 and 1?</p> </li> <li><p>Why do we fit the tree to the pseudo-residuals? What's the benefit of fitting trees to the pseudo-residuals instead of the target classes?</p> </li> </ul> Answer: <ol> <li><p>The initial prediction value <span class="math-container">$\hat{y}^{(0)}$</span> does not matter for gradient boosting. Typically it is set to the mean of the target variable for regression or the log odds of the class probabilities for classification. But any reasonable constant value works fine as the starting point. The key is that subsequent trees fit to the residuals will update and improve on this initial prediction. It may affect the algorithm's convergence time if a terrible initial value is selected.</p> </li> <li><p>We fit trees to the pseudo-residuals rather than the target classes because this allows each tree to focus on correcting the errors from the model ensemble so far. The pseudo-residuals represent the gap between the current model predictions and the true target. So fitting a tree to predict these residuals lets the tree specialize in hard examples that current trees are getting wrong. This complementary specialization of trees to focus on residuals is what makes gradient boosting so effective. Trees fit on residuals reduce bias while trees fit directly on the target may overfit and increase variance.</p> </li> </ol> <p>I highly recommend checking the <a href="https://www.youtube.com/watch?v=3CC4N4z3GJc" rel="nofollow noreferrer">following</a> videos from the StatQuest channel that clearly explain the boosting algorithms.</p> <p><strong>EDIT</strong>: Explaining the following statement</p> <blockquote> <p>Trees fit on residuals reduce bias while trees fit directly on the target may overfit and increase variance.</p> </blockquote> <p>When we fit decision trees directly to the target variable (e.g. directly predicting home prices), they can overfit the training data quite easily. A single tree is already a complex high-variance model, and fitting it directly to noisy targets often results in overspecializing to noise and outliers.</p> <p>This overfitting increases variance without necessarily reducing bias. So we end up with a very complex, wiggly model that fails to generalize.</p> <p>However, when we fit trees to model the residuals, we change the objective. Instead of memorizing the noisy targets, the tree is focused on explaining the current model's errors. The residuals represent our model's bias - examples it is consistently getting wrong.</p> <p>By having trees correct these residuals, we reduce bias while limiting variance growth because the trees cannot overfit relative to what came before them. The residual-fitting forces the trees to focus on systematic errors rather than noise.</p> <p>The ensembling smooths out variance over many trees, leaving us with a strong bias reduction that generalizes much better. This is why GBDTs beat random forests despite both using trees - the residual-focused learning prevents overfitting.</p>
https://datascience.stackexchange.com/questions/126108/gradient-boosting-why-pseudo-residuals
Question: <p>i am testing gradient boosting regressor from sklearn for time series prediction on noisy data (currency markets). </p> <p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html</a></p> <p>surprisingly, the the gradient boosting regressor achieves very high accuracy on the training data - surprising because the data is so noisy. however, it performs poorly on the test set. </p> <p>this is clearly a case of overfitting, so i'm wondering what parameters i can change to regularize the gradient boosting regressor. </p> <p>so far i've tried max_depth, reducing it to 1 (from the default of 3). this seems to work pretty well in increasing accuracy on the validation set. </p> <p>does anyone know what other parameters i could tweak, to improve performance on the validation/test set? thanks</p> Answer: <p>The hyper parameters that you could tune in any boosting technique are:</p> <ol> <li><p>Depth of each tree: As you rightly pointed out this is very important because each tree in boosting technique learns from the errors of the previous trees. Hence underfitting the initial trees ensure that the later trees learn actual patterns and not noise.</p></li> <li><p>Number of trees: this is kind of intuitive from previous point as the number of trees increase the learnable signal decreases and hence the ideal number of trees is more than underfitting trees and less than overfitted trees.</p></li> <li><p>Learning rate: this parameter gives weights to previous trees according to a value between 0 and 1. Lower learning rates give lesser importance to previous trees. Higher weights lead to faster steps towards optimization. Lower weights typically lead to global optimum. But lower learning rates need more trees to learn the function.</p></li> </ol> <p>4.Sub sample: if the value is less than 1 a subset of variables is used to build the tree making it robust and learn signal from more variables. This variable reduces overfitting by not fitting only 1 variable but a group of variables.</p> <p>These variables if tuned correctly are sufficient to reduce overfitting.</p>
https://datascience.stackexchange.com/questions/63313/best-way-to-regularize-gradient-boosting-regressor
Question: <p>I have a conceptual question. My understanding is, that Random Forest can be applied even when features are (highly) correlated. This is because with bagging, the influence of few highly correlated features is moderated, since each feature only occurs in <em>some</em> of the trees which are finally used to build the overall model. </p> <p>My question: With boosting, usually even smaller trees (basically "stunps") are used. Is it a problem to have many (highly) correlated features in a bagging approach? </p> Answer: <p>Actually, your understanding of a random forest is not 100 percent correct. Variables are sampled per split, not by tree. So every tree has access to all variables.</p> <p>In general, tree based models are not too strongly affected by highly correlated features. There are no numeric stability issues as with least squares. You can easily add a variable twice without numeric problem. Note however that most <em>interpretability</em> tools like split importance or partial dependence plots <em>are</em> affected by multicollinearity. So be careful with them in such cases.</p>
https://datascience.stackexchange.com/questions/71410/boosting-with-highly-correlated-features
Question: <p>Can anyone explain me the basic difference between bagging and boosting and which technique can be used in which scenario?</p> Answer: <p><strong>Bagging</strong>: Also known as Bootstrap Aggregation is an ensemble method. First, we create random samples of the training data set (sub sets of training data set). Then, we build a classifier for each sample. Finally, results of these multiple classifiers are combined using average or majority voting. Bagging helps to reduce the variance error.</p> <p><strong>Boosting</strong> provides sequential learning of the predictors. The first predictor is learned on the whole data set, while the following are learnt on the training set based on the performance of the previous one. It starts by classifying original data set and giving equal weights to each observation. If classes are predicted incorrectly using the first learner, then it gives higher weight to the missed classified observation. Being an iterative process, it continues to add classifier learner until a limit is reached in the number of models or accuracy. Boosting has shown better predictive accuracy than bagging, but it also tends to over-fit the training data as well. </p> <p>Algorithms work on these techniques </p> <p>Bagging: Random Forest</p> <p>Boosting : Ada Boost, Gradient Boosting, XGBoosting, etc</p>
https://datascience.stackexchange.com/questions/39577/difference-between-bagging-and-boosting