{'fraction_non_alphanumeric': 0.040639024203137586, 'fraction_numerical': 0.00974262590617928, 'mean_word_length': 4.439495097016482, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 1, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Hierarchical Clustering with Structural Constraints

Hierarchical clustering is a popular unsupervised data analysis method. For many real-world applications, we would like to exploit prior information about the data that imposes constraints on the clustering hierarchy, and is not captured by the set of features available to the algorithm. This gives rise to the problem of"hierarchical clustering with structural constraints". Structural constraints pose major challenges for bottom-up approaches like average/single linkage and even though they can be naturally incorporated into top-down divisive algorithms, no formal guarantees exist on the quality of their output. In this paper, we provide provable approximation guarantees for two simple top-down algorithms, using a recently introduced optimization viewpoint of hierarchical clustering with pairwise similarity information [Dasgupta, 2016]. We show how to find good solutions even in the presence of conflicting prior information, by formulating a constraint-based regularization of the objective. We further explore a variation of this objective for dissimilarity information [Cohen-Addad et al., 2018] and improve upon current techniques. Finally, we demonstrate our approach on a real dataset for the taxonomy application.


Introduction
Hierarchical clustering (HC) is a widely used data analysis tool, ubiquitous in information retrieval, data mining, and machine learning (see a survey by Berkhin [2006]). This clustering technique represents a given dataset as a binary tree; each leaf represents an individual data point and each internal node represents a cluster on the leaves of its descendants. HC has become the most popular method for gene expression data analysis Eisen et al. [1998], and also has been used in the analysis of social networks Leskovec et al. [2014], Mann et al. [2008], bioinformatics Diez et al. [2015], image and text classification Steinbach et al. [2000], and even in analysis of financial markets Tumminello et al. [2010]. It is attractive because it provides richer information at all levels of granularity simultaneously, compared to more traditional flat clustering approaches like k-means or k-median.
Recently, Dasgupta [2016] formulated HC as a combinatorial optimization problem, giving a principled way to compare the performance of different HC algorithms. This optimization viewpoint has since received a lot of attention Roy and Pokutta [2016], Charikar and Chatziafratis [2017], Cohen-Addad et al. [2017], Moseley and Wang [2017], Cohen-Addad et al. [2018] that has led not only to the development of new algorithms but also to theoretical justifications for the observed success of popular HC algorithms (e.g. average-linkage).
However, in real applications of clustering, the user often has background knowledge about the data that may not be captured by the input to the clustering algorithm. There is a rich body of work on constrained (flat) clustering formulations that take into account such user input in the form of "cannot link" and "must link" constraints Wagstaff and Cardie [2000], Wagstaff et al. [2001], Bilenko et al. [2004], Rangapuram and Hein [2012]. Very recently, "semi-supervised" versions of HC that incorporate additional constraints have been studied Vikram and Dasgupta [2016], where the natural form of such constraints is triplet (or "must link before") constraints ab|c 1 : these require that valid solutions contain a sub-cluster with a, b together and c previously separated from them. 2 Such triplet constraints, as we formally show later, can encode more general structural constraints in the form of rooted subtrees. Surprisingly, such simple triplet constraints already pose significant challenges for bottom-up linkage methods. (Figure 1). Figure 1: (Left) Example of a triplet constraint uv|w and more general rooted tree constraints on 4 points u, v, w, z. (Right) Example with only two constraints ab|c, a b |c demonstrating that popular distance-based linkage algorithms may fail to produce valid HC. Here they get stuck after 3 merging steps (green edges).
Our work is motivated by applying the optimization lens to study the interaction of hierarchical clustering algorithms with structural constraints. Constraints can be fairly naturally incorporated into top-down (i.e. divisive) algorithms for hierarchical clustering; but can we establish guarantees on the quality of the solution they produce? Another issue is that incorporating constraints from multiple experts may lead to a conflicting set of constraints; can the optimization viewpoint of hierarchical clustering still help us obtain good solutions even in the presence of infeasible constraints? Finally, different objective functions for HC have been studied in the literature; do algorithms designed for these objectives behave similarly in the presence of constraints? To the best of our knowledge, this is the first work to propose a unified approach for constrained HC through the lens of optimization and to give provable approximation guarantees for a collection of fast and simple top-down algorithms that have been used for unconstrained HC in practice (e.g. community detection in social networks Mann et al. [2008]).
Background on Optimization View of HC. Dasgupta [2016] introduced a natural optimization framework for HC. Given a weighted graph G(V, E, w) and pairwise similarities w ij ≥ 0 between the n data points i, j ∈ V , the goal is to find a hierarchical tree T * such that where T ij is the subtree rooted at the lowest common ancestor of i, j in T and |T ij | is the number 1 Hierarchies on data imply that all datapoints are linked at the highest level and all are separated at the lowest level, hence "cannot link" and "must link" constraints are not directly meaningful.
2 For a concrete example from taxonomy of species, a triplet constraint may look like (Tuna, Salmon|Lion).
of leaves it contains. 3 We denote (1) as similarity-HC. For applications where the geometry of the data is given by dissimilarities, again denoted by {w ij } (i,j)∈E , Cohen-Addad et al. [2018] proposed an analogous approach, where the goal is to find a hierarchical tree T * such that We denote (2) as dissimilarity-HC. A comprehensive list of desirable properties of the aformentioned objectives can be found in Dasgupta [2016], Cohen-Addad et al. [2018]. In particular, if there is an underlying ground-truth hierarchical structure in the data, then T * can recover the ground-truth. Also, both objectives are NP-hard to optimize, so the focus is on approximation algorithms.
Our Results. i) We design algorithms that take into account both the geometry of the data, in the form of similarities, and the structural constraints imposed by the users. Our algorithms emerge as the natural extensions of Dasgupta's original recursive sparsest cut algorithm and the recursive balanced cut suggested in Charikar and Chatziafratis [2017]. We generalize previous analyses to handle constraints and we prove an O(kα n )-approximation guarantee 4 , thus surprisingly matching the best approximation guarantee of the unconstrained HC problem for constantly many constraints.
ii) In the case of infeasible constraints, we extend the similarity-HC optimization framework, and we measure the quality of a possible tree T by a constraint-based regularized objective. The regularization naturally favors solutions with as few constraint violations as possible and as far down the tree as possible (similar to the motivation behind similarity-HC objective). For this problem, we provide a top-down O(kα n )-approximation algorithm by drawing an interesting connection to an instance of the hypergraph sparsest cut problem.
iii) We then change gears and study the dissimilarity-HC objective. Surprisingly, we show that known top-down techniques do not cope well with constraints, drawing a contrast with the situation for similarity-HC. Specifically, the (locally) densest cut heuristic performs poorly even if there is only one triplet constraint, blowing up its approximation factor to O(n). Moreover, we improve upon the state-of-the-art in Cohen-Addad et al. [2018], by showing a simple randomized partitioning is a 2 3 -approximation algorithm. We also give a deterministic local-search algorithm with the same worst-case guarantee. Furthermore, we show that our randomized algorithm is robust under constraints, mainly because of its "exploration" behavior. In fact, besides the number of constraints, we propose an inherent notion of dependency measure among constraints to capture this behavior quantitatively. This helps us not only to explain why "non-exploring" algorithms may perform poorly, but also gives tight guarantees for our randomized algorithm.
Experimental Results. We run experiments on the Zoo dataset [Lichman, 2013] to demonstrate our approach and the performance of our algorithms for a taxonomy application. We consider a setup where there is a ground-truth tree and extra information regarding this tree is provided for the algorithm in the form of triplet constraints. The upshot is we believe specific variations of our algorithms can exploit this information; In this practical application, our algorithms have around %9 imrpvements in the objective compared to the naive recursive sparsest cut proposed in Dasgupta [2016] that does not use this information. See Appendix B for more details on the setup and precise conclusions of our experiments.
3 Observe that in HC, all edges get cut eventually. Therefore it is better to postpone cutting "heavy" edges to when the clusters become small, i.e .as far down the tree as possible.
4 For n data points, αn = O( √ log n) is the best approximation factor for the sparsest cut and k is the number of constraints.
Constrained HC work-flow in Practice. Throughout this paper, we develop different tools to handle user-defined structural constraints for hierarchical clustering. Here we describe a recipe on how to use our framework in practice.
(1) Preprocessing constraints to form triplets. User-defined structural constraints as rooted binary subtrees are convenient for the user and hence for the usability of our algorithm. The following proposition (whose proof is in the supplement) allows us to focus on studying HC with just triplet constraints.
Proposition 1. Given constraints as a rooted binary subtree T on k data points (k ≥ 3), there is linear time algorithm that returns an equivalent set of at most k triplet constraints.
(2) Detecting feasibility. The next step is to see if the set of triplet constraints is consistent, i.e. whether there exists a HC satisfying all the constraints. For this, we use a simple linear time algorithm called BUILD Aho et al. [1981].
(3) Hard constraints vs. regularization. BUILD can create a hierarchical decomposition that satisfies triplet constraints, but ignores the geometry of the data, whereas our goal here is to consider both simultaneously. Moreover, in the case that the constraints are infeasible, we aim to output a clustering that minimizes the cost of violating constraints combined with the cost of the clustering itself.
• Feasible instance: to output a feasible HC, we propose using Constrained Recursive Sparsest Cut (CRSC) or Constrained Recursive Balanced Cut (CRBC): two simple top-down algorithms which are natural adaptations of recursive sparsest cut [Mann et al., 2008, Dasgupta, 2016 or recursive balanced cut Charikar and Chatziafratis [2017] to respect constraints (Section 2).
• Infeasible instance: in this case, we turn our attention to a regularized version of HC, where the cost of violating constraints is added to the tree cost. We then propose an adaptation of CRSC, namely Hypergraph Recursive Sparsest Cut (HRSC) for the regularized problem (Section 3).
Real-world application example. In phylogenetics, which is the study of the evolutionary history and relationships among species, an end-user usually has access to whole genomes data of a group of organisms. There are established methods in phylogeny to infer similarity scores between pairs of datapoints, which give the user the similarity weights w ij . Often the user also has access to rare structural footprints of a common ancestry tree (e.g. through gene rearrangement data, gene inversions/transpositions etc., see Patané et al. [2018]). These rare, yet informative, footprints play the role of the structural constraints. The user can follow our pre-processing step to get triplet constraints from the given rare footprints, and then use Aho's BUILD algorithm to choose between regularized or hard version of the HC problem. The above illustrates how to use our workflow and why using our algorithms facilitates HC when expert domain knowledge is available.
Further related work. Similar to Vikram and Dasgupta [2016], constraints in the form of triplet queries have been used in an (adaptive) active learning framework by Tamuz et al. [2011], Emamjomeh-Zadeh andKempe [2018], showing that approximately O(n log n) triplet queries are enough to learn an underlying HC. Other forms of user interaction in order to improve the quality of the produced clusterings have been used in , Awasthi et al. [2014] where they prove that interactive feedback in the form of cluster split/merge requests can lead to significant improvements. Robust algorithms for HC in the presence of noise were studied in  and a variety of sufficient conditions on the similarity function that would allow linkage-style methods to produce good clusters was explored in . On a different setting, the notion of triplets has been used as a measure of distance between hierarchical decomposition trees on the same data points Brodal et al. [2013]. More technically distant analogs of how to use relations among triplets points have recently been proposed in Kleindessner and von Luxburg [2017] for defining kernel functions corresponding to high-dimensional embeddings.

Constrained Sparsest (Balanced) Cut
Given an instance of the constrained hierarchical clustering, our proposed CRSC algorithm uses a blackbox α n -approximation algorithm for the sparsest cut problem (the best-known approximation factor for this problem is O( √ log n) due to Arora et al. [2009]). Moreover, it also maintains the feasibility of the solution in a top-down approach by recursive partitioning of what we call the supergraph G . Informally speaking, the supergraph is a simple data structure to track the progress of the algorithm and the resolved constraints.
More formally, for every constraint ab|c we merge the nodes a and b into a supernode {a, b} while maintaining the edges in G (now connecting to their corresponding supernodes). Note that G may have parallel edges, but this can easily be handled by grouping edges together and replacing them with the sum of their weights. We repeatedly continue this merging procedure until there are no more constraints. Observe that any feasible solution needs to start splitting the original graph G by using a cut that is also present in G . When cutting the graph G = (G 1 , G 2 ), if a constraint ab|c is resolved, 5 then we can safely unpack the supernode {a, b} into two nodes again (unless there is another constraint ab|c in which case we should keep the supernode). By continuing and recursively finding approximate sparsest cuts on the supergraph G 1 and G 2 , we can find a feasible hierarchical decomposition of G respecting all triplet constraints. Next, we show the approximation guarantees for our algorithm.
Algorithm 1 CRSC 1: Given G and the triplet constraints ab|c, run BUILD to create the supergraph G . 2: Use a blackbox access to an α n -approximation oracle for the sparsest cut problem, i.e. arg min S⊆V w G (S,S) |S|·|S| . 3: Given the output cut (S,S), separate the graph G into two pieces G 1 (S, E 1 ) and G 2 (V \ S, E 2 ). 4: Recursively compute a HC T 1 for G 1 using only G 1 's active constraints. Similarly compute T 2 for G 2 . 5: Output T = (T 1 , T 2 ).
Analysis of CRSC Algorithm. The main result of this section is the following theorem: Theorem 1. Given a weighted graph G(V, E, w) with k triplet constraints ab|c for a, b, c ∈ V , the CRSC algorithm outputs a HC respecting all triplet constraints and achieves an O(kα n )-approximation for the HC-similarity objective as in (1).
Notations and Definitions. We slightly abuse notation by having OPT denote the optimum hierarchical decomposition or its optimum value as measured by (1). Similarly for CRSC. For t ∈ [n], OPT(t) denotes the maximal clusters in OPT of size at most t. Note that OPT(t) induces a partitioning of V . We use OPT(t) to denote edges cut by OPT(t) (i.e. edges with endpoints in different clusters in OPT(t)) or their total weight; the meaning will be clear from context. For convenience, we define otherwise ab|c is resolved and can be discarded.

Overview of the Analysis.
There are three main ingredients: The first is to view a HC of n datapoints as a collection of partitions, one for each level t = n − 1, . . . , 1, as in [Charikar and Chatziafratis, 2017]. For a level t, the partition consists of maximal clusters of size at most t. The total cost incurred by OPT is then a combination of costs incurred at each level of this partition. This is useful for comparing our CRSC cost with OPT. The second idea is in handling constraints and it is the main obstacle where previous analyses Charikar and Chatziafratis [2017], Cohen-Addad et al.
[2018] break down: constraints inevitably limit the possible cuts that are feasible at any level, and since the set of active constraints 6 differ for CRSC and OPT, a direct comparison between them is impossible. If we have no constraints, we can charge the cost of partitioning a cluster A to lower levels of the OPT decomposition. However, when we have triplet constraints, the partition induced by the lower levels of OPT in a cluster A will not be feasible in general ( Figure 2). The natural way to overcome this obstacle is merging pieces of this partition so as to respect constraints and using higher levels of OPT, but it still may be impossible to compare CRSC with OPT if all pieces are merged. We overcome this difficulty by an indirect comparison between the CRSC cost and lower levels r 6k A of OPT, where k A is the number of active constraints in A. Finally, after a cluster-by-cluster analysis bounding the CRSC cost for each cluster, we exploit disjointness of clusters of the same level in the CRSC partition allowing us to combine their costs.
Proof of Theorem 1. We start by borrowing the following facts from [Charikar and Chatziafratis, 2017], modified slightly for the purpose of our analysis (proofs are provided in the supplementary materials).
Fact 1 (Decomposition of OPT). The total cost paid by OPT can be decomposed into costs of the different levels in the OPT partition, i.e. OPT = n t=0 w(OPT(t)). Fact 2 (OPT at scaled levels). Let k ≤ n 6 be the number of constraints. Then, OPT ≥ 1 6k · n t=0 w(OPT( t 6k )).

Figure 2:
The main obstacle in the constrained HC problem is that our algorithm has different active constraints compared to OPT. Both ab|c, de|f constraints are resolved by the cut OPT(t).
Given the above facts, we look at any cluster A of size r produced by the algorithm. Here is the main technical lemma that allows us to bound the cost of CRSC for partitioning A.
Let the size r ≥ 6k and let l = 6k A , where k A denotes the number of active constraints for A. Then: Even though all m cuts are allowed for OPT, for CRSC some of them are forbidden: for example, in Figure 2, the constraints ab|c, de|f render 4 out of the 6 cuts infeasible. But how many of them can become infeasible with k A active constraints? Since every constraint is involved in at most 2 cuts, we may have at most To cut A, we use an α n -approximation of sparsest cut, whose sparsity is upper bounded by any feasible cut: where for the last inequality we used the standard fact that min i We also have the following series of inequalities: where the first inequality holds because we double count some (potentially all) edges of OPT( r l )∩A (these are the edges cut by OPT( r l ) that are also present in cluster A, i.e. they have both endpoints in A) and the second inequality holds because Finally, we are ready to prove the lemma by combining the above inequalities ( r−s r ≤ 1): It is clear that we exploited the charging to lower levels of OPT, since otherwise if all pieces in A were merged, the denominator with the |A i |'s would become 0. The next lemma lets us combine the costs incurred by CRSC for different clusters A (proof is in the supplementary materials) Lemma 2 (Combining the costs of clusters in CRSC). The total CRSC cost for partitioning all A:|A|<6k Combining Fact 2 and Lemma 2 finishes the proof.
Remark 1. In the supplementary material, we prove how one can use balanced cut, i.e. finding a cut S such that arg min instead of sparsest cut, and using approximation algorithms for this problem achieves the same approximation factor as in Theorem 1, but with better running time.
Remark 2. Optimality of the CRSC algorithm: Note that complexity theoretic lower-bounds for the unconstrained version of HC from Charikar and Chatziafratis [2017] also apply to our setting; more specifically, they show that no constant factor approximation exists for HC assuming the Small-Set Expansion Hypothesis.
Theorem 2 (The divisive algorithm using balanced cut). Given a weighted graph G(V, E, w) with k triplet constraints ab|c for a, b, c ∈ V , the constrained recursive balanced cut algorithm CRBC (same as CRSC, but using balanced cut instead of sparsest cut) outputs a HC respecting all triplet constraints and achieves an O(kα n )-approximation for Dasgupta's HC objective. Moreover, the running time is almost linear time.

Constraints and Regularization
Previously, we assumed that constraints were feasible. However, in many practical applications, users/experts may disagree, hence our algorithm may receive conflicting constraints as input. Here we want to explore how to still output a satisfying HC that is a good in terms of objective (1) (similarity-HC) and also respects the constraints as much as possible. To this end, we propose a regularized version of Dasgupta's objective, where the regularizer measures quantitatively the degree by which constraints get violated. Informally, the idea is to penalize a constraint more if it is violated at top levels of the decomposition compared to lower levels. We also allow having different violation weights for different constraints (potentially depending on the expertise of the users providing the constraints). More concretely, inspired by the Dasgupta's original objective function, we consider the following optimization problem: where T is the set of all possible binary HC trees for the given data points, K is the set of the k triplet constraints, T ab is the size of the subtree rooted at the least common ancestor of a, b, and c ab|c is defined as the base cost of violating triplet constraint ab|c. Note that the regularization parameter λ ≥ 0 allows us to interpolate between satisfying the constraints or respecting the geometry of the data.
Hypergraph Recursive Sparsest Cut In order to design approximation algorithms for the regularized objective, we draw an interesting connection to a different problem, which we call 3-Hypergraph Hierarchical Clustering (3HHC). An instance of this problem consists of a hypergraph G H = (V, E, E H ) with edges E, and hyperedges of size 3, E H , together with similarity weights for edges, {w ij } (i,j)∈E , and similarity weights for 3-hyperedges, 7 {w ij|k } (i,j,k)∈E H . We now think of HC on the hypergraph G H , where for every binary tree T we define the cost to be the natural extension of Dasgupta's objective: where w T ijk is either equal to w ij|k , w jk|i or w ki|j , and T ijk is either the subtree rooted at LCA(i, j), 8 LCA(i, k) or LCA(k, j), all depending on how T cuts the 3-hyperedge {i, j, k}. The goal is to find a hierarchical clustering of this hypergraph, so as to minimize the cost (5) of the tree.
Reduction from Regularization to 3HHC. Given an instance of HC with constraints (with their costs of violations) and a parameter λ, we create a hypergraph G H so that the total cost of any binary clustering tree in the 3HHC problem (5) corresponds to the regularized objective of the same tree as in (4). G H has exactly the same set of vertices, (normal) edges and (normal) edge weights as in the original instance of the HC problem. Moreover, for every constraint ab|c (with cost c ab|c ) it has a hyperedge {a, b, c}, to which we assign three weights w ab|c = 0, w ac|b = w bc|a = λ · c ab|c . Therefore, we ensure that any divisive algorithm for the 3HHC problem avoids the cost |T abc |·λ·c ab|c only if it chops {a, b, c} into {a, b} and {c} at some level, which matches the regularized objective.
Reduction from 3HHC to Hypergraph Sparsest Cut. A natural generalization of the sparsest cut problem for our hypergraphs, which we call Hyper Sparsest Cut (HSC), is the following problem: where w(S,S) is the weight of the cut (S,S) and w S ijk is either equal to w ij|k , w jk|i or w ki|j , depending on how (S,S) chops the hyperedge {i, j, k}. Now, similar to Charikar and Chatziafratis [2017], Dasgupta [2016], we can recursively run a blackbox approximation algorithm for HSC to solve 3HHC. The main result of this section is the following technical proposition, whose proof is analogous to that of Theorem 1 (provided in the supplementary materials).
Proposition 2. Given the hypergraph G H with k hyperedges, and given access to an algorithm which is α n -approximation for HSC, the Recursive Hypergraph Sparsest Cut (R-HSC) algorithm achieves an O(kα n )-approximation.
Reduction from HSC back to Sparsest Cut. We now show how to get an α n -approximation oracle for our instance of the HSC problem by a general reduction to sparsest cut. Our reduction is simple: given a hypergraph G H and all the weights, create an instance of sparsest cut with the same vertices, (normal) edges and (normal) edge weights. Moreover, for every 3-hyperedge {a, b, c} 7 We have 3 different weights corresponding to the 3 possible ways of partitioning {i, j, k} in two parts: w ij|k , w jk|i and w ki|j . 8 LCA(i, j) denotes the lowest common ancestor of i, j ∈ T .
consider adding a triangle to the graph, i.e. three weighted edges connecting {a, b, c}, where: This construction can be seen in Figure 3. The important observation is that w ab +w ac = w bc|a , w ab + w bc = w ac|b and w bc + w ac = w ab|c , which are exactly the weights associated with the corresponding splits of the 3-hyperedge {a, b, c}. So, correctness of the reduction 9 follows as the weight of each cut is preserved between the hypergraph and the graph after adding the triangles. For a discussion on extending this gadget more generally, see the supplement.
Remark 3. Reduction to hypergraphs: we would like to emphasize the necessity of the hypergraph version in order for the reduction to work. One might think that just adding extra heavy edges would be sufficient, but there is a technical difficulty with this approach. Consider a triplet constraint ab|c; once c is separated from a and b at some level, there is no extra tendency anymore to keep a and b together (i.e. only the similarity weight should play role after this point). This behavior cannot be captured by only adding heavy-weight edges. Instead, one needs to add a heavy edge between a and b that disappears once c is separated, and this is exactly why we need the hyperedge gadget. One can replace the reduction for a one-shot proof, but we believe it will be less modular and less transparent.

Variations on a Theme
In this section we study dissimilarity-HC, and we look into the problem of designing approximation algorithms for both unconstrained and constrained hierarchical clustering. In Cohen-Addad et al.
[2017], they show that average linkage is a 1 2 -approximation for this problem and they propose a topdown approach based on locally densest cut achieving a ( 2 3 − )-approximation in timeÕ n 2 (n+m) . Notably, when gets small the running time blows up.
Here, we prove that the most natural randomized algorithm for this problem, i.e. recursive random cutting, is a 2 3 -approximation with expected running time O(n log n). We further derandomize this algorithm to get a simple deterministic local-search style 2 3 -approximation algorithm. If we also have structural constraints for the dissimilarity-HC, we show that the existing approaches fail. In fact we show that they lead to an Ω(n)-approximation factor due to the lack of "exploration" (e.g. recursive densest cut). We then show that recursive random cutting is robust to adding user constraints, and indeed it preserves a constant approximation factor when there are, roughly speaking, constantly many user constraints.
Randomized 2 3 -approximation. Consider the most natural randomized algorithm for hierarchical clustering, i.e. recursively partition each cluster into two, where each point in the current cluster independently flips an unbiased coin and based on the outcome, it is put in one of the two parts.
Proof sketch. An alternative view of Dasgupta's objective is to divide the reward of the clustering tree between all possible triples {i, j, k}, where (i, j) ∈ E and k is another point (possibly equal to i or j). Now, in any hierarchical clustering tree, if at the moment right before i and j become separated the vertex k has still been in the same cluster as {i, j}, then this triple contributes w ij to the objective function. We claim this event happens with probability exactly 2 3 . To see this, consider an infinite independent sequence of coin flips for i, j, and k. Without loss of generality, condition on i's sequence to be all heads. The aforementioned event happens only if j's first tales in its sequence happens no later than k's first tales in its sequence. This happens with probability i≥1 1 2 ( 1 4 ) i−1 = 2 3 . Therefore, the algorithm gets the total reward 2n 3 (i,j)∈E w ij in expectation. Moreover, the total reward of any hierarchical clustering is upper-bounded by n (i,j)∈E w ij , which completes the proof of the 2 3 -approximation.
Remark 4. This algorithm runs in time O(n log n) in expectation, due to the fact that the binary clustering tree has expected depth O(log n) (see for example Cormen et al. [2009]) and at each level we only perform n operations.
We now derandomize the recursive random cutting algorithm using the method of conditional expectations. At every recursion, we go over the points in the current cluster one by one, and decide whether to put them in the "left" partition or "right" partition for the next recursion. Once we make a decision for a point, we fix that point and go to the next one. Roughly speaking, these local improvements can be done in polynomial time, which will result in a simple local-search style deterministic algorithm.
Theorem 4. There is a deterministic local-search style 2 3 -approximation algorithm for maximizing dissimilarity-HC objective that runs in time O(n 2 (n + m)).
Maximizing the Objective with User Constraints From a practical point of view, one can think of many settings in which the output of the hierarchical clustering algorithm should satisfy user-defined hard constraints. Now, combining the new perspective of maximizing Dasgupta's objective with this practical consideration raises a natural question: which algorithms are robust to adding user constraints, in the sense that a simple variation of these algorithms still achieve a decent approximation factor?
• Failure of "Non-exploring" Approaches. Surprisingly enough, there are convincing reasons that adapting existing algorithms for maximizing Dasgupta's objective (e.g. those proposed in Cohen-Addad et al. [2018]) to handle user constraints is either challenging or hopeless. First, bottom-up algorithms, e.g. average-linkage, fail to output a feasible outcome if they only consider each constraint separately and not all the constraints jointly (as we saw in Figure 1). Second, maybe more surprisingly, the natural extension of (locally) Recursive-Densest-Cut 10 algorithm proposed in Cohen-Addad et al. [2018] to handle user constraints performs poorly in the worst-case, even when we have only one constraint. Recursive-Densest-Cut proceeds by repeatedly picking the cut that has maximum density, i.e. arg max S⊆V w(S,S) |S|·|S| and making two clusters. To handle the user constraints, we run it recursively on the supergraph generated by the constraints, similar to the approach in Section 2. Note that once the algorithm resolves a triplet constraint, it also breaks its corresponding supernode. Now consider the following example in Figure 4, in which there is just one triplet constraint ab|c. The weight W should be thought of as large and as small. By choosing appropriate weights on the edges of the clique K n , we can fool the algorithm into cutting the dense parts in the clique, without ever resolving the ab|c constraint until it is too late. The algorithm gets a gain of O(n 3 +W ) whereas OPT gets Ω(nW ) by starting with the removal of the edge (b, c) and then removing (a, b), thus enjoying a gain of ≈ nW . Figure 4: Ω(n)-approximation lower bound instance for the constrained Recursive-Densest-Cut algorithm.
• Constrained Recursive Random Cutting. The example in Figure 4, although a bit pathological, suggests that a meaningful algorithm for this problem should explore cutting low-weight edges that might lead to resolving constraints, maybe randomly, with the hope of unlocking rewarding edges that were hidden before this exploration.
Formally, our approach is showing that the natural extension of recursive random cutting for the constrained problem, i.e. by running it on the supergraph generated by constraints and unpacking supernodes as we resolve the constraints (in a similar fashion to CSC), achieves a constant factor approximation when the constraints have bounded dependency. In the remaining of this section, we define an appropriate notion of dependency between the constraints, under the name of dependency measure and analyze the approximation factor of constrained recursive random cutting (Constrained-RRC ) based on this notion.
Suppose we are given an instance of hierarchical clustering with triplet constraints {c 1 , . . . , c k }, where c i = x i |y i z i , ∀i ∈ [k]. For any triplet constraint c i , lets call the pair {y i , z i } the base, and z i the key of the constraint. We first partition our constraints into equivalence classes C 1 , . . . , C N , where C i ⊆ {c 1 , . . . , c k }. For every i, j, the constraints c i and c j belong to the same class C if they share the same base (see Figure 5).
Definition 1 (Dependency digraph). The Dependency digraph is a directed graph with vertex set {C 1 , . . . , C L }. For every i, j, there is a directed edge C i → C j if ∃ c = x|yz, c = x |y z , such that c ∈ C i , c ∈ C j , and either {x, z} = {y , z } or {x, y} = {y , z } (see Figure 6). The dependency digraph captures how groups of constraints impact each other. Formally, the existence of the edge C i → C j implies that all the constraints in C j should be resolved before one can separate the two endpoints of the (common) base edge of the constraints in C i .
Remark 5. If the constraints {c 1 , . . . , c k } are feasible, i.e. there exists a hierarchical clustering that can respect all the constraints, the dependency digraph is clearly acyclic.
Definition 2 (Layered dependency subgraph). Given any class C, the layered dependency subgraph of C is the induced subgraph in the dependency digraph by all the classes that are reachable from C. Moreover, the vertex set of this subgraph can be partitioned into layers {I 0 , I 1 , . . . , I L }, where L is the maximum length of any directed path leaving C and I l is a subset of classes where the length of the longest path from C to each of them is exactly equal to l (see Figure 7).
We are now ready to define a crisp quantity for every dependency graph. This will later help us give a more meaningful and refined beyond-worst-case guarantee for the approximation factor of the Constrained-RRC algorithm.
Definition 3 (Dependency measure). Given any class C, the dependency measure of C is defined as where I 0 , . . . , I L are the layers of the dependency subgraph of C, as in Definition 2. Moreover, the dependency measure of a set of constraints DMC({c 1 , . . . , c k }) is defined as max C DM(C), where the maximum is taken over all the classes generated by {c 1 , . . . , c k }.
Intuitively speaking, the notion of the dependency measure quantitatively expresses how "deeply" the base of a constraint is protected by the other constraints, i.e. how many constraints need to be resolved first before the base of a particular constraint is unpacked and the Constrained-RRC algorithm can enjoy its weight. This intuition is formalized through the following theorem, whose proof is deferred to the supplementary materials.
Corollary 1. Constrained-RRC is an O(1)-approximation for maximizing dissimilarity-HC objective, given feasible constraints of constant dependency measure.

Conclusion
We studied the problem of hierarchical clustering when we have structural constraints on the feasible hierarchies. We followed the optimization viewpoint that was recently developed in Dasgupta [2016], Cohen-Addad et al. [2018] and we analyzed two natural top-down algorithms giving provable approximation guarantees. In the case where the constraints are infeasible, we proposed and analyzed a regularized version of the HC objective by using the hypergraph version of the sparsest cut problem. Finally, we also explored a variation of Dasgupta's objective and improved upon previous techniques, both in the unconstrained and in the constrained setting. Proof of Fact 2 from Charikar and Chatziafratis [2017]. We rewrite OPT using the fact that w(OPT(t)) ≥ 0 at every level t ∈ [n]: 6k · OPT = 6k n t=0 w(OPT(t)) = 6k(w(OPT(0)) + · · · + w(OPT(n))) ≥ 6k(w(OPT(0)) + · · · + w(OPT( n 6k ))) = n t=0 w(OPT( t 6k )) Proof of Lemma 2. By using the previous lemma we have: Observe that w(OPT(t)) is a decreasing function of t, since as t decreases, more and more edges are getting cut. Hence we can write: To conclude with the proof of the first part all that remains to be shown is that: To see why this is true consider the clusters A with a contribution to the LHS. We have that r A −s A +1 ≤ t ≤ r A , hence |B 2 | < t meaning that A is a minimal cluster of size |A| ≥ t > |B 2 | ≥ |B 1 |, i.e. if both A's children are of size less than t, then this cluster A contributes such a term. The set of all such A form a disjoint partition of V because of the definition for minimality (in order for them to overlap in the hierarchical clustering, one of them needs to be ancestor of the other and this cannot happen because of minimality). Since OPT( t 6k ) ∩ A for all such A forms a disjoint partition of OPT( t 6k ), the claim follows by summing up over all t. Note that so far our analysis handles clusters A with size r A ≥ 6k. However, for clusters with smaller size r A < 6k we can get away by using a crude bound for bounding the total cost and still not affecting the approximation guarantee that will be dominated by O(kα n ): Theorem 6 (The divisive algorithm using balanced cut). Given a weighted graph G(V, E, w) with k triplet constraints ab|c for a, b, c ∈ V , the constrained recursive balanced cut algorithm (same as CRSC, but using balanced cut instead of sparsest cut) outputs a HC respecting all triplet constraints and achieves an O(kα n )-approximation for the HC objective (1).
Proof. It is not hard to show that one can use access to balanced cut rather than sparsest cut and achieve the same approximation factor by the recursive balanced cut algorithm.
We will follow the same notation as in the sparsest cut analysis and we will use some of the facts and inequalities we previously proved about OPT(t). Again, for a cluster A of size r, the important observation is that the partition A 1 , . . . , A l (at the end, we will again choose l = 6k A ) induced inside the cluster A by OPT( r l ) can be separated into two groups, let's say (C 1 , C 2 ) such that r/3 ≤ |C 1 |, |C 2 | ≤ 2r/3. In other words we can demonstrate a Balanced Cut with ratio 1 3 : 2 3 for the cluster A. Since we cut fewer edges when creating C 1 , C 2 compared to the partitioning of OPT( r l ): w(C 1 , C 2 ) ≤ w(OPT( r l ) ∩ A) By the fact we used an α n -approximation to balanced cut we can get the following inequality (similarly to Lemma 1): Finally, we have to sum up over all the clusters A (now in the summation we should write r A , s A instead of just r, s, since there is dependence in A) produced by the constrained recursive balanced cut algorithm for Hierarchical Clustering and we get that we can approximate the HC objective function up to O(kα n ).
Remark 6. Using balanced-cut can be useful for two reasons. First, the runtime of sparsest and balanced cut on a graph with n nodes and m edges areÕ(m + n 1+ ). When run recursively however as in our case, taking recursive sparsest cuts might be worse off by a factor of n (in case of unbalanced splits at every step) in the worst case. However, recursive balanced cut is stillÕ(m + n 1+ ). Second, it is known that an α-approximation for the sparsest cut yields an O(α)-approximation for balanced cut, but not the other way. This gives more flexibility to the balanced cut algorithm, and there is a chance it can achieve a better approximation factor (although we don't study it further in this paper).

A.2 Missing proofs in Section 3
Proof sketch of Proposition 2. Here the main obstacle is similar to the one we handled when proving Theorem (1): for a given cluster A created by the R-HSC algorithm, different constraints are, in general, active compared to the OPT decomposition for this cluster A. Note of course, that OPT itself will not respect all constraints, but because we don't know which constraints are active for OPT, we still need to use a charging argument to low levels of OPT. Observe that here we are allowed to cut an edge ab even if we had the ab|c constraint (incurring the corresponding cost c ab|c ), however we cannot possibly hope to charge this to the OPT solution, as OPT, for all we know, may have respected this constraint. In the analysis, we crucially use a merging procedure between sub-clusters of A having active constraints between them and this allows us to compare the cost of our R-HSC with the cost of OPT .
3-hyperedges to triangles for general weights . Even though the general reduction presented in Section 3 (Figure 3) to transform a 3-hyperedge to a triangle is valid even for general instances of HSC with 3-hyperedges and arbitrary weights, the reduced sparsest cut problem may have negative weights, e.g. when w bc|a + w ac|b < w ab|c . To the best of our knowledge, sparsest cut with negative weights has not been studied. Notice however that if the original weights w bc|a , w ac|b , w ab|c satisfy the triangle inequality (or as a special case, if two of them are zero which is usually the case when we have a triplet constraints), then we can actually solve (approximately) the HSC instance, as the sparsest cut instance will only have non-negative weights.
Proof sketch of Theorem 5. Before starting to prove the theorem, we prove the following simple lemma.
Lemma 3. There is no edge between any two classes in the same layer I l .
Proof of Lemma 3. If such an edge exists, then there is a path of length l + 1 from C to a class in I l , a contradiction. Now, similar to the proof of Theorem 3, we consider every triple {x, y, z}, where (x, y) ∈ E and z is another point , but this time we only consider z's that are not involved in any triplet constraint (there are at least n − k such points). We claim with probability at least 2 3·DMC({c 1 ,...,c k }) the supernode containing z is still in the same cluster as supernodes containing x and y right before x and y gets separated. By summing over all such triples, we show that the algorithm gets a gain of at least 2(n−k) 3·DMC({c 1 ,...,c k }) (x,y)∈E w xy , which proves the α-approximation as the optimal clustering has a reward bounded by n (x,y)∈E w xy .
To prove the claim, if (x, y) is not the base of any triplet constraint then a similar argument as in the proof of Theorem 3 shows the desired probability is exactly 2 3 (with a slight adaptation, i.e. by looking at the coin sequences of supernodes containing x and y, which are going to be disjoint in this case at all iterations, and the coin sequence of z). Now suppose (x, y) is the base of any constraint c and suppose c belongs to a class C. Consider the layered dependency subgraph of C as in Definition 2 and let the layers to be I 0 , . . . , I L . In order for z to be in the same cluster as x and y when they get separated, a chain of L + 1 independent events needs to happen. These events are defined inductively; for the first event, consider the coin sequence of z, coin sequence of (the supernode containing all the bases of) constraints in ∪ L l=0 I l and coin sequences of all the keys of constraints in I L (there are C ∈I L |C | of them). Without loss of generality, suppose the coin sequence of (the supernode containing) ∪ L l=0 I l is all heads. Now the event happens only if at the time z flips its first tales all keys of I L have already flipped at least one tales. Conditioned on this event happening, all the constraints in I L will be resolved and z remains in the same cluster as x and y. Now, remove I L from the dependency subgraph and repeat the same process to define the events 2, . . . , L in a similar fashion. For the l th event to happen, we need to look at 1 + C ∈I L |C | number of i.i.d. symmetric geometric random variable, and calculate the probability that first of them is no smaller than the rest. This event happens with a probability at least 1 + C ∈I L |C | −1 . Moreover the events are independent, as there is no edge between any two classes in I l for l ∈ [L], and different classes have different keys. After these L events, the final event that needs to happen is when all the constraints are unlocked, and z needs to remain in the same cluster as x and y at the time they get separated. This event happens with probability 2 3 . Multiplying all of these probabilities due to independence implies the desired approximation factor.

B Experiments
The purpose of this section is to present the benefits of incorporating triplet constraints when performing Hierarchical Clustering. We will focus on real data using the Zoo dataset (Lichman [2013]) for a taxonomy application. We demonstrate that using our approach, the performance of simple recursive spectral clustering algorithms can be improved by approximately 9% as measured by the Dasgupta's Hierarchical Clustering cost function (1). More specifically: • The Zoo dataset: It contains 100 animals forming 7 different categories (e.g. mammals, amphibians etc.). The features of each animal are provided by a 16-dimensional vector containing information such as if the animal has hair or feathers etc.
• Evaluation method : Given the feature vectors, we can create a similarity matrix M (·, ·) indexed by the labels of the animals. We choose the widely used cosine similarity to create M .
• Algorithms: We use a simple implementation of spectral clustering based on the second eigenvector of the normalized Laplacian of M . By applying the spectral clustering algorithm once, we can create two clusters; by applying it recursively we can create a complete hierarchical decomposition, which is ultimately the output of the HC algorithm.
• Baseline comparison: Since triplet constraints are especially useful when there is noisy information (i.e. noisy features), we simulate this situation by hiding some of the features of our Zoo dataset. Specifically, when we want to find the target HC tree T * , we use the full 16-dimensional feature vectors, but for the comparison between the unconstrained and the constrained HC algorithms we will use a noisy version of the feature vectors which consists of only the first 10 coordinates from every vector.
In more detail, the first step in our experiments is to evaluate the cost of the target clustering T * . For this, we use the full feature vectors and perform repeated spectral clustering to get a hierarchical decomposition (without incorporating any constraints). We call this cost OPT.
The second step is to perform unconstrained HC but with noisy information, i.e. to run the spectral clustering algorithm repeatedly on the 10-dimensional feature vectors (again without taking into account any triplet constraints). This will output a hierarchical tree that has cost in terms of the Dasgupta's HC cost Unconstrained_Noisy_Cost. 11 The final step is to choose some structural constraints (that are valid in T * ) 12 and perform again HC with noisy information. We again use the 10-dimensional feature vectors but the spectral clustering algorithm is allowed only cuts that do not violate any of the given structural constraints. Repeating until we get a decomposition gives us the final output which will have cost in terms of the Dasgupta's HC cost Constrained_Noisy_Cost.
The first main result of our experimental evaluation is that the Constrained_Noisy_Cost is surprisingly close to OPT, even though to get the Constrained_Noisy_Cost the features used were noisy and the second main result is that incorporating the structural constraints yields ≈ 9% improvement over the noisy unconstrained version of HC with cost Unconstrained_Noisy_Cost. Now that we have presented the experimental set-up, we can proceed by describing our results and final observations in greater depth.

B.1 Experimental Results
We ran our experiments for 20, 50, 80 and 100 animals from the Zoo dataset and for the evaluation of the % improvement in terms of the Dasgupta's HC cost (1), we used the following formula: Unconstrained_Noisy_Cost − Constrained_Noisy_Cost OPT The improvements obtained due to the constrained version are presented in Table 1. Table 1: Results obtained for the Zoo dataset. The improvement corresponds to the lower cost of the output HC tree after incorporating structural constraints, even in the presence of noisy features. Observe that in all cases the performance of Constrained_Noisy_Cost is extremely close to the OPT cost.
Some observations regarding the structural constraints are the following: • When we add triplet constraints to the input as advice for the algorithm, it is crucial for the triplet constraints to actually be useful. "Easy" constraints that are readily implied by the similarity scores will have no extra use and will not lead to better solutions.
• We also observed that having "nested" constraints can be really useful. Nested constraints can guide our algorithm to perform good cuts as they refer to a larger portion of the optimum tree T * (i.e. contiguous subtrees) rather than just different unrelated subtrees of it. The usefulness of the given constraints is correlated with the depth of the nested constraints and their accordance with the optimum tree T * based on Dasgupta's objective.
• Furthermore, since most of the objective cost comes from the large initial clusters, we focused on the partitions that created large clusters and imposed triplet constraints that ensured good cuts in the beginning. Actually in some cases, just the first 3 or 4 cuts are enough to guarantee that we get ≈ 12% improvement.
• Finally, we conclude that just the number of the given triplet constraints may not constitute a good metric for their usefulness. For example, a large number of constraints referring to wildly different parts of T * , may end up being much less useful than a smaller number of constraints guiding towards a good first cut.