Interesting clustering algorithms, part one: Affinity propagation
Part Two - DBSCAN
Part Three - Time Series Clustering
Part Four - Self-Organizing Maps (SOM)
Part Five - Growing Neural Gas (GNG)
If you ask a novice data analyst what classification methods he knows, you will probably be listed a pretty decent list: statistics, trees, SVMs, neural networks ... But if you ask about clustering methods, in return you will most likely get a confident “k-means!” It is this golden hammer that is considered in all machine learning courses. Often, it does not even come to its modifications (k-medians) or connected graph methods.
Not that k-means is so bad, but its result is almost always cheap and angry. There are more perfectclustering methods, but not everyone knows what to use when, and very few understand how they work. I would like to open the veil of secrecy over some algorithms. Let's start with Affinity propagation.

It is assumed that you are familiar with the classification of clustering methods , and also have already used k-means and know its pros and cons. I will try not to go very deep into the theory, but try to convey the idea of the algorithm in simple language.
Affinity propagation
Affinity propagation (AP, aka proximity distribution method) receives an input matrix of similarity between the elements of the dataset

Ha, it would be something to spread. Only three lines, if we consider the main cycle; (4) - explicit labeling rule. But not so simple. Most programmers are not at all clear what these three lines do with matrices
So I will start from the other end.
Intuitive explanation
In some space, in some state, dots live. The dots have a rich inner world, but there is some rule
It’s boring to be alone in the world, so the points want to get together in hobby groups. Circles are formed around the leader (exemplar), who represents the interests of all members of the partnership. Each point would like to see the leader of someone who is as similar to her as possible, but is ready to put up with other candidates if many others like them. It should be added that the points are rather modest: everyone thinks that someone else should be the leader. You can reformulate their low self-esteem as follows: each point believes that when it comes to grouping, it does not look like itself (
The points do not know in advance what kind of teams they will be, nor their total number. The union goes from top to bottom: at first the points cling to the presidents of the groups, then they only reflect on who else supports the same candidate. Three parameters influence the choice of a point as a leader: similarity (it has already been said about it), responsibility and accessibility. Responsibility (responsibility, table
Let's take a simple example: points X, Y, Z, U, V, W, whose whole inner world is love for cats,
So, in the first step, every point
- The nearest (most similar) point defines the distribution of responsibility for all other points. The location of points farther than the first two so far only affects
allotted to them and only to them.
- Responsibility assigned to the nearest point also depends on the location of the second nearest.
- If within reach
there are several candidates who are more or less similar to him; those will be assigned approximately the same responsibility
acts as a kind of limiter - if a point is too much unlike all the others, it has nothing left to do but to rely only on itself
If
Returning to an example: X holds Y liable in the amount of
Then the points begin to think how ready they are to be a leader (available, available, for leadership). Accessibility for oneself (3) consists of all positive responsibility, “votes” given to the point. For
A new round of elections begins, but now
. Then
does not play a role, and in (1) everything
on the right side will be no less than they were in the first step.
essentially moves the point away
from
. The point’s self-responsibility rises from the fact that the best candidate, from her point of view, has bad reviews.
. Both effects appear here. This case splits into two:
- max. The same as in case 1, but the responsibility assigned to the point increases
- max. Then
will be no more than in the first step,
decreases. If we continue the analogy, it is as if the point, which was already considering whether to become its leader, received additional approval.
Accessibility leaves points in the competition that are either ready to stand up for themselves (W,
We rewrite the decision rule to get another look at the decision rule of the algorithm. We use (1) and (3). We denote

Approximately what I formulated at the beginning. It can be seen from this that the less confident the points are, the more “votes” must be gathered, or the more unlike the others you need to be in order to become a leader. Those. less
Well, I hope you have acquired some intuitive insight into how the method works. Now a little more serious. Let's talk about the nuances of applying the algorithm.
A very, very brief excursion into theory
Clustering can be represented as a discrete maximization problem with constraints. Let the similarity function be given on the set of elements
Where
The authors of AP talk a lot about "messages" from one element of the graph to another. This analogy comes from the derivation of formulas through the dissemination of information in a graph. In my opinion, it is a little confusing, because in the implementations of the algorithm there are no point-to-point messages, but there are three matrices
- When calculating
messages from data points are being sent
to potential leaders
- we look through matrices
and
along the lines
- When calculating
messages are being sent from potential leaders
to all other points
- we look through matrices
and
along the columns
Affinity propagation is deterministic. He has difficulty
There is an accelerated version of AP. The method proposed in the article is based on the idea that it is not necessary to calculate all updates to the matrices of accessibility and responsibility in general, because all points in the thick of other points relate to distant copies from them approximately the same.
If you want to experiment (keep it up!), I would suggest conjuring over formulas (1-5). Parts
Mandatory optimizations and parameters
Affinity propagation, like many other algorithms, can be interrupted early if
Affinity propagation is prone to computational oscillations in cases where there are some good clustering. To avoid problems, firstly, at the very beginning a little noise is added to the similarity matrix (very, very little, so as not to affect determinism, in sklearn implementation of the order
This is what a failure looks like - a bunch of small clusters surrounded by a ring of medium-sized clusters:

As already mentioned, instead of a predetermined number of clusters, the parameter “self-similarity” is used
As
The sizes of clusters obtained during the propagation of proximity vary within rather small limits, and if the dataset contains clusters of very different sizes, AP can either skip small ones or count large ones for several. Usually the second situation is less unpleasant - it is fixable. Therefore, often AP needs post-processing - additional clustering of group leaders . Any other method is suitable; additional information about the task can help here. It should be remembered that honest, lonely-standing points stand out for their clusters; such emissions should be filtered out before post-processing.
The experiments
Fuh, the wall of text has ended, the wall of pictures has begun. Let's test Affinity propagation on different types of clusters.




Если складка пересекает другой сгусток, дело обстоит хуже, но даже так AP помогает понять, что в этом месте творится что-то интересное.


При хорошем подборе параметра и кластеризатора-постобработчика AP выигрывает и в случае кластеров разного размера. Обратите внимание на картинку с


With clusters of the same shape, but with different densities, AP and k-means plus or minus parity. In one case, you need to guess right


With a bunch of higher density in another bunch, in my opinion, k-means wins a little. He, of course, “eats away” a significant chunk in favor of a cluster of higher density, but according to the visual result of the AP's work, heterogeneity is not very visible at all.


A few more pictures:




Total
Use affinity propagation when
- You are not very big (
) or moderately large, but sparse (
) dataset
- Proximity function known in advance
- You expect to see many clusters of various shapes and slightly varying numbers of elements.
- Are you ready to tinker with post-processing
- The complexity of the dataset elements does not matter
- Properties of the proximity function do not matter
- The number of clusters does not matter
Allegedly , various scientists have successfully used affinity propagation to
- Image segmentation
- Isolation of groups in the genome
- Partitioning cities by accessibility
- Clustering Granite Samples
- Movie Grouping on Netflix
In all these cases, the result was better than with k-means. Not that it’s some kind of super result in itself. I do not know whether in all these cases a comparison was made with other algorithms. I plan to do this in future articles. Apparently, on datasets from real life, the ability to spread proximity to deal with clusters of different geometric shapes helps the most.
Well, that’s all. Next time, consider another algorithm and compare it with the proximity propagation method. Good luck, Habr!