{'fraction_non_alphanumeric': 0.03350763438611169, 'fraction_numerical': 0.01150386948337168, 'mean_word_length': 4.3963882618510155, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Clustering with Penalty for Joint Occurrence of Objects: Computational Aspects

The method of Hol\'y, Sokol and \v{C}ern\'y (Applied Soft Computing, 2017, Vol. 60, p. 752-762) clusters objects based on their incidence in a large number of given sets. The idea is to minimize the occurrence of multiple objects from the same cluster in the same set. In the current paper, we study computational aspects of the method. First, we prove that the problem of finding the optimal clustering is NP-hard. Second, to numerically find a suitable clustering, we propose to use the genetic algorithm augmented by a renumbering procedure, a fast task-specific local search heuristic and an initial solution based on a simplified model. Third, in a simulation study, we demonstrate that our improvements of the standard genetic algorithm significantly enhance its computational performance.


Introduction
Clustering of objects is typically based on a distance between objects or a density of objects in an area. Holý et al. (2017) propose a very different approach and cluster objects based on their joint occurrence in observed sets. It is assumed that there should typically be at most one object from each cluster in a single observed set. Deviation from this behavior is considered an error and the goal is to find the clustering which minimizes this error. Specifically, Holý et al. (2017) define the error as the average ratio of clustering decisions in which two objects from the same cluster occur in the same set. The problem of finding clusters minimizing this error can be formulated as an integer nonlinear optimization problem.
The motivation for this clustering technique lies in retail analytics. Holý et al. (2017) use this method to cluster products of a retail store into categories of substitutes. In this setting, it is assumed that most customers buy at most one product (object) from each cluster in a single visit (set), i.e. two or more products (objects) from the same cluster rarely occur together in the same shopping basket (set). This is quite reasonable behavior suggesting customers choose only one product for a given purpose. In retail, there is typically a large number of products (objects) and a huge number of shopping baskets (sets) making the method computationally very intensive. The main advantage is that no characteristics of products are needed and only a history of transactions is utilized. Holý et al. (2017) show that this method can uncover meaningful clusters in an empirical study of a Czech drugstore chain. For other clustering approaches in retail business, see e.g. Jonker et al. (2004), Tsai and Chiu (2004), Reutterer et al. (2006), Zhang et al. (2007), Lingras et al. (2014), Ammar et al. (2016), Peker et al. (2017), Wu and Liu (2020), and Sokol and Holý (2020a).
In this paper, we analyze the approach of Holý et al. (2017) from a computational point of view. First, we demonstrate that the related optimization problem is NP-hard. We build our proof on the results of Karp (1972) for the Max-Cut problem. Second, we propose to numerically find clusters using the genetic algorithm combined with local search. We adjust the standard genetic algorithm by applying the renumbering procedure of Falkenauer (1998) and Hruschka and Ebecken (2003) suitable for integer representation of clusters. Note that Hruschka and Ebecken (2003) also propose crossover and mutation operations specifically adapted for the integer representation of clusters. However, these operations are based on a distance between objects and are not applicable in our case. We therefore resort to the standard versions of these operations. Such approach in the context of clustering is used e.g. by Murthy and Chowdhury (1996). We further enhance the genetic algorithm by computationally effective local search. This improvement of the genetic algorithm is in general suggested e.g. by Hamzaçebi (2008). Finally, in the initial population, we include the solution of the simplified problem obtained by the k-means method with data transformed to distances. Our modifications significantly improve the computational performance in comparison to the basic genetic algorithm utilized by Holý et al. (2017). Our numerical method falls to the field of clustering methods based on nature-inspired metaheuristics. For an overview of this field, see e.g. Hruschka et al. (2009), Nanda andPanda (2014) and José-García and Gómez-Flores (2016).
The rest of the paper is structured as follows. In Section 2, we formulate our problem of finding clusters. In Section 3, we prove that this problem is NP-hard. In Section 4, we propose to numerically solve this problem by the improved genetic algorithm. In Section 5, we investigate the computational performance of the proposed algorithm using simulated data. We conclude the paper in Section 6.

Integer Formulation
The problem is based on the following data structure. Let N be the number of sets, M the number of objects and K the maximum number of clusters. A matrix A is available with N rows, M columns and elements a ij defined as Furthermore, we assume that there are at least two objects in each set, i.e. M j=1 a ij ≥ 2 for all i ∈ {1, . . . , N }. Otherwise the set is not interesting for our goal and can be ignored.
The variables in the model are vectors of possible object clustering x = (x 1 , . . . , x M ) , where x j is an integer in range 1 ≤ x j ≤ K for every j ∈ {1, . . . , M }. We are looking for such clustering x that minimizes the weighted occurrences of pairs of objects from one cluster in the same set.
For each set i = 1, . . . , N we denote the total number of object pairs in the set D i as and the number of violating object pairs from one cluster within the same set V i as where I(·) denotes the indicator function. The cost function is then Therefore, the cost function equals to the average ratio of object pairs in which two object from the same cluster are in the same set. The range of the cost function is from 0 (there is no set containing object from the same cluster) to 1 (every set contain only objects from the same cluster).
The nonlinear integer programming problem is of form x j ∈ N for j = 1, . . . , M. (5) In practical tasks, we can assume N M K.

Binary Formulation
The model can be straightforwardly transformed from the integer program to a binary program. Let for each j and k and let Y be matrix with elements y jk . Note that in the optimization process itself, the number of variables y jk can be further reduced by M as y jK = 1 − K−1 k=1 y jk for every j = 1, . . . , M . As the number of violating object pairs is dependent on clustering Y , we define V i alternatively as Similarly to (5), we define the cost function as The non-linear binary programming model is then 3 Computational Complexity Proof. In order to prove it, we reduce problem (9) to the simplest case. Set K = 2, i.e. let there be only two clusters of objects, and let M j=1 a ij = 2 for all i, i.e. the size of all sets is 2. The number of object pairs is therefore D i = 1 in each set i. Also, as we have only two clusters, we can define z j = 1 if object j is assigned to cluster 1, 0 if object j is assigned to cluster 2, and let a ij a i for j, = 1, . . . , M, j = , which is the number of occurrences of every pair of objects in the same set. The problem can now be formulated as Without the loss of generality, we can rewrite the objective function to the maximization form as Let P denote matrix with elements P j . The decision problem (13) can be formulated as follows: Problem 1. Is there a binary vector z = {z 1 , z 2 , . . . , z M } such that for a given M, P, and C holds Therefore, an instance of the problem is given by {M, P, C}. Now, we show that the Max-Cut problem can be reduced to Problem (14). The Max-Cut is an NP-hard decision problem (see the proof of NP-hardness in Karp, 1972) defined as follows: Hence, an instance of the Max-Cut problem is given by {V G , E G , w, C}. In order to prove that the Max-Cut problem is reducible to Problem 1, we need to shown that every instance of Problem 2 is reducible to Problem 1. The reduction function is following: V G is mapped to a vector (1, 2, . . . , n) where n is the number of vertices. Values of weighting function w(j, ) are directly translated into P j . If graph G = (V G , E G ) is not complete, then P j is set to zero for missing edges. A value of C remains the same.
Remark. Note that the Max-Cut problem does not assume non-negativity weighting function w and in our setup P j are naturally non-negative as it is number of instances that two objects are in the same set; however, this is not a problem. As it is shown in reduction of the Knapsack problem to the Max-Cut problem through the Partition problem (Karp, 1972), there are two cases when the w(j, ) are negative.
1. If the sum of all items in the Knapsack form is lower than the capacity, then w(j, ) may be negative. However, such instance is trivial to solve.

If the weight of
in the Knapsack problem is negative, then w(j, ) may be negative. However, this case can be easily transformed to instance without negative weights. Such transformation consists in multiplication of negative weight w . Therefore, the cases in which w(j, ) are negative can be straightforwardly transformed to non-negative cases or are easy to solve.
As a result, every hard instance of the Max-Cut problem given by [V G , E G , w, C] can be transformed to Problem 1 using reduction function g and therefore problem (5) is NP-hard.

Genetic Algorithm
In our model, it is not possible to calculate the similarity between individual clusterings without losing important information. Hence, we cannot use standard clustering methods such as k-means, DBSCAN or hierarchical clustering methods. For this reason, an integer genetic algorithm is chosen to find a suitable clustering.
The standard genetic algorithm has the following phases. First, the initial population is generated, where by population we mean a set of different clusterings x called individuals. Objects x j assigned to clusters in clustering x are called genes. Individuals can also be inserted to population if promising candidates are available. After the initial population is prepared, in each generation following steps are conducted: 1. Designation of given number of the best individuals as elite in order to preserve them.
(a) By crossover, when two different individuals are randomly selected using roulette wheel selection and by randomly swapping genes two new individuals are created, replacing the original ones.
(b) By mutation, when randomly selected genes are randomly switched.

Evaluation of all new individuals.
4. If the specified number of generations or a sufficiently high quality result is not achieved, the algorithm returns to Step 1, else the best individual is chosen and the algorithm ends.
In order to apply the genetic algorithm, several parameters are to be chosen. The first one is the size of population. With bigger population of individuals more possible clusterings are explored, which can result in finding better solution at the cost of higher computational demands. This parameter is task-specific and in our case a large population is preferred (see Holý et al., 2017). The number of iterations, sometimes called generations in terms of evolutionary algorithms, is another parameter. Simply put, it is a parameter of how long the solution space should be searched. The number of elites parameter determines how many individuals with the best evaluation are declared elite and are passed to the next generation without any alteration. This prevents the loss of the best individuals in population. Parameter mutation chance determines the probability of changing gene value to a random one. The purpose of mutation in genetic algorithm is to introduce more diversity into population, thus to avoid reaching local minimum by preventing the individuals from becoming too similar to each other. However, if a high value is selected, then the crossover effect is suppressed and algorithm is more of a random search of the solution space.
By far the most computationally demanding part of the algorithm is evaluating newly found clusters as it is necessary to work with a matrix with large dimensions, specifically N × M .

Renumbering Procedure
There are several complications concerning the application of traditional genetic algorithms for clustering tasks. The main one is the clustering codification. In our case, the clustering x has M elements x j with values {1, . . . , K}. If the standard genetic algorithm is used, the resulting clustering x allows symmetries in the solution space, for example, assuming M = 5 and K = 3, solution x = (3, 3, 2, 1, 3) is in fact identical to x = (2, 2, 1, 3, 2) but standard genetic algorithm treats them as significantly different. This has inappropriate consequences, especially in the case of crossover. This shortcoming can be remedied by introducing a simple rule (see Falkenauer, 1998) when cluster numbers are renumbered to start from the smallest based on the first occasion of each cluster, e.g. the solution above would be renumbered to x = (1, 1, 2, 3, 1). The renumbering procedure allows the suitable application of classic genetic algorithms in clustering problems, avoiding the problems of redundant codification (see Hruschka and Ebecken, 2003).

Local Search
Second proposed improvement is the implementation of a task-specific local search. The local search function consists in generating all possible neighbor individuals for the best individual in each iteration and checking whether the new individuals improve the cost function. If newly found individual gives better result than the original one, then the original is simply replaced. If the individual has already been checked in the previous iterations, then no local search is executed as the individual cannot be improved by local search.
By far the most time-consuming part of used genetic algorithm is the frequently called enumeration of f cost (x). In the proposed procedure, we therefore try to approach enumeration efficiently by repeated usage of the intermediate calculations, similar to dynamic programming approach. The goal is to find neighbors of individual x , i.e. all possible vectors x (j,k 1 ) for all j and k 1 , which differs from x in exactly one element j which is changed from the original cluster k 0 to the new cluster k 1 . To find neighbors, it is not necessary to calculate the value of the cost function from the beginning, but to use already prepared calculations. The main idea follows from the decomposition: With the knowledge of V (x (j,k 1 ) ), the cost function f cost (x (j,k 1 ) ) can be computed quickly as the other parts of the formula remains unchanged. Let D is a vector of all D i and B is the matrix N × K of the number of objects by set and cluster. In the algorithm, the operation / stands for element-wise division and \ is a set subtraction operation. The local search function which finds all neighbors of clustering x is described in Algorithm 1. 19: x best := x 20: x The proposed method also evaluates all neighbors, i.e. M · (K − 1) clusterings, but instead of repeated calls to the cost function, intermediate calculations are used repeatedly. The enumerations of the number of object pairs from the same cluster in one set is performed for the original clustering with a complexity of the order of N · M and then is used repeatedly. In the enumeration of the change in the cost function of individual neighbors, only the parts that actually differ are calculated, this is of the order of 2·N for one neighbor since only two sums change in respect to original clustering, see (17). The total computational complexity is then . Since M is expected to be of high value, e.g. hundreds or thousands, the time saved is significant.

Initial Solution
Finally, we obtain an appropriate initial solution. We transform the data set to dissimilarity matrix Q based on the simplified relationship between objects. The elements q j of matrix Q are computed as the proportions of sets in which objects appear together in the same set: a ij a i for j, = 1, . . . , M, j = , Using the dissimilarity matrix Q, we can use the standard clustering algorithms such as k-means to find initial solution for genetic algorithm. A substantial amount of information is lost through the data transformation, nevertheless, the solution found by k-means can serve as suitable initial point. The main advantage is that k-means is a very fast method, which allows finding a suitable initial point in a matter of seconds.

Setup
In the simulation study, we compare four modifications of the genetic algorithm for clustering problems in terms of the best solution found and the speed of convergence. The modifications are as follow: (a) Standard algorithm with completely random initial population and without local search; (b) Only Local algorithm with completely random initial population but using the proposed local search function; (c) Only Init algorithm with inserted initial solution from the simplified model and without local search; (d) Local & Init algorithm with both inserted initial solution from the simplified model and using the proposed local search approach.
The main problem of the studied clustering model is the difficulty of finding the optimal solution. Even in test instances, we cannot determine the optimum with certainty. Therefore, as a benchmark we use the solution of the simplified model found by the k-means method, as described in Section 4.4 and used in Only Local and Local & Init algorithms. For parameters of the k-means method we use the Euclidean distance metric with 1000 starting locations, the maximum number of iterations to 1000 and the Hartigan-Wong's algorithm. With these parameters, the k-means solution is found almost instantly.
The following parameters from Holý et al. (2017) are used for all modifications. The population size is set to 500 individuals. Initial population is generated randomly but in the case of Only Init a Local & Init we also supply the k-means solution of the simplified model. We always use the fixed number of 500 generations even though simulations show that vast majority of instances converge faster. The elite ratio is set to 0.1. The mutation chance is set to 0.01 to allow algorithm to concentrate on improving one point while retaining some exploratory ability of mutation. Unlike the local search which is conducted only on the best individual of the generation, the mutation can take place on any non-elite individual.
The basic parameters for data generation are the number of sets N , objects M and clusters K. Sets are generated independently. For each set, it is randomly determined how many unique clusters exist in the set. In doing so, every cluster has the same probability of occurrence given by the parameter ρ. From each cluster assigned to the set, one product is assigned to the set. In the next step, based on the π parameter, other products from the same cluster are assigned into sets, thus creating situations that violate the model's assumptions.
We work with the default values N = 10000, M = 100, K = 10, ρ = 0.50 and π = 0.03 which roughly correspond to retail datasets. In the next part, we investigate the effects of changes in the values of parameters N , M , K, and π on the results of the genetic algorithm modifications.

Results
Throughout this section, we assume the parameters are set to their default value unless said otherwise -then only one parameter changes at a time. Each algorithm is run 10 times for each dataset and each dataset is generated 100 times for each scenario. Computation time is reported for 3.40 GHz CPU and the algorithm is implemented in R software. We consider the k-means solution of the simplified model from Section 4.4 as the benchmark solution. We report values of the objective function standardized to this benchmark solution (standardized objective = objective / benchmark objective).  First, we take a look at the progress of the objective function over time in Figure 1. We report the objective function over time rather than over the number of iterations as some versions of the algorithm require to compute local search in each iteration. The computation time spent on local search is, however, quite negligible. Apparently, for default values of the parameters, the Standard algorithm cannot overcome the benchmark solution. The local search improvement in the Only Local algorithm allows surpassing the benchmark solution. The Only Init and Local & Init algorithms use the benchmark solution as their initial point and both are able to quickly improve it with the Local & Init algorithm being considerably faster.
Next, we focus on differences in performance based on the changes in parameters of the data generating process and the number of clusters. The average found solutions after 500 iterations are shown in Figure 2 and Table 1. With a low number of sets N , the benchmark approach is clearly worse than the genetic algorithms. With an increasing number of sets N , the Standard algorithm results are worsening and the differences between the benchmark approach and other genetic algorithms shrink. However, the Only Init and Local & Init algorithms are still able to improve their initial solution. With an increasing number of objects M in the dataset, the benchmark solution proves to be insufficient -all tested modifications of the genetic algorithm give significantly better results. The same can be said about an increasing probability of extra objects π. Simply put, the more violations occur in the dataset, the worse is the benchmark solution. Concerning the impact of the true number of clusters K, the genetic algorithm gives better results than the benchmark approach when K is significantly lower than M . With increasing K, the Standard algorithm ceases to be suitable. With high values of K, Only Local, Only Init and Local & Init algorithms give very similar results to the benchmark approach. Overall, it is highly advantageous to use both proposed improvements of the genetic algorithm. Not only the Local & Init algorithm ends in the best solution among the four candidates, but is also the fastest one to reach it.
Finally, we examine variation in results from the perspective of repeated data generation and repeated algorithm runs. In Table 1, we report two kinds of standard deviations. The standard deviation capturing repeated data generation (labeled as SD/Sim) is obtained by first averaging objective values of all runs based on the same dataset and then taking standard deviation over all generated datasets. Conversely, the standard deviation capturing repeated algorithm runs (labeled as SD/Alg) is obtained by first taking standard deviation of all runs based on the same dataset and then averaging it over all generated datasets. We can see that SD/Alg is quite small except for the Standard algorithm in some scenarios. Nevertheless, in most cases, random data generation is the dominant source of variation.

Conclusion
The clustering method of Holý et al. (2017) offers a unique way of categorizing products in retail stores. The main limitation of the method lies in its computational complexity. To make the method more usable for practitioners, we revisit the algorithm finding an approximate solution and improve it in several ways. We augment the basic genetic algorithm by the renumbering procedure, the local search heuristic and the initial solution based on the simplified model. Although, these are rather common approaches, we tailor them to our specific problem in a non-trivial and efficient way. On a final note, the presented formulation of our problem is quite general which allows for straightforward use in other potential applications.