ó
cÂY]c           @  sÊ  d  Z  d d l m Z d d l Z d d l Z d d l Z d d l Z d d l m Z d d l m	 Z	 m
 Z
 m Z d d l m Z m Z m Z m Z m Z m Z d d l Z d d l m Z d d	 l m Z d d l Z d d
 l m Z e d d d d g ƒ Z d d „ Z d d „ Z d d e e d d d d „ Z  d „  Z! e" d „ Z# e" d „ Z$ e" d „ Z% d e" d „ Z& e" d „ Z' e" d „ Z( e" d „ Z) d „  Z* d „  Z+ d „  Z, d  „  Z- d d! „ Z. d S("   s   
Base IO code for all datasets
iÿÿÿÿ(   t   print_functionN(   t
   namedtuple(   t   environt   listdirt   makedirs(   t   dirnamet   existst
   expandusert   isdirt   joint   splitexti   (   t   Bunch(   t   check_random_state(   t   urlretrievet   RemoteFileMetadatat   filenamet   urlt   checksumc         C  sS   |  d k r* t j d t d d ƒ ƒ }  n  t |  ƒ }  t |  ƒ sO t |  ƒ n  |  S(   ss  Return the path of the scikit-learn data dir.

    This folder is used by some large dataset loaders to avoid downloading the
    data several times.

    By default the data dir is set to a folder named 'scikit_learn_data' in the
    user home folder.

    Alternatively, it can be set by the 'SCIKIT_LEARN_DATA' environment
    variable or programmatically by giving an explicit folder path. The '~'
    symbol is expanded to the user home folder.

    If the folder does not already exist, it is automatically created.

    Parameters
    ----------
    data_home : str | None
        The path to scikit-learn data dir.
    t   SCIKIT_LEARN_DATAt   ~t   scikit_learn_dataN(   t   NoneR   t   getR	   R   R   R   (   t	   data_home(    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   get_data_home   s    	c         C  s   t  |  ƒ }  t j |  ƒ d S(   s˜   Delete all the content of the data home cache.

    Parameters
    ----------
    data_home : str | None
        The path to scikit-learn data dir.
    N(   R   t   shutilt   rmtree(   R   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   clear_data_home<   s    t   stricti    c         C  s8  g  } g  }	 g  }
 g  t  t |  ƒ ƒ D]! } t t |  | ƒ ƒ r% | ^ q% } | d k	 r€ g  | D] } | | k r_ | ^ q_ } n  x‹ t | ƒ D]} \ } } |	 j | ƒ t |  | ƒ } g  t  t | ƒ ƒ D] } t | | ƒ ^ qÈ } | j t | ƒ | g ƒ |
 j | ƒ q Wt	 j
 |
 ƒ }
 t	 j
 | ƒ } | rxt | ƒ } t	 j |
 j d ƒ } | j | ƒ |
 | }
 | | } n  | rg  } x9 |
 D]1 } t | d ƒ  } | j | j ƒ  ƒ Wd QXq‹W| d k	 rôg  | D] } | j | | ƒ ^ qÓ} n  t d | d |
 d |	 d | d | ƒ St d |
 d |	 d | d | ƒ S(	   s“  Load text files with categories as subfolder names.

    Individual samples are assumed to be files stored a two levels folder
    structure such as the following:

        container_folder/
            category_1_folder/
                file_1.txt
                file_2.txt
                ...
                file_42.txt
            category_2_folder/
                file_43.txt
                file_44.txt
                ...

    The folder names are used as supervised signal label names. The individual
    file names are not important.

    This function does not try to extract features into a numpy array or scipy
    sparse matrix. In addition, if load_content is false it does not try to
    load the files in memory.

    To use text files in a scikit-learn classification or clustering algorithm,
    you will need to use the `sklearn.feature_extraction.text` module to build
    a feature extraction transformer that suits your problem.

    If you set load_content=True, you should also specify the encoding of the
    text using the 'encoding' parameter. For many modern text files, 'utf-8'
    will be the correct encoding. If you leave encoding equal to None, then the
    content will be made of bytes instead of Unicode, and you will not be able
    to use most functions in `sklearn.feature_extraction.text`.

    Similar feature extractors should be built for other kind of unstructured
    data input such as images, audio, video, ...

    Read more in the :ref:`User Guide <datasets>`.

    Parameters
    ----------
    container_path : string or unicode
        Path to the main folder holding one subfolder per category

    description : string or unicode, optional (default=None)
        A paragraph describing the characteristic of the dataset: its source,
        reference, etc.

    categories : A collection of strings or None, optional (default=None)
        If None (default), load all the categories. If not None, list of
        category names to load (other categories ignored).

    load_content : boolean, optional (default=True)
        Whether to load or not the content of the different files. If true a
        'data' attribute containing the text information is present in the data
        structure returned. If not, a filenames attribute gives the path to the
        files.

    shuffle : bool, optional (default=True)
        Whether or not to shuffle the data: might be important for models that
        make the assumption that the samples are independent and identically
        distributed (i.i.d.), such as stochastic gradient descent.

    encoding : string or None (default is None)
        If None, do not try to decode the content of the files (e.g. for images
        or other non-text content). If not None, encoding to use to decode text
        files to Unicode if load_content is True.

    decode_error : {'strict', 'ignore', 'replace'}, optional
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. Passed as keyword
        argument 'errors' to bytes.decode.

    random_state : int, RandomState instance or None (default=0)
        Determines random number generation for dataset shuffling. Pass an int
        for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are: either
        data, the raw text data to learn, or 'filenames', the files
        holding it, 'target', the classification labels (integer index),
        'target_names', the meaning of the labels, and 'DESCR', the full
        description of the dataset.
    i    t   rbNt   datat	   filenamest   target_namest   targett   DESCR(   t   sortedR   R   R	   R   t	   enumeratet   appendt   extendt   lent   npt   arrayR   t   aranget   shapet   shufflet   opent   readt   decodeR   (   t   container_patht   descriptiont
   categoriest   load_contentR,   t   encodingt   decode_errort   random_stateR!   R    R   t   ft   folderst   labelt   foldert   folder_patht   dt	   documentst   indicesR   R   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt
   load_filesH   sL    Y!(+
(c      	   C  s	  t  t |  d | ƒ ƒ â } t j | ƒ } t | ƒ } t | d ƒ } t | d ƒ } t j | d ƒ } t j | | f ƒ } t j | f d t j ƒ}	 xZ t	 | ƒ D]L \ }
 } t j
 | d  d t j ƒ| |
 <t j
 | d d t j ƒ|	 |
 <q¦ WWd QX| |	 | f S(   s  Loads data from module_path/data/data_file_name.

    Parameters
    ----------
    module_path : string
        The module path.

    data_file_name : string
        Name of csv file to be loaded from
        module_path/data/data_file_name. For example 'wine_data.csv'.

    Returns
    -------
    data : Numpy array
        A 2D array with each row representing one sample and each column
        representing the features of a given sample.

    target : Numpy array
        A 1D array holding target variables for all the samples in `data.
        For example target[0] is the target varible for data[0].

    target_names : Numpy array
        A 1D array containing the names of the classifications. For example
        target_names[0] is the name of the target[0] class.
    R   i    i   i   t   dtypeiÿÿÿÿN(   R-   R	   t   csvt   readert   nextt   intR(   R)   t   emptyR$   t   asarrayt   float64(   t   module_patht   data_file_namet   csv_filet	   data_filet   tempt	   n_samplest
   n_featuresR    R   R!   t   it   ir(    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt	   load_dataÑ   s     *c         C  s­   t  t ƒ } t | d ƒ \ } } } t t | d d ƒ ƒ  } | j ƒ  } Wd QX|  ra | | f St d | d | d | d | d	 d
 d d d d d d d d d d d d g ƒ S(   sY  Load and return the wine dataset (classification).

    .. versionadded:: 0.18

    The wine dataset is a classic and very easy multi-class classification
    dataset.

    =================   ==============
    Classes                          3
    Samples per class        [59,71,48]
    Samples total                  178
    Dimensionality                  13
    Features            real, positive
    =================   ==============

    Read more in the :ref:`User Guide <wine_dataset>`.

    Parameters
    ----------
    return_X_y : boolean, default=False.
        If True, returns ``(data, target)`` instead of a Bunch object.
        See below for more information about the `data` and `target` object.

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are: 'data', the
        data to learn, 'target', the classification labels, 'target_names', the
        meaning of the labels, 'feature_names', the meaning of the features,
        and 'DESCR', the full description of the dataset.

    (data, target) : tuple if ``return_X_y`` is True

    The copy of UCI ML Wine Data Set dataset is downloaded and modified to fit
    standard format from:
    https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data

    Examples
    --------
    Let's say you are interested in the samples 10, 80, and 140, and want to
    know their class name.

    >>> from sklearn.datasets import load_wine
    >>> data = load_wine()
    >>> data.target[[10, 80, 140]]
    array([0, 1, 2])
    >>> list(data.target_names)
    ['class_0', 'class_1', 'class_2']
    s   wine_data.csvt   descrs   wine_data.rstNR   R!   R    R"   t   feature_namest   alcoholt
   malic_acidt   asht   alcalinity_of_asht	   magnesiumt   total_phenolst
   flavanoidst   nonflavanoid_phenolst   proanthocyaninst   color_intensityt   hues   od280/od315_of_diluted_winest   proline(   R   t   __file__RQ   R-   R	   R.   R   (   t
   return_X_yRH   R   R!   R    t   rst_filet   fdescr(    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt	   load_wineû   s,    2
c         C  sª   t  t ƒ } t | d ƒ \ } } } t | d d ƒ } t t | d d ƒ ƒ  } | j ƒ  } Wd QX|  rs | | f St d | d | d | d | d	 d
 d d d g d | ƒ S(   s  Load and return the iris dataset (classification).

    The iris dataset is a classic and very easy multi-class classification
    dataset.

    =================   ==============
    Classes                          3
    Samples per class               50
    Samples total                  150
    Dimensionality                   4
    Features            real, positive
    =================   ==============

    Read more in the :ref:`User Guide <iris_dataset>`.

    Parameters
    ----------
    return_X_y : boolean, default=False.
        If True, returns ``(data, target)`` instead of a Bunch object. See
        below for more information about the `data` and `target` object.

        .. versionadded:: 0.18

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn, 'target', the classification labels,
        'target_names', the meaning of the labels, 'feature_names', the
        meaning of the features, 'DESCR', the full description of
        the dataset, 'filename', the physical location of
        iris csv dataset (added in version `0.20`).

    (data, target) : tuple if ``return_X_y`` is True

        .. versionadded:: 0.18

    Notes
    -----
        .. versionchanged:: 0.20
            Fixed two wrong data points according to Fisher's paper.
            The new version is the same as in R, but not as in the UCI
            Machine Learning Repository.

    Examples
    --------
    Let's say you are interested in the samples 10, 25, and 50, and want to
    know their class name.

    >>> from sklearn.datasets import load_iris
    >>> data = load_iris()
    >>> data.target[[10, 25, 50]]
    array([0, 0, 1])
    >>> list(data.target_names)
    ['setosa', 'versicolor', 'virginica']
    s   iris.csvR   RR   s   iris.rstNR!   R    R"   RS   s   sepal length (cm)s   sepal width (cm)s   petal length (cm)s   petal width (cm)R   (   R   R`   RQ   R	   R-   R.   R   (   Ra   RH   R   R!   R    t   iris_csv_filenameRb   Rc   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt	   load_irisH  s    9
c   	       C  s  t  t ƒ } t | d ƒ \ } } } t | d d ƒ } t t | d d ƒ ƒ  } | j ƒ  } Wd QXt j d d d d	 d
 d d d d d d d d d d d d d d d d d d d d d d  d! d" d# g ƒ } |  rÜ | | f St d | d$ | d% | d& | d' | d( | ƒ S()   sË  Load and return the breast cancer wisconsin dataset (classification).

    The breast cancer dataset is a classic and very easy binary classification
    dataset.

    =================   ==============
    Classes                          2
    Samples per class    212(M),357(B)
    Samples total                  569
    Dimensionality                  30
    Features            real, positive
    =================   ==============

    Read more in the :ref:`User Guide <breast_cancer_dataset>`.

    Parameters
    ----------
    return_X_y : boolean, default=False
        If True, returns ``(data, target)`` instead of a Bunch object.
        See below for more information about the `data` and `target` object.

        .. versionadded:: 0.18

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn, 'target', the classification labels,
        'target_names', the meaning of the labels, 'feature_names', the
        meaning of the features, and 'DESCR', the full description of
        the dataset, 'filename', the physical location of
        breast cancer csv dataset (added in version `0.20`).

    (data, target) : tuple if ``return_X_y`` is True

        .. versionadded:: 0.18

    The copy of UCI ML Breast Cancer Wisconsin (Diagnostic) dataset is
    downloaded from:
    https://goo.gl/U2Uwz2

    Examples
    --------
    Let's say you are interested in the samples 10, 50, and 85, and want to
    know their class name.

    >>> from sklearn.datasets import load_breast_cancer
    >>> data = load_breast_cancer()
    >>> data.target[[10, 50, 85]]
    array([0, 1, 0])
    >>> list(data.target_names)
    ['malignant', 'benign']
    s   breast_cancer.csvR   RR   s   breast_cancer.rstNs   mean radiuss   mean textures   mean perimeters	   mean areas   mean smoothnesss   mean compactnesss   mean concavitys   mean concave pointss   mean symmetrys   mean fractal dimensions   radius errors   texture errors   perimeter errors
   area errors   smoothness errors   compactness errors   concavity errors   concave points errors   symmetry errors   fractal dimension errors   worst radiuss   worst textures   worst perimeters
   worst areas   worst smoothnesss   worst compactnesss   worst concavitys   worst concave pointss   worst symmetrys   worst fractal dimensionR!   R    R"   RS   R   (	   R   R`   RQ   R	   R-   R.   R(   R)   R   (	   Ra   RH   R   R!   R    t   csv_filenameRb   Rc   RS   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_breast_cancer“  s6    6
