hierarchical clustering of ternary matrix

Viewed 101

I have a matrix with values -1,0,1 of the form

array([[ 1,   1],
       [ 0,  -1],
       [ 1,  -1],
       [ 1,   1]
       [ -1,  1]])

and what I want is kind of a hierarchical clustering from left to right.

  • The 'biggest' 3 clusters contain the data points, that have a -1,0 or 1 in the first dimension.
  • The next 9 clusters are a refinement of the first 3 clusters such that they contain a
    • 1 at first dimension, 1 at second dimension or

    • 1 at first dimension, 0 at second dimension or

    • 1 at first dimension, -1 at second dimension or

    • 0 at first dimension, 1 at second dimension or

    • 0 at first dimension, 0 at second dimension or

    • 0 at first dimension, -1 at second dimension or

    • -1 at first dimension, 1 at second dimension or

    • -1 at first dimension, 0 at second dimension or

    • -1 at first dimension, -1 at second dimension

and so on.

The desired output should be

output = [[[0,3],[],[2]],[[1],[],[]],[[4],[],[]]]

because

data point 0 ([1,1]), data point 2 ([1,-1]) and data point 3 ([1,1]) are in the first big cluster, data point 1 ([0,-1]) is in the second big cluster, data point 4 ([-1,1]) is in the third big cluster and then the refinements concerning the second dimension.

1 Answers

This is not a good example on clustering, I believe it's more of a classification case since the classes in this case are defined, and a deterministic code such as the proposition below is enough to classifiy all the entries:

import numpy as np
a = np.array([[ 1,   1],
              [ 0,  -1],
              [ 1,  -1],
              [ 1,   1],
              [ -1,  1]])

def categorize(a):
    classes = [[[],[],[]],[[],[],[]],[[],[],[]]]
    def get_classes(x,y):
        idx = 0 if x==1 else 1 if x == 0  else 2
        idy = 0 if y==1 else 1 if y == 0  else 2
        return idx,idy

    for i in range(a.shape[0]):
        idx,idy=get_classes(a[i,0],a[i,1])
        classes[idx][idy].append(i)
    return classes

output = categorize(a)
print(output)
Related