
V[              	   @   s  d  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 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 d
 l m Z d d l m Z d d l Z d d l m Z Gd d   d e  Z d d d  Z d d d  Z d d d d d d d d d  Z d d   Z d d   Z d d d  Z d d    Z d! d"   Z d# d$   Z d% d&   Z d' d(   Z d) d*   Z  d S)+z
Base IO code for all datasets
    N)environ)dirname)join)exists)
expanduser)isdir)splitext)listdir)makedirs   )check_random_statec               @   sF   e  Z d  Z d Z d d   Z d d   Z d d   Z d d	   Z d
 S)BunchzContainer object for datasets

    Dictionary-like object that exposes its keys as attributes.

    >>> b = Bunch(a=1, b=2)
    >>> b['b']
    2
    >>> b.b
    2
    >>> b.a = 3
    >>> b['a']
    3
    >>> b.c = 6
    >>> b['c']
    6

    c             K   s   t  j |  |  d  S)N)dict__init__)selfkwargs r   P/s/python-3.5.2/amd64_ubu14/lib/python3.5/site-packages/sklearn/datasets/base.pyr   0   s    zBunch.__init__c             C   s   | |  | <d  S)Nr   )r   keyvaluer   r   r   __setattr__3   s    zBunch.__setattr__c             C   s1   y |  | SWn t  k
 r, t |   Yn Xd  S)N)KeyErrorAttributeError)r   r   r   r   r   __getattr__6   s    zBunch.__getattr__c             C   s   d  S)Nr   )r   stater   r   r   __setstate__<   s    	zBunch.__setstate__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r      s
   r   c             C   sM   |  d k r' t  j d t d d   }  t |   }  t |   sI t |   |  S)a  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.
    NZSCIKIT_LEARN_DATA~Zscikit_learn_data)r   getr   r   r   r
   )	data_homer   r   r   get_data_homeH   s    	
r#   c             C   s   t  |   }  t j |   d S)z.Delete all the content of the data home cache.N)r#   shutilrmtree)r"   r   r   r   clear_data_home`   s    r&   Tstrictc                s  g  } g  }	 g  }
  f d d   t  t    D }   d k	 r\   f d d   | D } x t |  D]t \ } } |	 j |  t  |    f d d   t  t    D } | j t |  | g  |
 j |  qi Wt j |
  }
 t j |  } | rHt	 |  } t j
 |
 j d  } | j |  |
 | }
 | | } | rg  } x: |
 D]2 } t | d   } | j | j    Wd QRXq[W d k	 r  f d d   | D } t d	 | d
 |
 d |	 d | d |  St d
 |
 d |	 d | d |  S)a  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.

    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.

    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.

    random_state : int, RandomState instance or None, optional (default=0)
        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`.

    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.
    c                s+   g  |  ]! } t  t   |   r |  q Sr   )r   r   ).0f)container_pathr   r   
<listcomp>   s   	 zload_files.<locals>.<listcomp>Nc                s"   g  |  ] } |   k r |  q Sr   r   )r(   r)   )
categoriesr   r   r+      s   	 c                s   g  |  ] } t    |   q Sr   )r   )r(   d)folder_pathr   r   r+      s   	r   rbc                s"   g  |  ] } | j       q Sr   )decode)r(   r-   )decode_errorencodingr   r   r+      s   	 data	filenamestarget_namestargetDESCR)sortedr	   	enumerateappendr   extendlennparrayr   arangeshapeshuffleopenreadr   )r*   descriptionr,   Zload_contentrA   r2   r1   Zrandom_stater6   r5   r4   ZfolderslabelZfolderZ	documentsindicesr3   filenamer)   r   )r,   r*   r1   r2   r.   r   
load_filesf   sJ    \%

rH   c              C   st  t  t  }  t t |  d d    } t j |  } t |  } t | d  } t | d  } t j	 | d d   } t j
 | | f  } t j
 | f d t j } x` t |  D]R \ }	 }
 t j |
 d d  d t j | |	 <t j |
 d d t j | |	 <q WWd QRXt t |  d d	    } | j   } Wd QRXt d | d
 | d | d | d d d d d g  S)ay  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 <datasets>`.

    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.

    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']
    r3   ziris.csvr      r   Ndtypedescrziris.rstr6   r5   r7   feature_nameszsepal length (cm)zsepal width (cm)zpetal length (cm)zpetal width (cm)rM   )r   __file__rB   r   csvreadernextintr=   r>   emptyr9   asarrayfloatrC   r   )module_pathcsv_file	data_filetemp	n_samples
n_featuresr5   r3   r6   iZirrst_filefdescrr   r   r   	load_iris   s&    %&+r_   c           -   C   s  t  t  }  t t |  d d    } t j |  } t |  } t | d  } t | d  } t j	 | d d   } t j
 | | f  } t j
 | f d t j } x` t |  D]R \ }	 }
 t j |
 d d-  d t j | |	 <t j |
 d. d t j | |	 <q WWd QRXt t |  d	 d
    } | j   } Wd QRXt 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  } t d | d) | d* | d+ | d, |  S)/a  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
    =================   ==============

    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.

    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']
    r3   zbreast_cancer.csvr   rI   r      rJ   NrK   zbreast_cancer.rstzmean radiuszmean texturezmean perimeterz	mean areazmean smoothnesszmean compactnesszmean concavityzmean concave pointszmean symmetryzmean fractal dimensionzradius errorztexture errorzperimeter errorz