i
   c   
      C  s%  t  t ƒ } t j t | d d ƒ d d ƒ} t t | d d ƒ ƒ  } | j ƒ  } Wd QX| d d … d f j t j ƒ } | d d … d d … f } | j	 ƒ  } d | _
 |  d
 k  rç | |  k  }	 | |	 | |	 } } | |	 } n  | r÷ | | f St d | d | d t j d
 ƒ d | d | ƒ S(   s  Load and return the digits dataset (classification).

    Each datapoint is a 8x8 image of a digit.

    =================   ==============
    Classes                         10
    Samples per class             ~180
    Samples total                 1797
    Dimensionality                  64
    Features             integers 0-16
    =================   ==============

    Read more in the :ref:`User Guide <digits_dataset>`.

    Parameters
    ----------
    n_class : integer, between 0 and 10, optional (default=10)
        The number of classes to return.

    return_X_y : boolean, default=False.
        If True, returns ``(data, target)`` instead of a Bunch object.
        See below for more information about the `data` and `target` object.

        .. versionadded:: 0.18

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn, 'images', the images corresponding
        to each sample, 'target', the classification labels for each
        sample, 'target_names', the meaning of the labels, and 'DESCR',
        the full description of the dataset.

    (data, target) : tuple if ``return_X_y`` is True

        .. versionadded:: 0.18

    This is a copy of the test set of the UCI ML hand-written digits datasets
    http://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits

    Examples
    --------
    To load the data and visualize the images::

        >>> from sklearn.datasets import load_digits
        >>> digits = load_digits()
        >>> print(digits.data.shape)
        (1797, 64)
        >>> import matplotlib.pyplot as plt #doctest: +SKIP
        >>> plt.gray() #doctest: +SKIP
        >>> plt.matshow(digits.images[0]) #doctest: +SKIP
        >>> plt.show() #doctest: +SKIP
    R   s   digits.csv.gzt	   delimitert   ,RR   s
   digits.rstNiÿÿÿÿi   i
   R!   R    t   imagesR"   (   iÿÿÿÿi   i   (   R   R`   R(   t   loadtxtR	   R-   R.   t   astypeRD   t   viewR+   R   R*   (
   t   n_classRa   RH   R   R7   RR   R!   t	   flat_dataRk   t   idx(    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_digitsê  s(    7	"	
c   	      C  sÝ   t  t ƒ } t | d ƒ } t | d ƒ } t j | ƒ } t | d ƒ } t j | ƒ } t t | d d ƒ ƒ  } | j ƒ  } Wd QX|  r” | | f St d | d | d | d	 d
 d d d d d d d d d g
 d | d | ƒ S(   s,  Load and return the diabetes dataset (regression).

    ==============      ==================
    Samples total       442
    Dimensionality      10
    Features            real, -.2 < x < .2
    Targets             integer 25 - 346
    ==============      ==================

    Read more in the :ref:`User Guide <diabetes_dataset>`.

    Parameters
    ----------
    return_X_y : boolean, default=False.
        If True, returns ``(data, target)`` instead of a Bunch object.
        See below for more information about the `data` and `target` object.

        .. versionadded:: 0.18

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn, 'target', the regression target for each
        sample, 'data_filename', the physical location
        of diabetes data csv dataset, and 'target_filename', the physical
        location of diabetes targets csv datataset (added in version `0.20`).

    (data, target) : tuple if ``return_X_y`` is True

        .. versionadded:: 0.18
    R   s   diabetes_data.csv.gzs   diabetes_target.csv.gzRR   s   diabetes.rstNR!   R"   RS   t   aget   sext   bmit   bpt   s1t   s2t   s3t   s4t   s5t   s6t   data_filenamet   target_filename(   R   R`   R	   R(   Rl   R-   R.   R   (	   Ra   RH   t   base_dirR}   R   R~   R!   Rb   Rc   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_diabetes:  s    !
c   
      C  s  t  t t ƒ d ƒ } t  | d ƒ } t  | d ƒ } t j | d d ƒ} t j | d d ƒ} t | ƒ  } | j ƒ  j ƒ  } Wd QXt | ƒ  } | j ƒ  j ƒ  } Wd QXt t t ƒ d ƒ  } | j ƒ  }	 Wd QX|  ræ | | f St	 d | d	 | d
 | d | d |	 d | d | ƒ S(   s
  Load and return the linnerud dataset (multivariate regression).

    ==============    ============================
    Samples total     20
    Dimensionality    3 (for both data and target)
    Features          integer
    Targets           integer
    ==============    ============================

    Read more in the :ref:`User Guide <linnerrud_dataset>`.

    Parameters
    ----------
    return_X_y : boolean, default=False.
        If True, returns ``(data, target)`` instead of a Bunch object.
        See below for more information about the `data` and `target` object.

        .. versionadded:: 0.18

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are: 'data' and
        'targets', the two multivariate datasets, with 'data' corresponding to
        the exercise and 'targets' corresponding to the physiological
        measurements, as well as 'feature_names' and 'target_names'.
        In addition, you will also have access to 'data_filename',
        the physical location of linnerud data csv dataset, and
        'target_filename', the physical location of
        linnerud targets csv datataset (added in version `0.20`).

    (data, target) : tuple if ``return_X_y`` is True

        .. versionadded:: 0.18
    s   data/s   linnerud_exercise.csvs   linnerud_physiological.csvt   skiprowsi   Ns   /descr/linnerud.rstR   RS   R!   R    R"   R}   R~   (
   R	   R   R`   R(   Rl   R-   t   readlinet   splitR.   R   (
   Ra   R   R}   R~   t   data_exerciset   data_physiologicalR7   t   header_exerciset   header_physiologicalRR   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_linnerudo  s&    $
c         C  sy  t  t ƒ } t | d d ƒ } t | ƒ  } | j ƒ  } Wd QXt | d d ƒ } t | ƒ á } t j | ƒ } t | ƒ } t | d ƒ } t | d ƒ }	 t	 j
 | |	 f ƒ }
 t	 j
 | f ƒ } t | ƒ } t	 j | ƒ } xZ t | ƒ D]L \ } } t	 j | d  d	 t	 j ƒ|
 | <t	 j | d d	 t	 j ƒ| | <qê WWd QX|  rP|
 | f St d |
 d
 | d | d  d | d | ƒ S(   s  Load and return the boston house-prices dataset (regression).

    ==============     ==============
    Samples total                 506
    Dimensionality                 13
    Features           real, positive
    Targets             real 5. - 50.
    ==============     ==============

    Read more in the :ref:`User Guide <boston_dataset>`.

    Parameters
    ----------
    return_X_y : boolean, default=False.
        If True, returns ``(data, target)`` instead of a Bunch object.
        See below for more information about the `data` and `target` object.

        .. versionadded:: 0.18

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn, 'target', the regression targets,
        'DESCR', the full description of the dataset,
        and 'filename', the physical location of boston
        csv dataset (added in version `0.20`).

    (data, target) : tuple if ``return_X_y`` is True

        .. versionadded:: 0.18

    Notes
    -----
        .. versionchanged:: 0.20
            Fixed a wrong data point at [445, 0].

    Examples
    --------
    >>> from sklearn.datasets import load_boston
    >>> boston = load_boston()
    >>> print(boston.data.shape)
    (506, 13)
    RR   s   boston_house_prices.rstNR   s   boston_house_prices.csvi    i   iÿÿÿÿR@   R!   RS   R"   R   (   R   R`   R	   R-   R.   RA   RB   RC   RD   R(   RE   R)   R$   RF   RG   R   (   Ra   RH   t   fdescr_nameR7   t
   descr_textRI   RK   RL   RM   RN   R   R!   RS   RO   R<   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_boston¯  s0    - *

c          C  sÁ   d d l  m }  t t t ƒ d ƒ } t t | d ƒ ƒ  } | j ƒ  } Wd QXg  t j | ƒ D]$ } | j	 d ƒ r_ t | | ƒ ^ q_ } g  | D] } |  | ƒ ^ q } t
 d | d | d | ƒ S(	   s_  Load sample images for image manipulation.

    Loads both, ``china`` and ``flower``.

    Read more in the :ref:`User Guide <sample_images>`.

    Returns
    -------
    data : Bunch
        Dictionary-like object with the following attributes : 'images', the
        two sample images, 'filenames', the file names for the images, and
        'DESCR' the full description of the dataset.

    Examples
    --------
    To load the data and visualize the images:

    >>> from sklearn.datasets import load_sample_images
    >>> dataset = load_sample_images()     #doctest: +SKIP
    >>> len(dataset.images)                #doctest: +SKIP
    2
    >>> first_img_data = dataset.images[0] #doctest: +SKIP
    >>> first_img_data.shape               #doctest: +SKIP
    (427, 640, 3)
    >>> first_img_data.dtype               #doctest: +SKIP
    dtype('uint8')
    i   (   t   imreadRk   s
   README.txtNs   .jpgR   R"   (   t   externals._pilutilRŒ   R	   R   R`   R-   R.   t   osR   t   endswithR   (   RŒ   RH   R7   RR   R   R   Rk   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_sample_imagesü  s    $c         C  sr   t  ƒ  } d } x6 t | j ƒ D]% \ } } | j |  ƒ r | } Pq q W| d k rg t d |  ƒ ‚ n  | j | S(   su  Load the numpy array of a single sample image

    Read more in the :ref:`User Guide <sample_images>`.

    Parameters
    -----------
    image_name : {`china.jpg`, `flower.jpg`}
        The name of the sample image loaded

    Returns
    -------
    img : 3D array
        The image as a numpy array: height x width x color

    Examples
    ---------

    >>> from sklearn.datasets import load_sample_image
    >>> china = load_sample_image('china.jpg')   # doctest: +SKIP
    >>> china.dtype                              # doctest: +SKIP
    dtype('uint8')
    >>> china.shape                              # doctest: +SKIP
    (427, 640, 3)
    >>> flower = load_sample_image('flower.jpg') # doctest: +SKIP
    >>> flower.dtype                             # doctest: +SKIP
    dtype('uint8')
    >>> flower.shape                             # doctest: +SKIP
    (427, 640, 3)
    s   Cannot find sample image: %sN(   R   R   R$   R   R   t   AttributeErrorRk   (   t
   image_nameRk   t   indexRO   R   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   load_sample_image)  s    	c          O  sg   | j  d d ƒ } t |  d ƒ \ } } t j d d k rH | | 7} n  |  d  | | f } t | Œ  S(   s†  Ensure different filenames for Python 2 and Python 3 pickles

    An object pickled under Python 3 cannot be loaded under Python 2. An object
    pickled under Python 2 can sometimes not be loaded correctly under Python 3
    because some Python 2 strings are decoded as Python 3 strings which can be
    problematic for objects that use Python 2 strings as byte buffers for
    numerical data instead of "real" strings.

    Therefore, dataset loaders in scikit-learn use different files for pickles
    manages by Python 2 and Python 3 in the same SCIKIT_LEARN_DATA folder so as
    to avoid conflicts.

    args[-1] is expected to be the ".pkl" filename. Under Python 3, a suffix is
    inserted before the extension to s

    _pkl_filepath('/path/to/folder', 'filename.pkl') returns:
      - /path/to/folder/filename.pkl under Python 2
      - /path/to/folder/filename_py3.pkl under Python 3+

    t
   py3_suffixt   _py3iÿÿÿÿi    i   (   R   R
   t   syst   version_infoR	   (   t   argst   kwargsR•   t   basenamet   extt   new_args(    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   _pkl_filepathR  s    c         C  sg   t  j ƒ  } d } t |  d ƒ : } x0 t rV | j | ƒ } | sF Pn  | j | ƒ q' WWd QX| j ƒ  S(   s.   Calculate the sha256 hash of the file at path.i    R   N(   t   hashlibt   sha256R-   t   TrueR.   t   updatet	   hexdigest(   t   patht
   sha256hasht
   chunk_sizeR7   t   buffer(    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   _sha256o  s    	c         C  sw   | d k r |  j n t | |  j ƒ } t |  j | ƒ t | ƒ } |  j | k rs t d j | | |  j ƒ ƒ ‚ n  | S(   s  Helper function to download a remote dataset into path

    Fetch a dataset pointed by remote's url, save into path using remote's
    filename and ensure its integrity based on the SHA256 Checksum of the
    downloaded file.

    Parameters
    -----------
    remote : RemoteFileMetadata
        Named tuple containing remote dataset meta information: url, filename
        and checksum

    dirname : string
        Directory to save the file to.

    Returns
    -------
    file_path: string
        Full path of the created file.
    sS   {} has an SHA256 checksum ({}) differing from expected ({}), file may be corrupted.N(	   R   R   R	   R   R   R¨   R   t   IOErrort   format(   t   remoteR   t	   file_pathR   (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   _fetch_remote|  s    	(/   t   __doc__t
   __future__R    RŽ   RA   R—   R   t   collectionsR   R   R   R   t   os.pathR   R   R   R   R	   R
   RŸ   t   utilsR   R   t   numpyR(   t*   sklearn.externals.six.moves.urllib.requestR   R   R   R   R   R¡   R?   RQ   t   FalseRd   Rf   Rh   Rr   R€   Rˆ   R‹   R   R”   Rž   R¨   R­   (    (    (    s4   lib/python2.7/site-packages/sklearn/datasets/base.pyt   <module>   sB   .	‡	*MKWP5@M	-	)		