def kmeans_init(X, Y, n_labels, n_hidden_states, latent_node_features=False):
    all_feats = []
    # iterate over samples
    for x, y in zip(X, Y):
        # first, get neighbor counts from nodes
        if len(x) == 3:
            features, edges, n_hidden = x
        elif len(x) == 4:
            # edge features are discarded
            features, edges, _, n_hidden = x
        else:
            raise ValueError("Something is fishy!")
        n_visible = features.shape[0]
        if latent_node_features:
            n_visible -= n_hidden
        if np.max(edges) != n_hidden + n_visible - 1:
            raise ValueError("Edges don't add up")

        labels_one_hot = np.zeros((n_visible, n_labels), dtype=np.int)
        y = y.ravel()
        gx = np.ogrid[:n_visible]
        labels_one_hot[gx, y] = 1

        graph = sparse.coo_matrix((np.ones(edges.shape[0]), edges.T),
                                  (n_visible + n_hidden, n_visible + n_hidden))
        graph = (graph + graph.T)[-n_hidden:, :n_visible]

        neighbors = graph * labels_one_hot.reshape(n_visible, -1)
        # normalize (for borders)
        neighbors /= np.maximum(neighbors.sum(axis=1)[:, np.newaxis], 1)

        all_feats.append(neighbors)
    all_feats_stacked = np.vstack(all_feats)
    try:
        km = KMeans(n_clusters=n_hidden_states)
    except TypeError:
        # for old versions :-/
        km = KMeans(k=n_hidden_states)

    km.fit(all_feats_stacked)
    H = []
    for y, feats in zip(Y, all_feats):
        H.append(np.hstack([y, km.predict(feats) + n_labels]))

    return H
dataset/ETHPy150Open pystruct/pystruct/pystruct/models/latent_node_crf.py/kmeans_init/original