area errorzsmoothness errorzcompactness errorzconcavity errorzconcave points errorzsymmetry errorzfractal dimension errorzworst radiuszworst texturezworst perimeterz
worst areazworst smoothnesszworst compactnesszworst concavityzworst concave pointszworst symmetryzworst fractal dimensionr6   r5   r7   rL   rM   rM   )r   rN   rB   r   rO   rP   rQ   rR   r=   r>   rS   r9   rT   rU   rC   r   )rV   rW   rX   
first_linerZ   r[   r5   r3   r6   countr   r]   r^   rL   r   r   r   load_breast_cancer/  sB    '&+rc   
   c       	      C   s  t  t  } t j t | d d  d d } t t | d d    } | j   } Wd QRX| d d  d f } | d d  d d  f } | j   } d | _ |  d
 k  r | |  k  } | | | | } } | | } t	 d | d | j
 t j  d t j d
  d | d |  S)a/  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 <datasets>`.

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

    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.

    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 pylab as pl #doctest: +SKIP
        >>> pl.gray() #doctest: +SKIP
        >>> pl.matshow(digits.images[0]) #doctest: +SKIP
        >>> pl.show() #doctest: +SKIP
    r3   zdigits.csv.gz	delimiter,rK   z
digits.rstNrI      rd   r6   r5   imagesr7   rM   rM   rM   )rM   rg   rg   )r   rN   r=   loadtxtr   rB   rC   viewr@   r   astyperR   r?   )	Zn_classrV   r3   r)   rK   r6   Z	flat_datarh   idxr   r   r   load_digits}  s$    *		
rm   c              C   sX   t  t t  d  }  t j t  |  d   } t j t  |  d   } t d | d |  S)a  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 <datasets>`.

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn and 'target', the regression target for each
        sample.
    r3   zdiabetes_data.csv.gzzdiabetes_target.csv.gzr6   )r   r   rN   r=   ri   r   )base_dirr3   r6   r   r   r   load_diabetes  s    ro   c               C   s   t  t t  d  }  t j |  d d d } t j |  d d d } t |  d   } | j   j   } Wd QRXt |  d   } | j   j   } Wd QRXt t t  d   } | j   } Wd QRXt	 d | d	 | d
 | d | d |  S)a  Load and return the linnerud dataset (multivariate regression).

    Samples total: 20
    Dimensionality: 3 for both data and targets
    Features: integer
    Targets: integer

    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'.
    zdata/zlinnerud_exercise.csvskiprowsrI   zlinnerud_physiological.csvNz/descr/linnerud.rstr3   rL   r6   r5   r7   )
