ó
‡ˆ\c           @   s#  d  Z  d d l Z d d l Z d d l m Z d d l m Z m Z d d l m	 Z	 d d l
 m Z d d	 l m Z d d
 l m Z d d l m Z d g Z d Z e j e ƒ j d Z d „  Z d „  Z d e f d „  ƒ  YZ d e e f d „  ƒ  YZ d „  Z d e	 e e f d „  ƒ  YZ d S(   s#   Approximate nearest neighbor searchiÿÿÿÿN(   t   sparsei   (   t   KNeighborsMixint   RadiusNeighborsMixini   (   t   BaseEstimator(   t   check_array(   t   check_random_state(   t   pairwise_distances(   t   GaussianRandomProjectiont	   LSHForests   >u4i   c         C   s<   t  j |  | | @ƒ } t  j |  | | Bd d ƒ} | | f S(   s³   Finds indices in sorted array of integers.

    Most significant h bits in the binary representations of the
    integers are matched with the items' most significant h bits.
    t   sidet   right(   t   npt   searchsorted(   t   treet   bin_Xt	   left_maskt
   right_maskt
   left_indext   right_index(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _find_matching_indices   s    	c         C   sz  t  j | d t  j ƒ} | j | ƒ t  j | d t  j ƒ} t  j | d t  j ƒ} t |  | | | | | ƒ \ } }	 |	 | k }
 | | |
 <| |
 <t  j | j d ƒ } | | | k  } x· | j d ru| j | ƒ | j | ƒ d } t |  | j | ƒ | | | | ƒ \ } }	 |	 | k }
 | |
 } | d | | |
 <| | | |
 <| |
 | | |
 <| | | k  } q¿ W| S(   s{   Find the longest prefix match in tree for each query in bin_X

    Most significant bits are considered as the prefix.
    t   dtypei    i   i   (	   R   t
   empty_liket   intpt   fillt
   zeros_likeR   t   aranget   shapet   take(   R   R   t	   hash_sizet
   left_maskst   right_maskst   hit   lot   rest   left_idxt	   right_idxt   foundt   rt   keptt   midt	   mid_found(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _find_longest_prefix_match$   s0    	 
t   ProjectionToHashMixinc           B   s2   e  Z d  Z e d „  ƒ Z d d „ Z d „  Z RS(   s0   Turn a transformed real-valued array into a hashc         C   sg   |  j  d d d k r& t d ƒ ‚ n  t j |  d k j t ƒ ƒ j d t ƒ } | j |  j  d d ƒ S(   Ni   i   i    s@   Require reduced dimensionality to be a multiple of 8 for hashingR   iÿÿÿÿ(	   R   t
   ValueErrorR   t   packbitst   astypet   intt   viewt
   HASH_DTYPEt   reshape(   t	   projectedt   out(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _to_hashK   s    *c         C   s   |  j  | ƒ |  j | ƒ S(   sæ   
        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.
        (   t   fitt	   transform(   t   selft   Xt   y(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   fit_transformT   s    	c         C   s   |  j  t t |  ƒ j | ƒ ƒ S(   sæ   
        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of predictors.
        (   R4   t   superR*   R6   (   R7   R8   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyR6   `   s    N(   t   __name__t
   __module__t   __doc__t   staticmethodR4   t   NoneR:   R6   (    (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyR*   I   s   	t   GaussianRandomProjectionHashc           B   s   e  Z d  Z d d d „ Z RS(   s  Use GaussianRandomProjection to produce a cosine LSH fingerprint

    Parameters
    ----------

    n_components : int or 'auto', optional (default = 32)
        Dimensionality of the target projection space.

        n_components can be automatically adjusted according to the
        number of samples in the dataset and the bound given by the
        Johnson-Lindenstrauss lemma. In that case the quality of the
        embedding is controlled by the ``eps`` parameter.

        It should be noted that Johnson-Lindenstrauss lemma can yield
        very conservative estimated of the required number of components
        as it makes no assumption on the structure of the dataset.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.
    i    c         C   s#   t  t |  ƒ j d | d | ƒ d  S(   Nt   n_componentst   random_state(   R;   RA   t   __init__(   R7   RB   RC   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyRD   „   s    N(   R<   R=   R>   R@   RD   (    (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyRA   k   s   c         C   s&   t  j t |  ƒ d t ƒ} |  | (| S(   s.   Creates an array of array from list of arrays.R   (   R   t   emptyt   lent   object(   t   list_of_arraysR3   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _array_of_arraysŒ   s    c           B   s   e  Z d  Z d d d d d d d d „ Z d „  Z d	 „  Z d
 „  Z d „  Z d d „ Z	 d „  Z
 d e d „ Z d e d „ Z d d „ Z RS(   sž  Performs approximate nearest neighbor search using LSH forest.

    LSH Forest: Locality Sensitive Hashing forest [1] is an alternative
    method for vanilla approximate nearest neighbor search methods.
    LSH forest data structure has been implemented using sorted
    arrays and binary search and 32 bit fixed-length hashes.
    Random projection is used as the hash family which approximates
    cosine distance.

    The cosine distance is defined as ``1 - cosine_similarity``: the lowest
    value is 0 (identical point) but it is bounded above by 2 for the farthest
    points. Its value does not depend on the norm of the vector points but
    only on their relative angles.

    Parameters
    ----------

    n_estimators : int (default = 10)
        Number of trees in the LSH Forest.

    radius : float, optinal (default = 1.0)
        Radius from the data point to its neighbors. This is the parameter
        space to use by default for the :meth:`radius_neighbors` queries.

    n_candidates : int (default = 50)
        Minimum number of candidates evaluated per estimator, assuming enough
        items meet the `min_hash_match` constraint.

    n_neighbors : int (default = 5)
        Number of neighbors to be returned from query function when
        it is not provided to the :meth:`kneighbors` method.

    min_hash_match : int (default = 4)
        lowest hash length to be searched when candidate selection is
        performed for nearest neighbors.

    radius_cutoff_ratio : float, optional (default = 0.9)
        A value ranges from 0 to 1. Radius neighbors will be searched until
        the ratio between total neighbors within the radius and the total
        candidates becomes less than this value unless it is terminated by
        hash length reaching `min_hash_match`.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Attributes
    ----------

    hash_functions_ : list of GaussianRandomProjectionHash objects
        Hash function g(p,x) for a tree is an array of 32 randomly generated
        float arrays with the same dimension as the data set. This array is
        stored in GaussianRandomProjectionHash object and can be obtained
        from ``components_`` attribute.

    trees_ : array, shape (n_estimators, n_samples)
        Each tree (corresponding to a hash function) contains an array of
        sorted hashed values. The array representation may change in future
        versions.

    original_indices_ : array, shape (n_estimators, n_samples)
        Original indices of sorted hashed values in the fitted index.

    References
    ----------

    .. [1] M. Bawa, T. Condie and P. Ganesan, "LSH Forest: Self-Tuning
           Indexes for Similarity Search", WWW '05 Proceedings of the
           14th international conference on World Wide Web,  651-660,
           2005.

    Examples
    --------
      >>> from sklearn.neighbors import LSHForest

      >>> X_train = [[5, 5, 2], [21, 5, 5], [1, 1, 1], [8, 9, 1], [6, 10, 2]]
      >>> X_test = [[9, 1, 6], [3, 1, 10], [7, 10, 3]]
      >>> lshf = LSHForest(random_state=42)  # doctest: +SKIP
      >>> lshf.fit(X_train)  # doctest: +SKIP
      LSHForest(min_hash_match=4, n_candidates=50, n_estimators=10,
                n_neighbors=5, radius=1.0, radius_cutoff_ratio=0.9,
                random_state=42)
      >>> distances, indices = lshf.kneighbors(X_test, n_neighbors=2)
      ... # doctest: +SKIP
      >>> distances                                        # doctest: +SKIP
      array([[0.069..., 0.149...],
             [0.229..., 0.481...],
             [0.004..., 0.014...]])
      >>> indices  # doctest: +SKIP
      array([[1, 2],
             [2, 0],
             [4, 0]])

    i
   g      ð?i2   i   i   gÍÌÌÌÌÌì?c         C   sS   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ t j d t	 ƒ d  S(   Nsc   LSHForest has poor performance and has been deprecated in 0.19. It will be removed in version 0.21.(
   t   n_estimatorst   radiusRC   t   n_candidatest   n_neighborst   min_hash_matcht   radius_cutoff_ratiot   warningst   warnt   DeprecationWarning(   R7   RJ   RK   RL   RM   RN   RO   RC   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyRD   õ   s    								c         C   sÇ   | j  d k r: t j d d t j ƒt j d d t ƒf St j |  j ƒ r\ |  j | } n |  j j | d d d d ƒ} t	 | | d d ƒd } t j
 | ƒ } | j | d d d d ƒ} | | f S(	   sÈ   Computes the cosine distance.

        Distance is from the query to points in the candidates array.
        Returns argsort of distances in the candidates
        array and sorted distances.
        i    R   t   axist   modet   clipt   metrict   cosine(   i    (   R   R   RE   R.   t   floatR    t   issparset   _fit_XR   R   t   argsort(   R7   t   queryt
   candidatest   candidate_Xt	   distancest   distance_positions(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _compute_distances  s    +c         C   s¦   t  d } t j t j | | f d t ƒƒ d d … d d … f } | d d d … d d d … f } t j | ƒ j d t ƒ |  _ t j | ƒ j d t ƒ |  _	 d S(   s2   Creates left and right masks for all hash lengths.i   R   Niÿÿÿÿ(
   t   MAX_HASH_SIZER   t   trilt   onesR.   R,   R/   R0   t
   _left_maskt   _right_mask(   R7   t   tri_sizeR   R   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _generate_masks  s
    
:"c         C   sÉ  |  j  j d } d } t ƒ  } |  j |  j } xÄ | |  j k rõ | | k  s_ t | ƒ | k  rõ |  j | }	 |  j | }
 xl t	 |  j ƒ D][ } t
 |  j | | | |	 |
 ƒ \ } } | | | 7} | j |  j | | | !j ƒ  ƒ q‰ W| d 8} q2 Wt j | d t | ƒ d t j ƒ} | j d | k  r’t j d | |  j f ƒ t j t j d | ƒ | ƒ } | | j d } t j | | |  f ƒ } n  |  j | | j t ƒ ƒ \ } } | | |  | |  f S(   s‡   Performs the Synchronous ascending phase.

        Returns an array of candidates, their distance ranks and
        distances.
        i    i   t   countR   s•   Number of candidates is not sufficient to retrieve %i neighbors with min_hash_match = %i. Candidates are filled up uniformly from unselected indices.(   RZ   R   t   setRL   RJ   RN   RF   Re   Rf   t   rangeR   t   trees_t   updatet   original_indices_t   tolistR   t   fromiterR   RP   RQ   t	   setdiff1dR   t   concatenateRa   R-   R.   (   R7   R\   t	   max_deptht   bin_queriesRM   t
   index_sizeRL   t   candidate_sett   min_candidatesR   R   t   it   startt   stopR]   t	   remainingt   to_fillt   ranksR_   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _get_candidates#  s<    		c         C   sÇ  d } d |  j  } t j g  d t ƒ} t j g  d t ƒ} t j g  d t ƒ}	 xh| |  j k r¼| | k r¼|  j | }
 |  j | } g  } x^ t |  j	 ƒ D]M } t
 |  j | | | |
 | ƒ \ } } | j |  j | | | !j ƒ  ƒ q  Wt j | | ƒ } t j | | ƒ } |  j | | ƒ \ } } t j | | d d ƒ} t j |	 | |  ƒ } t j | | | | |  ƒ } t j |	 | | |  ƒ }	 | j d t | j d ƒ } | d } qU W| |	 f S(   sª   Finds radius neighbors from the candidates obtained.

        Their distances from query are smaller than radius.
        Returns radius neighbors and distances.
        i   R   R	   R
   i    (   RO   R   t   arrayR.   RX   RN   Re   Rf   Rk   RJ   R   Rl   t   extendRn   Ro   Rq   t   appendRa   R   t   insertR   (   R7   R\   Rs   Rt   RK   t   ratio_within_radiust	   thresholdt   total_candidatest   total_neighborst   total_distancesR   R   R]   Rx   Ry   Rz   R}   R_   t   mt	   positions(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _get_radius_neighborsT  s:    
c   
      C   s  t  | d d ƒ|  _ g  |  _ g  |  _ g  |  _ t |  j ƒ } t j t j	 ƒ j
 } x t |  j ƒ D]Œ } t t | j d | ƒ ƒ } | j |  j ƒ d d … d f } t j | ƒ } | | }	 |  j j | ƒ |  j j |	 ƒ |  j j | ƒ qd W|  j ƒ  |  S(   s{  Fit the LSH forest on the data.

        This creates binary hashes of input data points by getting the
        dot product of input points and hash_function then
        transforming the projection into a binary string array based
        on the sign (positive/negative) of the projection.
        A sorted array of binary hashes is created.

        Parameters
        ----------
        X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single data point.

        Returns
        -------
        self : object
        t   accept_sparset   csri    N(   R   RZ   t   hash_functions_Rl   Rn   R   RC   R   t   iinfot   int32t   maxRk   RJ   RA   Rb   t   randintR:   R[   R   Rh   (
   R7   R8   R9   t   rngt   int_maxRx   t   hashert   hashest   original_indext
   bin_hashes(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyR5   y  s"    			"

c         C   s¸   t  j g  |  j D]% } | j | ƒ d d … d f ^ q ƒ } t  j | d ƒ } g  t |  j t  j | d ƒ ƒ D]* \ } } t | | t |  j	 |  j
 ƒ ^ qo } | t  j | d d ƒf S(   s0   Performs descending phase to find maximum depth.Ni    i   RS   (   R   t   asarrayR   R6   t   rollaxist   zipRl   R)   Rb   Re   Rf   R   (   R7   R8   R”   Rt   R   t   tree_queriest   depths(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   _query©  s    	5	Cc         C   s  t  |  d ƒ s t d ƒ ‚ n  | d k r6 |  j } n  t | d d ƒ} g  g  } } |  j | ƒ \ } } xb t | j d ƒ D]M } |  j | | g | | | | | ƒ \ }	 }
 | j	 |	 ƒ | j	 |
 ƒ q~ W| rñ t
 j | ƒ t
 j | ƒ f St
 j | ƒ Sd S(   s²  Returns n_neighbors of approximate nearest neighbors.

        Parameters
        ----------
        X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
            List of n_features-dimensional data points.  Each row
            corresponds to a single query.

        n_neighbors : int, optional (default = None)
            Number of neighbors required. If not provided, this will
            return the number specified at the initialization.

        return_distance : boolean, optional (default = True)
            Returns the distances of neighbors if set to True.

        Returns
        -------
        dist : array, shape (n_samples, n_neighbors)
            Array representing the cosine distances to each point,
            only present if return_distance=True.

        ind : array, shape (n_samples, n_neighbors)
            Indices of the approximate nearest points in the population
            matrix.
        R   s   estimator should be fitted.R‹   RŒ   i    N(   t   hasattrR+   R@   RM   R   R   Rk   R   R~   R   R   R   (   R7   R8   RM   t   return_distancet	   neighborsR_   Rt   Rs   Rx   t   neighst   dists(    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt
   kneighbors¸  s     c         C   sù   t  |  d ƒ s t d ƒ ‚ n  | d k r6 |  j } n  t | d d ƒ} g  g  } } |  j | ƒ \ } } xb t | j d ƒ D]M } |  j | | g | | | | | ƒ \ }	 }
 | j	 |	 ƒ | j	 |
 ƒ q~ W| rë t
 | ƒ t
 | ƒ f St
 | ƒ Sd S(   sÁ  Finds the neighbors within a given radius of a point or points.

        Return the indices and distances of some points from the dataset
        lying in a ball with size ``radius`` around the points of the query
        array. Points lying on the boundary are included in the results.

        The result points are *not* necessarily sorted by distance to their
        query point.

        LSH Forest being an approximate method, some true neighbors from the
        indexed dataset might be missing from the results.

        Parameters
        ----------
        X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
            List of n_features-dimensional data points. Each row
            corresponds to a single query.

        radius : float
            Limiting distance of neighbors to return.
            (default is the value passed to the constructor).

        return_distance : boolean, optional (default = False)
            Returns the distances of neighbors if set to True.

        Returns
        -------
        dist : array, shape (n_samples,) of arrays
            Each element is an array representing the cosine distances
            to some points found within ``radius`` of the respective query.
            Only present if ``return_distance=True``.

        ind : array, shape (n_samples,) of arrays
            Each element is an array of indices for neighbors within ``radius``
            of the respective query.
        R   s   estimator should be fitted.R‹   RŒ   i    N(   Rž   R+   R@   RK   R   R   Rk   R   RŠ   R   RI   (   R7   R8   RK   RŸ   R    R_   Rt   Rs   Rx   R¡   R¢   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   radius_neighborsé  s    %c         C   s  t  | d d ƒ} t |  d ƒ s. |  j | ƒ S| j d |  j j d k rZ t d ƒ ‚ n  | j d } |  j j d } x© t |  j ƒ D]˜ } |  j | j	 | ƒ d d … d f } |  j
 | j | ƒ } t j |  j
 | | | ƒ |  j
 | <t j |  j | | t j | | | ƒ ƒ |  j | <q‡ Wt j | ƒ sDt j |  j ƒ rbt j |  j | f ƒ |  _ n t j |  j | f ƒ |  _ |  S(   sQ  
        Inserts new data into the already fitted LSH Forest.
        Cost is proportional to new total size, so additions
        should be batched.

        Parameters
        ----------
        X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
            New data point to be inserted into the LSH Forest.
        R‹   RŒ   R   i   s8   Number of features in X and fitted array does not match.i    N(   R   Rž   R5   R   RZ   R+   Rk   RJ   R   R6   Rl   R   R   R‚   Rn   R   R    RY   t   vstackt	   row_stack(   R7   R8   R9   t	   n_samplest	   n_indexedRx   R   R‰   (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   partial_fit$  s*    &	!N(   R<   R=   R>   R@   RD   Ra   Rh   R~   RŠ   R5   R   t   TrueR£   R¤   R©   (    (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyR   “   s   `				
	1	%0	1;(   R>   t   numpyR   RP   t   scipyR    t   baseR   R   R   t   utils.validationR   t   utilsR   t   metrics.pairwiseR   t   random_projectionR   t   __all__R0   R   t   itemsizeRb   R   R)   RG   R*   RA   RI   R   (    (    (    s<   lib/python2.7/site-packages/sklearn/neighbors/approximate.pyt   <module>   s&   			%" 	