Learning graphs from data and spectral clustering with applications to finance
Abstract
In this bachelor's thesis we give a survey of methods to learn meaningful graphs from time series and study different spectral clustering algorithms. Finally, as a practical application, we use these algorithms to study the stock market.
Full text
Degree in Mathematics Degree in Engineering Physics Bachelor’s Degree Thesis Learning graphs from data and spectral clustering with applications to finance Josep M Gallegos Saliner May 2019 Supervised by Daniel P. Palomar Tutored by Jordi Castro Department of Electronic & Computer Engineering Hong Kong University of Science and Technology
First of all, thanks to Prof. Daniel P. Palomar and Dr. Sandeep Kumar for receiving me in their research group and being so attentive and helpful to every doubt that arise. Thanks to Fundaci´o Cellex and CFIS for giving me the support and help with the mobility scholarship, allowing me to take part in this international research experience. Thanks to Gen´ıs and Alejandro for sharing this time and all the help given. Thanks to my mother for all her support. And to finish, special thanks to Alexandra for all the interest and selfless advice she gave me.
Abstract Graph representations of data sets give us many possibilities to enhance the processing, analysis and visualization of data. Specifically, they are fundamental for spectral clustering: a family of algorithms that separate the data points of a set into groups by using the spectrum of its graph representation. As these representations are not unique, we give in this bachelor’s thesis a survey of methods useful to learn them. Some approaches are geared towards the general setting but others try to take advantage of specific properties of certain data sets. We also study the family of spectral clustering algorithms with a theoretical approach but also with a focus on its performance. As a practical application, these techniques are used to find clusters in the stock market with the aim of comparing the structure of the clusters with the industry classification of companies. Finally, we have used these representation techniques to visualize the increase of systemic risk associated with an economic crisis. Keywords Spectral clustering, graph Laplacian, graph learning 1
Contents 1 Introduction 3 2 Spectral Clustering 5 2.1 Basicclustering ........................................ 5 2.2 Graphnotation ........................................ 6 2.3 Basicsimilaritymeasures ................................... 8 2.4 Graphcuts........................................... 10 2.5 Algorithm ........................................... 12 2.6 Intuitive idea of spectral clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.7 Comparing performance of clusterings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.8 Performance of different Laplacians . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3 Graph learning for random variables 17 3.1 Correlationgraph ....................................... 17 3.2 Conditional independence graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.3 Precision matrix with Laplacian structure . . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.4 Graphsignalprocessing.................................... 20 4 Modelling stock data 23 4.1 Effectofaglobalfactor.................................... 23 4.2 Latentvariablemodel..................................... 24 5 Experiments with stock data 27 5.1 Drawing algorithms for graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 5.2 Clusterstructureofstocks .................................. 27 5.3 Effectofaglobalcrisis .................................... 33 A Fast approximate spectral clustering 37 B Spectral clustering as kernelized k-means 40 C List of stocks used 42 D R codes implemented 46 2
1. Introduction Clustering a data set consists in finding a partition of its data points such that the elements belonging to the same set are similar in some way. The aim of clustering is to explore and find structure in data without any human guidance, which makes it especially important nowadays with the large quantities of data available. Some direct applications of clustering are in market segmentation, identifying groups of people who might be susceptible to purchase a specific product, or in image segmentation, finding a partition of a digital image into groups that represent different elements in the image. Figure 1: Example of image segmentation[18]. In (a) there is the initial image and in (b), . . . , (h), the different objects detected using spectral clustering. In this thesis, we will study specifically spectral clustering, which is a very powerful and simple to implement method for clustering data points. However, it requires a graph representation of the data set. Such a graph representation is usually not available outside the study of some specific field like social networks. Nevertheless, it is also very interesting by itself since it gives rise to new visualization and analysis possibilities. These representations are not unique and well defined, so we consider different kinds of graphs: •For general data sets that only need to be in a metric space, we consider representations that only depend on the distance between the different points. •For data sets that consist of collections of i.i.d. random variables, we also consider representations depending on the covariance matrix. As a practical application we study the stock market in two different ways: •Finding a clustering of the stocks based only on its daily returns with the aim to create portfolios robust to certain market downfalls. •Using the graph visualization to observe a change in the number of connections during the subprime mortgage crisis of 2008. This bachelor’s thesis is divided into four sections. The first is organized as a tutorial or introduction to the different aspects of spectral clustering. It starts with the necessary definitions, gives some intuition on 3
Learning graphs and spectral clustering why it works and finally ends with a comparison of performances of different algorithms. There are some extra topics, which are not crucial, presented in the annex. These are about giving fast approximations for spectral clustering (in Annex A) and its relationship with k-means (in Annex B). The second part explains four different approaches to estimate a graph with different properties from the covariance matrix. The third one establishes the models for the returns of the stock market and studies different ways to clear up a possible problem with learning the graphs under the presence of an undesired factor. These approaches are presented with the aim to try to refine the estimation of the factor. In the last part, we apply all the different graph learning methods to the stock market and compare the different clusterings obtained with each graph. Since the aim of this thesis is not to study accurately the stock market, the conclusions of the experiments should be taken skeptically. 4
2. Spectral Clustering The reference for most of this first part on spectral clustering comes from the tutorial by Luxburg[20] which is a very comprehensive tutorial on the topic. 2.1 Basic clustering Clustering a data set consists in finding a partition of its points such that the elements belonging to the same set are similar in some way and the elements belonging to different sets are not. The concept of similarity is not something unique, it depends on the problem to solve. However, we generally assume that two points are similar if they are close to each other. K-means algorithm Given npoints in Rm, we want to find a partition of the points in ksets C1, . . . , Cksuch that the points in a set are close between them and far from the ones in other sets. To get this, we may try to minimize within-cluster variation of the sets. Definition 2.1. The within-cluster variation of a set Cjis: WCV(Cj) = 1 |Cj|X xi,xl∈Cjkxi−xlk2 2 where xiand xlare points in the set. The problem we want to solve is: minimize C1,...,Ck k X j=1 1 |Cj|X xi,xl∈Cjkxi−xlk2 2 This function is hard to minimize, but we can observe that: 1 |Cj|X xi,xl∈Cjkxi−xlk2 2= 2 X xi∈Cjkxi−¯xjk2 2 where ¯xj=1 |Cj|Pxi∈Cjxiis the centroid of the cluster Cj. We can find a local minimum with the following iterative algorithm: 1. Assign a number between 1 and krandomly to each point. This is their initial cluster. 2. Repeat iteratively until the clusters stop changing: (a) For each cluster compute its centroid. (b) For each point assign it to the cluster with the nearest centroid. This algorithm has the problem that the resulting clusters form convex sets in the space. This can lead to issues when the ideal clusters form non convex sets. 5
Learning graphs and spectral clustering We can relax the constraint of the structure of Hand just ask that HTH=I. minimize HTr(HTLH) subject to HTH=I The Rayleigh-Ritz theorem tells that the solution is given by Hsuch that contains the keigenvectors of L corresponding to the ksmallest eigenvalues. Relaxing NCut Something similar can be done with NCut. We define the indicator vectors hj= (h1,j, ..., hn,j)Tby: hi,j= 1/qvol(Aj) if vi∈Aj, or 0 otherwise. We set H∈Rn×kas the matrix containing those kindicator vectors as columns. Observe that HTDH =I. Also observe that: hT jLhj= (HTLH)jj =cut(Aj,Aj) vol(Aj) We can relax the constraint of the structure of Hand just ask that HTDH =I. minimize HTr(HTLH) subject to HTDH =I We can also substitute T=D1/2Hand we obtain: minimize TTr(TTD−1/2LD−1/2T) subject to TTT=I which, in a similar fashion, has as solution the eigenvectors of the normalized symmetric Laplacian. Remark 2.15.We should observe that after the relaxation, the solution that we obtain is not feasible for the original problem. 2.5 Algorithm RatioCut - Unnormalized spectral clustering Given a weight matrix W∈Rn×nand the number kof clusters to construct: 1. Compute L=D−W(unnormalized Laplacian). 2. Compute the ksmallest eigenvectors of Land let Ube the matrix containing them as columns. 3. Cluster the nrows (let’s call them yj∈Rk,j= 1 ... n) of the matrix Uusing the k-means algorithm. The output are the clusters A1, ...Akwith Ai={xj|yj∈Ci}. There are versions that come from the Ncut relaxation such as: 12
•Ng, Jordan and Weiss algorithm [14]: uses the eigenvectors of the Lsym and normalizes the rows of the matrix Ubefore applying k-means. •Shi and Malik [18]: uses the eigenvectors of the Lrw which correspond to the generalized eigenvectors of the problem. 2.6 Intuitive idea of spectral clustering Let’s remember the result we have presented before in Theorem 2.7 to give an intuitive idea of why the algorithm works. Theorem 2.16 (Eigenspace of Laplacians).Each Laplacian has 0as eigenvalue and its multiplicity k is the number of connected components A1, ...Akof the graph. Also, the kernel of the unnormalized Laplacian is spanned by the indicator vectors 1A1, ..., 1Akof those components. If we consider this theorem, we can establish a comparison between the ideal case and the real case: •Ideal case: the graph has kconnected components, one for each cluster. Thus the Laplacian has eigenvalue 0 with multiplicity k. The keigenvectors with eigenvalue 0 are linear combinations of the indicator vectors which let us identify the clusters as they belong in the subspace spanned by the indicator vectors. •In practice: small eigenvalues are an approximation of the ideal zero eigenvalues and eigenvectors are an approximation of the indicator vectors. If the approximation is good enough, we can recover the ideal connected components when doing the k-means step. Connecting with this interpretation, there is an heuristic method to choose the number kof clusters to find. If 0 = λ1≤... ≤λnare the eigenvalues of Lin increasing order, we can look at the eigengap: maxkλk+1 −λk. This eigengap can give us an intuition on which values are the approximation of the zero eigenvalues and which are not. 2.7 Comparing performance of clusterings There are many different ways to measure if the clustering obtained is good, but we will restrict ourselves to comparing with some ground truth information. Definition 2.17. A clustering Cis a partition of a set of points or data set Dinto sets C1, ... Ckwith |Ci|=ni>0, i= 1 ... kand |D|=n. In this section we will consider that C0is the ”perfect” clustering, the ground truth. Purity One of the most basic ones is to consider the purity of the clustering [10]. Definition 2.18. If C0is the ”ideal” clustering of the data set, we can define the purity of our clustering as: purity(C,C0) = 1 nX k max j|Ck∩C0 j| 13
Learning graphs and spectral clustering Purity has a lower bound of 0 and an upper bound of 1 (higher means better clustering) and is very easy to interpret. It has the downfall that high purity is easy to achieve if the number of clusters is large (if every point gets its own cluster then we get maximum purity). Variation of information Definition 2.19. The mutual information between two clusterings is defined as: I(C,C0) = X k,k0 P(k,k0) log P(k,k0) P(k)P(k0) where P(k,k0) is the probability that a point belongs to Ckin clustering Cand to C0 kin C0. Intuitively it gives us the reduction of uncertainty that we have in C0when we are told where the points are clustered in the clustering C. Some properties: •It is symmetric and nonnegative •I(C,C0)≤min{H(C), H(C0)}having equality when one cluster completely determines the other Definition 2.20. We define the variation of information [12] VI(C,C0) = H(C) + H(C0)−2I(C,C0) It satisfies that it is a distance function. Also it is lower bounded by 2 log Kwhere Kis the number of clusters. Normalized mutual information Definition 2.21. We can define: NMI(C,C0) = I(C,C0) (H(C) + H(C0))/2 Now the index takes values between 0 and 1 (with 0 being that one clustering does not give any information about the other). This way we get an index that is easier to interpret. This is the measure we have used in all the experiments in this thesis. 2.8 Performance of different Laplacians We want to test the performance of the different Laplacians associated to different spectral clustering algorithms. To experiment we have chosen different data sets: some from real life experiments, some that try to represent synthetic shapes and randomized weight matrix with noise. Synthetic shapes The synthetic shapes correspond to random data points in R2that try to look like certain figure. Specifically we have used the figure of two moons and the figure of three circles. They are created using the “clusterSim” package in R. In the experiments we have considered the self tuning Gaussian graph with 7 neighbors. 14
Figure 5: Plot of the two different kind of synthetic shapes used. Every cluster is in a different color. Real life data We have used the Yeast data set [2] which contains 1484 data points, 8 variables and data should belong to 9 different clusters. It tries to predict the localization site of a protein (non-numerically). Another data set used is the famous Iris data set [2]. It contains 150 points with 4 variables and the 3 different clusters correspond to different kind of flowers. In the experiments we have considered the self tuning Gaussian graph with 7 neighbors. Noisy weight matrices Definition 2.22. A noisy weight matrix is a symmetric matrix in [0, 1]n×nsuch that the elements that are in certain blocks along the diagonal (the clusters) belong to a U(0, 1) and the elements outside this blocks belong to a U(0, c) for some 0 <c<1. Each one represents a weight matrix with randomly weighted connections. To be useful for the experiments, inside the clusters the weights are higher on average. As we can see in the Figure 6the “yellower” blocks along the diagonal correspond to the clusters. We have use different kinds of noisy affinity matrices: •n= 100 with 4 “balanced” clusters of size 25 and varying values for c. •n= 300 with 5 “unbalanced” clusters of size 20, 40, 40, 100, 100 and varying values for c. •n= 100 with 10 “small” clusters of size 10 and varying values for c. We have repeated every clustering 100 times to try to reduce the effect of the randomness of the data (except for real life data sets, as they do not change every repetition). In the following table 1there is the average NMI for each Laplacian and data set. In red there is the maximum result for each data set. The Laplacians named “reg.” are regularized normalized Laplacians with regularization constant equal to the next value. 15
Learning graphs and spectral clustering Figure 6: Level plot of two of the different weight matrices. The left image corresponds to a “small” clusters weight matrix with c= 0.4 and the right one to a “balanced” clusters with c= 0.65. The result we get is that the unnormalized Laplacian works really worse in our tests. There is not a single case where we gain anything by choosing it instead of the normalized symmetric Laplacian or the random walk Laplacian. This may lead us to think that these are more useful for clustering and that solving the NCut problem is more helpful in real life than solving the RatioCut one. unnormalized norm. sym. r. walk reg. 0.25 reg. 0.5 reg. 1 two moons 0.73 0.77 0.74 0.62 0.61 0.59 three circles 0.99 0.99 0.99 0.43 0.42 0.42 iris 0.77 0.79 0.77 0.82 0.82 0.82 yeast 0.23 0.25 0.27 0.26 0.26 0.26 balanced 0.65 0.49 0.91 0.90 0.91 0.91 0.91 balanced 0.75 0.14 0.44 0.44 0.44 0.45 0.45 balanced 0.85 0.06 0.12 0.12 0.12 0.12 0.12 unbalanced 0.6 0.66 0.92 0.94 0.88 0.87 0.87 unbalanced 0.7 0.22 0.80 0.79 0.79 0.79 0.79 unbalanced 0.8 0.07 0.43 0.43 0.42 0.42 0.42 small 0.4 0.78 0.99 0.97 0.99 0.99 0.98 small 0.5 0.49 0.87 0.86 0.87 0.87 0.87 small 0.6 0.31 0.59 0.59 0.59 0.60 0.59 Table 1: Values of NMI for the different Laplacians and data sets. In red there are the maximum results for each data set. 16
3. Graph learning for random variables In the last section we saw some methods to obtain graph representations from general data sets. We only asked for a distance measure between different data points. But if our data consists of a collection of independent realizations of a random variable, we may consider other ways to get a similarity between data points. 3.1 Correlation graph Definition 3.1. We define the correlation of the vector of random variables Xas: C= (diag(Σ))−1/2Σ(diag(Σ))−1/2 where Σis the covariance matrix of Xand diag(Σ) is the diagonal matrix that has the same diagonal as Σ. The absolute value of the correlation [8] between two time series can be used as a measure of similarity and this way we can construct an adjacency matrix out of the correlation matrix. We could use as a weight matrix: W:= |C|−I where |C|corresponds to the entrywise absolute value of the correlation matrix. 3.2 Conditional independence graphs Conditional independence Definition 3.2. We say that two random variables Xand Yare conditionally independent given a third variable Zif their conditional probability distributions given Zare independent. We denote it by X⊥Y|Z. Example 3.3. An intuitive example of the concept is the following: Height and vocabulary of kids are not independent, but they are conditionally independent if you also account for age. Definition 3.4. We define precision matrix as Θ:= Σ−1where Σis the covariance matrix. If we consider that our random variables are Gaussian with zero mean and covariance Σ, we have a nice result: Theorem 3.5. The graph G = (V,E)with V ={v1,v2, ..., vn}and E ={vivj|Θij 6= 0, vi,vj∈V} satisfies that vivj6∈ E⇐⇒ xi⊥xj| {x1, ..., xn}\{xi,xj} In other words, if we consider the graph that has edges corresponding to the non-zero entries of Θthen this edges indicate conditional dependence between the two random variables given all the other random variables. To prove it we need a previous proposition first: 17
Learning graphs and spectral clustering Proposition 3.6 (Conditional Normal distribution).If Y =Y1 Y2∼N(0, Σ)and Σ=Σ11 Σ12 Σ21 Σ22then Y1|Y2∼N(0, Σ11 −Σ12Σ−1 22 Σ21). Proof. Using the proposition 3.6 we can check that Σ11 −Σ12Σ−1 22 Σ21−1=Σ−111 =Θ11. Now let’s take Y1=Ya Yband Y2the rest. From the above results we know that the conditional random variable Y1|Y2follows a N 0, Θaa Θab Θba Θbb−1!. Trivially we can see now that if Θab = 0 then since Θis symmetric Θba = 0, the inverse is also diagonal and thus Yaand Ybare independent given Y2. In the other way, if Yaand Ybare independent given Y2 then Y1|Y2has a diagonal covariance matrix and thus Θab = 0. Learning a sparse precision Remark 3.7.So if we get a precision matrix we get a meaningful graph: two vertices will only be connected if the variables are conditionally dependent given all the others. Also an important assumption we can make is that, in real life, interactions are mostly local and thus there are not many of them. So it would make sense to have a sparse precision matrix. In practice, though, we will only have access to a noisy sample covariance, so if we just invert it to get the precision we will not get zeros and we will lose this property. So we may want to estimate a sparse precision matrix and that can be done by solving the following convex optimization problem called graphical LASSO [7]: maximize Θ0log det Θ−Tr(ˆ ΣΘ)−ρkvec(Θ)k1 The two first terms come from the Maximum Likelihood estimation of the precision matrix under a Gaussian distribution and the last term with an l1norm induces sparsity on the matrix. This ρparameter controls how much sparsity we want. Ideally we would have the cardinality of the matrix here to enforce sparsity, but that is not a convex function so that is why we use the l1norm. It can also be interpreted as a maximum a posteriori (MAP) estimation assuming a double exponential prior distribution. 3.3 Precision matrix with Laplacian structure The precision matrices estimated with graphical LASSO do not give us a weighted graph directly since they dont have Laplacian or weight matrix structure in general (as they may have off diagonal elements with different signs). We might directly estimate a precision matrix with Laplacian structure [4] so we dont have to do any extra tricks. minimize Θ0Tr(ˆ ΣΘ)−log |Θ|+ρkvec(Θ)k1 subject to Θij ≤0∀i6=j, Θ1 =0 The log determinant is substituted by the log pseudo determinant as now the matrix is singular but some mathematical tricks can be done in order to get a normal log determinant and an easier problem to solve. 18
Remark 3.8.The values of the inverse are related with the kind of partial correlation or covariance as it can be seen from the Proof 3.2. To learn a precision matrix with Laplacian structure implies learning a model where all the partial covariances are positive. So this may not be useful for general data sets. To solve this problem we will use an iterative algorithm [22]. MM algorithm If we assume that the graph we are looking for is a connected, we know that the Laplacian will have eigenvalue 0 with multiplicity 1 and eigenvector 1. Then: log |Θ|= n−1 X i=1 log(λi) = n−1 X i=1 log(λi) + log(1) = log det (Θ+J/n) where J=11Tand λifor i= 1 ... n−1 are the positive eigenvalues of Θ. This way we get rid of the log |Θ|. Following, using that Θis a Laplacian, we can write it as a sum of weight contributions for each edge: Θ= n X i=1 X j>i wij eieT i−eieT j−ejeT i+ejeT j= n X i=1 X j>i wij (ei−ej) (ei−ej)T=: EDiag(w)ET where Eis the incidence matrix, wis a vector that contains the weights of the edges and Diag(w) is the diagonal matrix that contains the vector win the diagonal. This way the Laplacian constraints simplify to w≥0. Finally let’s observe another thing: kvec(Θ)k1= Tr(Θ(2I−J)) so to simplify the formulation, let’s define K:= ˆ Σ+ρ(2I−J). Also let’s rewrite: EDiag(w)ET+J/n= [E,1]Diag([w, 1/n])[E,1]T:= GDiag([w, 1/n])GT. The original formulation becomes now: minimize w≥0Tr(EDiag(w)ETK)−log det(GDiag([w, 1/n])GT) MM framework The MM method [19], which stands for Majorization-Minimzation, can be used to solve general optimization problems of the form: minimize xf(x) subject to x∈ X where fis differentiable. So instead of minimizing f(x) we iteratively solve: x(l+1) ∈arg minx∈X ¯ fx;x(l) where ¯ fx;x(l)should satisfy: 19
Learning graphs and spectral clustering 1. ¯ fx;x(l)≥f(x), ∀x∈ X; 2. ¯ fx(l);x(l)=f(x(l)); 3. ∇¯ fx(l);x(l)=∇f(x(l)); 4. ¯ fx;x(l)is continuous in both xand x(l). We can apply this framework to our formulation and get an iterative problem with a closed form solution: 1. Using the concavity of the log-determinant function: −log det(GXGT)≤Tr F0(GXGT)−1+ const. with F0:= GX0GTand X:= Diag([w, 1/n]). 2. We also have: Tr F0(GDiag([w, 1/n])GT)−1= Tr F1/2 0(GDiag([w, 1/n])GT)−1F1/2 0≤ Tr F−1/2 0GDiag([w0, 1/n])(Diag([w, 1/n]))−1Diag([w0, 1/n])GTF−1/2 0 and this functions satisfy the conditions necessary to be useful for MM. Now we can rewrite the MM iterative problem as: minimize w≥0diag(R)Tw+ diag(Q)Tw−1 where R:= ETKE and Q:= Diag([w0, 1/n])GTGDiag([w0, 1/n])GT−1GDiag([w0, 1/n]). This problem has a closed form solution given by: w∗=qdiag(Q)diag(R)−1 where corresponds to the Hadamard (entrywise) matrix product and the square root is also entrywise. 3.4 Graph signal processing Definition 3.9. The shift operator Sof a graph is a linear operator that replaces a signal value at each vertex with the linear combination of the values at the neighbors of that vertex. Remark 3.10.It can be interpreted as the graph equivalent of the time shift or delay z−1. We can consider that the weight matrix or the Laplacian matrix of a graph are examples of symmetric shift operators. One supposition [17] may be that the signal xcomes from a filter on the symmetric shift operator Sof the graph applied to white noise w:x=Pl≥0βlSlw. The signal processing equivalent would be to say that the signal comes from a FIR filter applied to white noise. Proposition 3.11. The shift operator Sand the covariance matrix Cxhave a common base of eigenvectors: SCx=CxS. 20
Proof. If S=VΛVTwith Λdiagonal, then the filter Hsatisfies H:= Pl≥0βlSl=VPl≥0βlΛlVT. Thus the covariance matrix Cx=E(xxT) = E(Hw(Hw)T) = HE(wwT)HT=HHT. In particular Cxhas the same eigenvectors as S. But knowing the eigenvectors is not enough. Thus we decide to use convex optimization to find a shift operator that shares eigenvectors with the covariance matrix but also has certain convex structure and is the most sparse by using the l1norm. minimize S,λkvec(S)k1 subject to S=Vdiag(λ)VT S∈ S where Vis the matrix of eigenvectors of the covariance matrix Σ. An example of convex structure might be that the matrix is a unnormalized Laplacian or an affinity matrix. S∈ SA⇐⇒ Sij ≥0, Sii = 0, S=ST,∀i6=j S∈ SL⇐⇒ Sij ≤0, S1 = 0, S=ST,∀i6=j We should also add some scale constraint to avoid the null solution: for example Pn i=2 |S1i|= 1 Like before, we will not have normally the exact real covariance matrix as we only have the noisy sample covariance matrix ˆ Σ. So we should allow for some error in the eigenvectors. We can get that by adding an auxiliary term that shares the eigenvectors with the sample covariance and asking that this term and the shift operator are close in Frobenius norm. minimize S,λ,S0kvec(S)k1+α 2kS−S0k2 F subject to S0=ˆ Vdiag(λ)ˆ VT S∈ S where ˆ Vis the matrix of eigenvectors of the sample covariance matrix. We include a reformulation of this problem as a quadratic programming problem (QP). Using this formulation, we can use specialized algorithms to find the solution. QP formulation For the case where the graph operator is an affinity matrix the relaxed weight formulation can be written as: minimize S,S0kvec(S)k1+α 2kS−S0k2 F subject to S0Σ=ΣS0 Sij =Sji ≥0 Sii = 0 X k S1k= 1 since S0and Σcommute if and only if they have a common base of eigenvectors. 21
Learning graphs and spectral clustering values: 0, 0.05, 0.1, 0.15, ... , 0.95 as the values are lower bounded by 0 and upper bounded by 1). Finally, to compare the performance of different parameters we have used spectral clustering on the graph obtained for each value (using the normalized symmetric Laplacian with a very small regularization constant). The parameters chosen are the ones that give higher NMI when comparing the graph obtained to the industry classification of stocks. Some of the methods of learning (nuclear norm approximation, learning a shift operator with Laplacian constraints, . . . ) give non-exact results: the graphs obtained are only an approximation of the solution because we have used general purpose convex solvers. In those cases, we have “smoothed” the graph by thresholding it by a small value. Finally, the fixed rank latent model estimation could not be used because the algorithm was too slow for a data set of this size. Remark 5.3.In the data set used in this experiment there is not any significant difference between the PCA and the ML estimation of the global factor. For this reason we will only use the PCA method. Results Figure 7: Jordan estimation graph with 3 neighbors. The NMI value is 0.96. 28
Figure 8: k-nearest neighbors graph with 3 neighbors. The NMI value is 0.96. Figure 9: Correlation graph with 0.45 thresholding. The NMI value is 0.96. 29
Learning graphs and spectral clustering Figure 10: Graphical LASSO graph with regularization ρ=e(−10). The NMI value is 0.96. Figure 11: Plot of the NMI values in graphical LASSO estimation as a function of log(ρ) 30
Figure 12: Laplacian precision graph with regularization ρ= 3.7 ·10−6and extra thresholding afterwards. The NMI is 0.84. Figure 13: Weight shift operator graph with α= 4.9 ·108with some thresholding afterwards. The NMI is 0.7. 31
Learning graphs and spectral clustering Figure 14: Correlation graph after using PCA with threshold 0.15. The NMI is 0.62. Figure 15: Nuclear norm graph with regularization α= 0.22 and γ= 3.3 ·10−4and extra thresholding afterwards. The NMI is 0.76. 32
Conclusions Some observations we can extract from this experiment: •In general, we can observe that for the parameters chosen, the graph structure agrees with the industry classification. Intuitively, we may think that the industry classification already gives a good clustering. •The green vertices (energy companies) seem to be more interconnected than the vertices of other sectors in most realizations. This agrees with [11] which says that the energy sector is kind of isolated. •The method in Figure 12 does not give a very good result (the matrix obtained is not sparse). Some possible reasons are lack of iterations for the MM algorithm or that the problem does not admit a Laplacian inverse. •In a similar fashion, in the Figure 13 we do not get a very sparse matrix. One possible explanation is that the QP solver used does not seem to be very precise. Besides that, the problem probably does not admit a shift operator with weight matrix constraints. 5.3 Effect of a global crisis The following experiment consists in trying to observe the effect of the crisis that happened between 2007 - 2009 in the United States by using animated graphs. The crisis started in the subprime mortgage market and ended up affecting almost the whole world. An augment of the correlations [11] between stocks is observed during crisis and is associated to the increase of systemic risk. This is what we want to see in the graphs. We have tried to use all the stocks from the last experiment, but some companies did not exist back in 2005. The companies we have considered are the ones from the last experiment that were in SP500 back in 2005. We have estimated graphs using graphical LASSO and we have estimated the market factor using PCA. The market factor has been added as an extra black vertex using the idea presented in Section 4.1. As a parameter we have used a high value of ρ= 0.22 to keep only the most relevant connections by enforcing a lot of sparsity. Finally, as data, we have used the daily log-returns from 2005 to 2018 in groups of 365 days. There are four estimations for every year: one starting on January, one on April, one on July and one on October. The following link corresponds to the html animation: https://drive.google.com/open?id=1OSiBDQ9JfqTUOYPzNDgEF3Bd9HhmHuel In this written thesis, there are only screenshots of the animation taken at the beginning of some of the years. Conclusions We can see that in the years 2008 and 2009 the graph estimated gets denser and that afterwards it disconnects again. Besides that, in most of the graphs, the points are only connected to the black point: the PCA estimation of the market factor. That means that the estimated factor explains most of the behavior of the stocks (as we are estimating a conditional independence graph). 33
Learning graphs and spectral clustering Figure 16: Plots of the estimated graph for each year. 34
References [1] Charanpal Dhanjal, Romaric Gaudel, and St´ephan Cl´emenon. Efficient eigen-updating for spectral graph clustering. Neurocomputing, 131:440 – 452, 2014. [2] Dua Dheeru and Efi Karra Taniskidou. UCI machine learning repository, 2017. [3] Inderjit S. Dhillon, Yuqiang Guan, and Brian Kulis. A unified view of kernel k-means, spectral clustering and graph cuts. Technical Report TR-04-25, University of Texas Dept. of Computer Science, 2005. [4] H. E. Egilmez, E. Pavez, and A. Ortega. Graph learning from data under Laplacian and structural constraints. IEEE Journal of Selected Topics in Signal Processing, 11(6):825–841, Sep. 2017. [5] Yiyong Feng and Daniel P. Palomar. A signal processing perspective of financial engineering. Foundations and Trends in Signal Processing, 9(3-4), 2016. [6] Maurizio Filippone, Francesco Camastra, Francesco Masulli, and Stefano Rovetta. A survey of kernel and spectral methods for clustering. Pattern Recognition, 41(1):176 – 190, 2008. [7] Jerome Friedman, Trevor Hastie, and Robert Tibshirani. Sparse inverse covariance estimation with the graphical lasso. Biostatistics, 9(3):432–441, 2008. [8] Tapio Heimo, Jari Saramaki, Jukka-Pekka Onnela, and Kimmo Kaski. Spectral and network methods in the analysis of correlation matrices of stock returns. Physica A: Statistical Mechanics and its Applications, 383(1):147–151, 2007. [9] Koulik Khamaru and Rahul Mazumder. Computation of the maximum likelihood estimator in low-rank factor analysis. Mathematical Programming, pages 1–32, 2018. [10] Christopher D. Manning, Prabhakar Raghavan, and Hinrich Sch¨utze. Introduction to Information Retrieval. Cambridge University Press, New York, NY, USA, 2008. [11] Gautier Marti, Frank Nielsen, Mikolaj Bi´nkowski, and Philippe Donnat. A review of two decades of correlations, hierarchies, networks and clustering in financial markets. Papers 1703.00485, arXiv.org, March 2017. [12] Marina Meil˘a. Comparing clusterings—an information based distance. J. Multivar. Anal., 98(5):873– 895, May 2007. [13] Zhaoshi Meng, Brian Eriksson, and Al Hero. Learning latent variable Gaussian graphical models. In International Conference on Machine Learning, pages 1269–1277, 2014. [14] Andrew Y. Ng, Michael I. Jordan, and Yair Weiss. On spectral clustering: Analysis and an algorithm. In Advances in Neural Information Processing Systems, pages 849–856. MIT Press, 2001. [15] Feiping Nie, Xiaoqian Wang, Michael I. Jordan, and Heng Huang. The constrained laplacian rank algorithm for graph-based clustering. In Proceedings of the Thirtieth AAAI Conference on Artificial Intelligence, February 12-17, 2016, Phoenix, Arizona, USA., pages 1969–1976, 2016. [16] Huazhong Ning, Wei Xu, Yun Chi, Yihong Gong, and Thomas S. Huang. Incremental spectral clustering by efficiently updating the eigen-system. Pattern Recognition, 43(1):113 – 127, 2010. 35
Learning graphs and spectral clustering [17] S. Segarra, A. G. Marques, G. Mateos, and A. Ribeiro. Network topology inference from spectral templates. IEEE Transactions on Signal and Information Processing over Networks, 3(3):467–483, Sept 2017. [18] Jianbo Shi and J. Malik. Normalized cuts and image segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(8):888–905, Aug 2000. [19] Ying Sun, Prabhu Babu, and Daniel P. Palomar. Majorization-minimization algorithms in signal processing, communications, and machine learning. IEEE Transactions on Signal Processing, 65:794– 816, 02 2017. [20] Ulrike von Luxburg. A tutorial on spectral clustering. Statistics and Computing, 17(4):395–416, Dec 2007. [21] Lihi Zelnik-manor and Pietro Perona. Self-tuning spectral clustering. In L. K. Saul, Y. Weiss, and L. Bottou, editors, Advances in Neural Information Processing Systems 17, pages 1601–1608. MIT Press, 2005. [22] Licheng Zhao, Yiwei Wang, Sandeep Kumar, and Daniel P. Palomar. Optimization algorithms for graph laplacian estimation via admm and mm. under review, 2018. 36
A. Fast approximate spectral clustering For some data sets that change constantly (like internet blog communities) we would like to cluster new data as it comes. Typical spectral clustering needs to calculate the eigenvectors all over again with complexity O(n3) which is quite slow for this kind of applications. But we may just update the eigenvalues and eigenvectors when adding new points or changing the weights between vertices. This might be useful when working with data sets that evolve along time like time series. Approximation by considering small perturbations We may approximate [16] the new eigenvectors and eigenvalues by considering that the change in the Laplacian matrix is a small perturbation and taking the first order approximation. Definition A.1. An incidence vector rij (w) is a vector with only two nonzero elements: i-th element equal to √wand j-th element equal to −√w, indicationg that the data points iand jhave similarity w. we will also use: rij (w) = √wuij where uij is the vectors that contains ±1 and zeros. Definition A.2. An incidence matrix Ris a matrix whose columns are incidence vectors. Remark A.3.With our definition of an incidence matrix, we may consider an incidence matrix that contains the vectors rij (w1) and rij (w2) and then the total similarity between the points iand jwould be w1+w2. That is valid and will be useful in the following steps. Proposition A.4. If L=D−Wis a Laplacian matrix, then there exists an incidence matrix Rsuch that L=RRT. Also, Rhas all the incidence vectors rij (wij ), 1 ≤i<j≤n. Following from the observation from before: Proposition A.5. If L=RRTand data points i and j have a similarity change ∆wij , the new graph laplacian L0= [R,rij (∆wij )][R,rij (∆wij )]T. Proposition A.6. Suppose Lx=λDx our generalized eigenvalue problem where both Land Dare symmetric. Then the first order approximation of the change of λcan be approximated as: ∆λ=xT(∆L−λ∆D)x xTDx(1) Example: if the update were adding an incidence vector rij (∆wij ) = p∆wij uij then: ∆λ= ∆wij xT(uij uT ij −λdiag(i,j))x xTDx= ∆wij (xi−xj)2−λ(x2 i+x2 j) where by diag(i,j) we denote the diagonal matrix that contains 1 in the positions iand jand 0 in the others and xis the vector corresponding to the eigenvalue. If we assume that that xis an indicator vector, that two clusters have nearly the same degrees and λ << 1 that holds for the smallest eigenvalues: ∆λ≈ −2λ∆wij /dif iand jare in the same cluster, or ∆λ≈4∆wij /dif they are in different clusters. If we define K=L−λDwe end up getting: 37
Learning graphs and spectral clustering 54. MKC, McCormick & Company Incorporated, Consumer Staples 55. CHD, Church & Dwight Co. Inc., Consumer Staples 56. HSY, Hershey Company, Consumer Staples 57. K, Kellogg Company, Consumer Staples 58. CAG, Conagra Brands Inc., Consumer Staples 59. SJM, J.M. Smucker Company, Consumer Staples 60. TAP, Molson Coors Brewing Company Class B, Consumer Staples 61. HRL, Hormel Foods Corporation, Consumer Staples 62. LW, Lamb Weston Holdings Inc., Consumer Staples 63. BF-B, Brown-Forman Corporation Class B, Consumer Staples 64. CPB, Campbell Soup Company, Consumer Staples 65. COTY, Coty Inc. Class A, Consumer Staples 66. XOM, Exxon Mobil Corporation, Energy 67. CVX, Chevron Corporation, Energy 68. COP, ConocoPhillips, Energy 69. SLB, Schlumberger NV, Energy 70. EOG, EOG Resources Inc., Energy 71. OXY, Occidental Petroleum Corporation, Energy 72. MPC, Marathon Petroleum Corporation, Energy 73. PSX, Phillips 66, Energy 74. KMI, Kinder Morgan Inc Class P, Energy 75. VLO, Valero Energy Corporation, Energy 76. WMB, Williams Companies Inc., Energy 77. OKE, ONEOK Inc., Energy 78. HAL, Halliburton Company, Energy 79. PXD, Pioneer Natural Resources Company, Energy 80. APC, Anadarko Petroleum Corporation, Energy 81. CXO, Concho Resources Inc., Energy 44
82. HES, Hess Corporation, Energy 83. FANG, Diamondback Energy Inc., Energy 84. MRO, Marathon Oil Corporation, Energy 85. BHGE, Baker Hughes a GE Company Class A, Energy 86. DVN, Devon Energy Corporation, Energy 87. APA, Apache Corporation, Energy 88. NBL, Noble Energy Inc., Energy 89. COG, Cabot Oil & Gas Corporation, Energy 90. NOV, National Oilwell Varco Inc., Energy 91. FTI, TechnipFMC Plc, Energy 92. HFC, HollyFrontier Corporation, Energy 93. XEC, Cimarex Energy Co., Energy 94. HP, Helmerich & Payne Inc., Energy 45
Learning graphs and spectral clustering D. R codes implemented In this section we add some of the R codes implemented. 1kn affinity <−function(data points , k ) { 2require(dbscan) 3n = nrow (data p o i n t s ) 4affinity = m atr ix (0L , nrow = n , ncol = n ) 5aux = dbscan : : kNN( data p oi nt s , k , s o r t = FALSE) 6f o r ( i i n 1 : n ) { 7for ( j i n 1 : k ) { 8node = aux$i d [ i , j ] 9a f f i n i t y [ i , node ] = 1 10 a f f i n i t y [ node , i ] = 1 11 } 12 } 13 r e t u r n (affinity) 14 } 1n u c l e a r norm p r e c i s i o n <−function( Sigma , a l f a , gamma){ 2require(CVXR) 3n = NROW( Sigma ) 4 5Theta = S emidef ( n ) 6Spa rs e = Symmetric ( n ) 7LowRank = Semidef ( n ) 8 9obj = Minimize (CVXR : : ma tr ix t r a c e ( Sigma % ∗% Theta) −CVXR : : log det ( Theta ) + a l f a ∗ cv xr norm (CVXR : : vec ( Sparse ) , p = 1) + gamma∗ma tr ix t r a c e ( LowRank ) ) 10 11 c o n s t r a i n t s = list( 12 Theta == Sparse −LowRank 13 ) 14 15 p = Problem ( obj , c o n s t r a i n t s ) 16 result = s o l v e (p , s o l v e r = ”SCS” ) 17 18 r e t u r n (as .mat rix (result$getValue ( Sparse ) ) ) 19 } 1s p e c t r a l c l u s t e r i n g <−function(W, num c l u s t e r s ) { 2# c l u s t e r u sin g the r e g u l a r i z e d nor ma li ze d L a placian with a ve r y sma l l r e g u l a r i z a t i o n constant 3tau = 10ˆ( −10) # to av oid problems when the ma tri x i s zero 4W = W + tau 5# we c r e a t e t he r eg sym L a p l a c i a n 6diag (W) = 0 7d = rowSums (W) 8n = length( d ) 9L = diag ( n ) −d iag (sqrt(1 /d ) ) % ∗%W% ∗%diag (sqrt(1 /d ) ) 10 11 # we s t a r t c l u s t e r i n g 46
12 evL = e ige n (L , symmetric = TRUE) 13 evL$v e c t o r s = evL $v e c t o r s [ , ( n −num c l u s t e r s + 1) : n ] 14 15 # Normalize the rows of the e i g e n v e c t o r s 16 Z = sqrt( rowSums ( evL $vectors ∗evL$v e c t o r s ) ) 17 Z = evL$v e c t o r s /Z 18 km = kmeans (Z , c e n te rs = num c l u s t e r s , n s t a r t = 10) 19 r e t u r n (km$cluster) 20 } 1graph L a p l ac i a n e s t i m a t i o n MM <−function(S , A = −1, a l f a = 0 , w0 = −1){ 2# MM−Based Graph L a pl a c ia n e s t i m a t i o n 3# a l f a i s the r e g u l a r i z a t i o n c o ns ta nt f o r the l 1 norm ( o f th e o r i g i n a l f o r m u l a t i o n ) 4# A i s t he a dj ace nc y m atr ix t ha t o nl y t a ke s the v a l u e s 0 or 1 5# E i s the i n c i d e n c y ma tr ix 6# S i s t he sample c o v a r i a n c e ma tri x 7# H = 2 I d −1 1ˆT 8# K = S + a l f a H 9# M i s the number of edges 10 # i t does a f i x e d number of i t e r a t i o n s : 100 11 12 l = 0 13 n = NROW(S) 14 15 K = S −alfa 16 K=K+2∗alfa∗di ag (n) 17 18 # g iv en A f i r s t we have to get an i n c i d e n c y mat ri x E 19 i f (A == −1){ 20 A = matrix ( 1 , n , n ) −diag (n) # f u l l y connected graph 21 } 22 E = NULL 23 M = 0 # number of edges 24 f o r ( i i n 1 : n ) { 25 i f ( i <n ) { 26 f o r ( j i n ( i +1) : n ) { 27 i f (A[ i , j ] == 1) { 28 M = M + 1 29 v = rep ( 0 , n ) 30 v [ i ] = 1 31 v [ j ] = −1 32 E = cbind(E , v ) 33 } 34 } 35 } 36 } 37 v = rep ( 1 , n ) 38 G = cbind(E , v ) 39 40 R=t(E) % ∗% K % ∗% E 41 42 i f (w0 == −1){ 43 w = rep (1 /M, M) 44 } 45 e l s e {w = w0} 47
Learning graphs and spectral clustering 46 47 w h i l e ( l <100){ 48 Aux w = d iag (c(w, 1/n ) ) 49 Q= Aux w % ∗%t(G) % ∗%solve(G % ∗% Aux w % ∗%t(G) ) % ∗% G % ∗% Aux w 50 51 Q=Q[ 1 :M, 1:M] 52 53 w = s q r t (di ag (Q)/ di ag (R) ) 54 55 l=l+1 56 } 57 58 Theta = E % ∗%diag (w) % ∗%t(E) 59 r e t u r n (Theta) 60 } 1l e a r n weight Jordan <−function(X, m) { 2# X has as rows the d i f f e r e n t data p o i n t s (X [ 1 , ] , X[ 2 , ] , . . . ) 3# m i s the number of n ei gh bo rs d e s i r e d per p oi nt 4 5n = nrow (X) 6A = matrix ( 0 , n , n ) 7s c a l a r prods = X % ∗%t(X) 8 9f o r ( i i n 1 : n ) { 10 e = rep( s c a l a r prods [ i , i ] , n ) + di ag ( s c a l a r prods ) −2∗s c a l a r prods [ i , ] # e c o n t a i n s norm (X i −X j , 2) ˆ2 11 e s o r t e d = sort( e ) 12 13 Divisor = m∗e s o r t e d [m+2] −sum( e s o r t e d [ 1 : (m+1) ] ) # because we ar e i n c l u d i n g the d i a g o n a l terms t ha t a re z e ro 14 A[ i , ] = e s o r t e d [m+2] 15 A[ i , ] = (A[ i , ] −e ) /Divisor # we w i l l s e t to z er o a l l the unwanted n e g a t i v e c on n ec ti o n i n th e ne xt s t ep 16 } 17 A[A <0] = 0 # only keep p o s i t i v e element s 18 diag (A) = 0 # d i a g o n a l i s s e t to z er o 19 A = 1/2∗(A + t(A) ) # symmetrize 20 r e t u r n (A) 21 } The following code obtains the stock data used for the experiments: 1library(tidyquant) 2library(XLConnectJars) 3library( XLConnect ) 4 5SP500 = tq index(”SP500”) 6SP500aux = NULL 7SP500aux$symbol = SP500$ symbol [ SP500$s e c t o r == ” Real E st ate ” ] 8SP500aux$s e c t o r = SP500$s e c t o r [ SP500$s e c t o r == ” Real E sta te ” ] 9SP500aux$symbol =c(SP500aux$symbol , SP500$ symbol [ SP500$s e c t o r == ”Consumer S t a p l e s ” ] ) 10 SP500aux$sector = c(SP500aux$se c tor , SP500$s e c t o r [ SP500$s e c t o r == ” Consumer S t a p l e s ” ] ) 48
11 SP500aux$symbol =c(SP500aux$symbol , SP500$ symbol [ SP500$s e c t o r == ”Energy”] ) 12 SP500aux$sector = c(SP500aux$se c tor , SP500$s e c t o r [ SP500$s e c t o r == ”Energy”] ) 13 14 #These ones have some problems . . . 15 SP500aux$symbol [ SP500aux$ symbol == ”BF .B” ] = ”BF−B” 16 SP500aux$symbol [ SP500aux$ symbol == ”ECA−CA” ] = ”ECA” 17 18 SP500 = SP500aux 19 20 t e s t set = NULL 21 for ( word i n SP500$ symbol ){ 22 #t r y ({# t h e r e a re some s t o c k s which a re not c o r r e c t l y downloaded 23 getSymbols ( word , from = ”2018−01−01” , to = ”2019−01−01” ) 24 r e t = ROC( na .approx( Cl ( get( word ) ) ) ) # we f i l l the NA 25 r e t = r e t [ −1] #we take out the f i r s t v a lue which i s a NA 26 colnames( r e t ) = word 27 t e s t set =cbind ( t e s t set , r e t ) 28 #}) 29 } 30 31 t r u e l a b e l s =as .numeric(as .f a c t o r ( SP500$s e c t o r ) ) 32 num c l u s t e r s = max( t r u e l a b e l s ) 33 v e r t e x colors = NULL 34 v e r t e x colors [ SP500$s e c t o r == ” Real E st ate ” ] = ” cyan ” 35 v e r t e x colors [ SP500$s e c t o r == ” Consumer S t a p l e s ” ] = ”indianred1” 36 v e r t e x colors [ SP500$s e c t o r == ”Energy”] = ”green” 37 v e r t e x l a b e l s = SP500$ symbol 1Seg arra a f f i n i t y OSQP <−function( Sigma , a l f a ) { 2# S eg ar ra a f f i n i t y ma tri x e s t i m a t i o n problem as a QP 3 4# n = s i z e o f the c o v a r i a n c e m at ri x 5# Sigma i s the sample c o v a r i a n c e ma tr ix 6# a l f a e n f o r c e s t ha t S and S ’ ar e s i m i l a r i n f r o b e n i u s norm 7# a l f a i s a ve ct o r of a l f a v a lu es ( i . e . we w i l l s o l v e the problem as many times as t h e r e ar e el em ent s i n a l f a ) . t he advanta ge i s t h at we do not have to compute t he m a t r i c e s a l l o v er a ga in 8require( osqp ) 9 10 n = length( Sigma [ 1 , ] ) 11 nc2 = n∗(n−1)/2# n choose 2 12 13 big mat rix = NULL 14 f o r ( i i n 2 : n ) {# n choose 2 eqs , common e i g e n v e c t o r s of S ’ and Sigma 15 for ( j i n 1 : ( i −1) ) { 16 row F Sigma = m atrix ( 0 , n , n ) 17 row F Sigma [ i , ] = Sigma [ j , ] 18 row F Sigma [ j , ] = −Sigma [ i , ] 19 row F Sigma = row F Sigma + t(row F Sigma ) −di ag (diag (row F Sigma ) ) 20 21 row F Sigma = c(rep( 0 , nc2+n ) , as .vector(row F Sigma [ l ower .t r i (row F Sigma , diag = T) ] ) ) 22 big mat rix =rbind( b ig matrix ,row F Sigma ) 23 } 24 } 49
Learning graphs and spectral clustering 25 26 f o r ( i i n 1 : n ) {# n eqs , d i a g o n a l i s z e ro 27 row F n u l l d i a g = matri x (0 , n , n ) 28 row F n u l l d i a g [ i , i ] = 1 29 row F n u l l d i a g = c(as .vector(row F n u l l d i a g [ lower .t r i (row F n u l l d i a g , d iag = T) ] ) , rep(0 , nc2+n) ) 30 31 big mat rix =rbind( b ig matrix ,row F n u l l d i a g ) 32 } 33 34 row F normal = mat rix ( 0 , n , n ) #1 eq , s e t t i n g the s c a l e ( f i r s t row sums 1) 35 row F normal [ 2 : n , 1] = 1 36 row F normal = c(as .vector(row F normal [ lower .tri(row F normal , di ag = T) ] ) , rep(0 , nc2+n ) ) 37 big mat rix =rbind( b ig matrix ,row F normal) # c a r e f u l b s h ou l d be 1 i n t h i s e n t r y 38 39 f o r ( i i n 2 : n ) {# n choose 2 i n e q u a l i t i e s , the element s ar e nonnegative (>=0) 40 for ( j i n 1 : ( i −1) ) { 41 row F geq = matrix (0 , n , n ) 42 row F geq [ i , j ] = 1 43 row F geq = c(as .vector(row F geq [ lower .t r i (row F geq , diag = T) ] ) , rep(0 , nc2+n ) ) 44 big mat rix =rbind( b ig matrix ,row F geq ) 45 } 46 } 47 48 Dmat aux = ma trix (s q r t ( 2 ) , n , n ) 49 diag (Dmat aux ) = 1 50 Dmat aux = as .vector(Dmat aux [ lower .tri(Dmat aux , d iag = T) ] ) 51 52 Dmat = d iag (c(Dmat aux , Dmat aux ) ) #now i t can be s e m i d e f i n i t e p o s i t i v e 53 Dmat [ 1 : ( nc2 + n ) , ( nc2+n+1) : ( 2 ∗nc2+2∗n ) ] = −dia g (Dmat aux ) 54 Dmat [ ( nc2+1+n ) : ( 2 ∗nc2+2∗n ) , 1 : ( nc2+n ) ] = −d iag (Dmat aux ) 55 56 dvec = 2∗c(rep ( 1 , nc2+n ) , rep ( 0 , nc2+n ) ) 57 58 l = c(rep ( 0 , nc2 + n ) , n , rep (0 , nc2 ) ) # here we change t ha t the sum of the row i s n , not 1 59 u = c(rep( 0 , nc2 + n ) , n , rep(+ I n f , nc2 ) ) 60 61 pars = osqpSettings(max i t e r = 100000 , p o l i s h = TRUE, ve rbo se = FALSE) 62 63 S h i f t op = NULL 64 S h i f t aux = NULL 65 f o r ( i i n 1 : length( a l f a ) ) { 66 solucio = solve osqp (P = Dmat∗a l f a [ i ] , q= dvec , A = ( bi g matrix ) , l , u , pa rs = pa rs ) $x 67 S = matrix ( 0 , n , n ) 68 S [ lower .t r i (S , di ag = T) ] = s o l u c i o [ 1 : ( nc2+n) ] 69 S=S+t(S) # s i n c e the d i a g o n a l s ar e ze ro 70 71 Saux = matrix ( 0 , n , n ) 72 Saux [ lowe r .t r i ( Saux , di ag = T) ] = s o l u c i o [ ( nc2+1+n ) : ( 2 ∗nc2+2∗n ) ] 73 Saux = Saux + t( Saux ) −diag (di ag ( Saux ) ) 74 75 S h i f t op [ [ i ] ] = S 76 S h i f t aux [ [ i ] ] = Saux 77 } 50
78 79 r e t u r n ( S h i f t op ) 80 } 51