r   r   rN   r=   ri   rB   readlinesplitrC   r   )rn   Zdata_exerciseZdata_physiologicalr)   Zheader_exerciseZheader_physiologicalrK   r   r   r   load_linnerud  s    	rs   c              C   sq  t  t  }  t |  d d  } t |   } | j   } Wd QRXt |  d d  } t |   } t j |  } t |  } t | d  } t | d  } t	 j
 | | f  }	 t	 j
 | f  }
 t |  } t	 j |  } x` t |  D]R \ } } t	 j | d d  d t	 j |	 | <t	 j | d d t	 j |
 | <q WWd QRXt d |	 d	 |
 d
 | d d  d |  S)a  Load and return the boston house-prices dataset (regression).

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

    Returns
    -------
    data : Bunch
        Dictionary-like object, the interesting attributes are:
        'data', the data to learn, 'target', the regression targets,
        and 'DESCR', the full description of the dataset.

    Examples
    --------
    >>> from sklearn.datasets import load_boston
    >>> boston = load_boston()
    >>> print(boston.data.shape)
    (506, 13)
    rK   zboston_house_prices.rstNr3   zboston_house_prices.csvr   rI   rJ   r6   rL   r7   rM   rM   rM   )r   rN   r   rB   rC   rO   rP   rQ   rR   r=   rS   r>   r9   rT   rU   r   )rV   Zfdescr_namer)   Z
descr_textZdata_file_namerX   rY   rZ   r[   r3   r6   rL   r\   r-   r   r   r   load_boston  s*    &+rt   c                 s   y= y d d l  m   Wn" t k
 r; d d l m   Yn XWn t k
 r] t d   Yn Xt t t  d   t t  d    }  |  j   } Wd QRX f d d   t	 j
   D }   f d	 d   | D } t d | d
 | d |  S)a-  Load sample images for image manipulation.
    Loads both, ``china`` and ``flower``.

    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')
    r   )imreadzIThe Python Imaging Library (PIL) is required to load data from jpeg filesrh   z
README.txtNc                s.   g  |  ]$ } | j  d   r t   |   q S)z.jpg)endswithr   )r(   rG   )rV   r   r   r+   T  s   	z&load_sample_images.<locals>.<listcomp>c                s   g  |  ] }   |   q Sr   r   )r(   rG   )ru   r   r   r+   X  s   	 r4   r7   )Z
scipy.miscru   ImportErrorZscipy.misc.pilutilr   r   rN   rB   rC   osr	   r   )r)   rK   r4   rh   r   )ru   rV   r   load_sample_images-  s     ry   c             C   sl   t    } d } x3 t | j  D]" \ } } | j |   r | } Pq W| d k ra t d |    | j | S)a:  Load the numpy array of a single sample image

    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)
    NzCannot find sample image: %s)ry   r9   r4   rv   r   rh   )Z
image_namerh   indexr\   rG   r   r   r   load_sample_image_  s    	r{   c              O   sj   | j  d d  } t |  d  \ } } t j d d k rE | | 7} |  d d  | | f } t |   S)	a  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 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+

    
py3_suffixZ_py3rI   r      NrM   rM   )r!   r   sysversion_infor   )argsr   r|   basenameextZnew_argsr   r   r   _pkl_filepath  s    
r   )!r   rx   rO   r~   r$   r   os.pathr   r   r   r   r   r   r	   r
   numpyr=   utilsr   r   r   r#   r&   rH   r_   rc   rm   ro   rs   rt   ry   r{   r   r   r   r   r   <module>   s<   +	=N@#42'