Ejemplo n.º 1
0
def eps_nn(X, eps=1.):
    """Returns the eps-nearest-neighbours graph of the data

    Parameters
    ----------
    X, array of shape (n_samples, n_features), input data
    eps, float, optional: the neighborhood width

    Returns
    -------
    the resulting graph instance
    """
    from nipy.algorithms.routines.fast_distance import euclidean_distance
    if np.size(X) == X.shape[0]:
        X = np.reshape(X, (np.size(X), 1))
    try:
        eps = float(eps)
    except:
        "eps cannot be cast to a float"
    if np.isnan(eps):
        raise ValueError('eps is nan')
    if np.isinf(eps):
        raise ValueError('eps is inf')
    dist = euclidean_distance(X)
    dist = dist * (dist < eps)

    # this would is just for numerical reasons
    dist -= np.diag(np.diag(dist))
    return wgraph_from_adjacency(dist)
Ejemplo n.º 2
0
def knn(X, k=1):
    """returns the k-nearest-neighbours graph of the data

    Parameters
    ----------
    X, array of shape (n_samples, n_features): the input data
    k, int, optional:  is the number of neighbours considered

    Returns
    -------
    the corresponding WeightedGraph instance

    Note
    ----
    The knn system is symmeterized: if (ab) is one of the edges
    then (ba) is also included
    """
    from nipy.algorithms.routines.fast_distance import euclidean_distance

    if np.size(X) == X.shape[0]:
        X = np.reshape(X, (np.size(X), 1))
    try:
        k = int(k)
    except:
        "k cannot be cast to an int"
    if np.isnan(k):
        raise ValueError('k is nan')
    if np.isinf(k):
        raise ValueError('k is inf')
    k = min(k, X.shape[0] - 1)

    # create the distance matrix
    dist = euclidean_distance(X)
    sorted_dist = dist.copy()
    sorted_dist.sort(0)

    # neighbour system
    bool_knn = dist < sorted_dist[k + 1]
    bool_knn += bool_knn.T
    bool_knn -= np.diag(np.diag(bool_knn))
    dist *= (bool_knn > 0)
    return wgraph_from_adjacency(dist)