ó
‡ˆ\c           @   sï  d  Z  d d l Z d d l m Z m Z d d l Z d d l Z d d l Z d d l Z d d l	 Z	 d d l
 Z
 d d l Z d d l j 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 m Z m Z e j e  ƒ Z! e d d d d d d ƒ Z" d Z# d Z$ d Z% e d ƒ d „  ƒ Z& d „  Z' d „  Z( e	 j) d ƒ Z* d „  Z+ d „  Z, d d  d e. d! d$ e. d" „ Z/ d  d% d e. e0 d# „ Z1 d S(&   s  Caching loader for the 20 newsgroups text classification dataset


The description of the dataset is available on the official website at:

    http://people.csail.mit.edu/jrennie/20Newsgroups/

Quoting the introduction:

    The 20 Newsgroups data set is a collection of approximately 20,000
    newsgroup documents, partitioned (nearly) evenly across 20 different
    newsgroups. To the best of my knowledge, it was originally collected
    by Ken Lang, probably for his Newsweeder: Learning to filter netnews
    paper, though he does not explicitly mention this collection. The 20
    newsgroups collection has become a popular data set for experiments
    in text applications of machine learning techniques, such as text
    classification and text clustering.

This dataset loader will download the recommended "by date" variant of the
dataset and which features a point in time split between the train and
test sets. The compressed dataset size is around 14 Mb compressed. Once
uncompressed the train set is 52 MB and the test set is 34 MB.
iÿÿÿÿN(   t   dirnamet   joini   (   t   get_data_home(   t
   load_files(   t   _pkl_filepath(   t   _fetch_remote(   t   RemoteFileMetadatai   (   t   CountVectorizer(   t	   normalize(   t
   deprecated(   t   _joblib(   t   check_random_statet   Buncht   filenames   20news-bydate.tar.gzt   urls.   https://ndownloader.figshare.com/files/5975967t   checksumt@   8f1b2514ca22a5ade8fbb9cfa5727df95fa587f4c87b786e15c759fa66d95610s   20news-bydate.pkzs   20news-bydate-trains   20news-bydate-tests}   Function 'download_20newsgroups' was renamed to '_download_20newsgroups' in version 0.20 and will be removed in release 0.22.c         C   s   t  |  | ƒ S(   N(   t   _download_20newsgroups(   t
   target_dirt
   cache_path(    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   download_20newsgroupsA   s    c         C   s(  t  j j |  t ƒ } t  j j |  t ƒ } t  j j |  ƒ sL t  j |  ƒ n  t j d t	 j
 ƒ t t	 d |  ƒ} t j d | ƒ t j | d ƒ j d |  ƒ t  j | ƒ t d t | d d ƒd	 t | d d ƒƒ } t j t j | ƒ d
 ƒ } t | d ƒ  } | j | ƒ Wd QXt j |  ƒ | S(   sA   Download the 20 newsgroups data and stored it as a zipped pickle.s#   Downloading dataset from %s (14 MB)R    s   Decompressing %ss   r:gzt   patht   traint   encodingt   latin1t   testt
   zlib_codect   wbN(   t   osR   R   t   TRAIN_FOLDERt   TEST_FOLDERt   existst   makedirst   loggert   infot   ARCHIVER   R   t   debugt   tarfilet   opent
   extractallt   removet   dictR   t   codecst   encodet   picklet   dumpst   writet   shutilt   rmtree(   R   R   t
   train_patht	   test_patht   archive_patht   cachet   compressed_contentt   f(    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyR   H   s     c         C   s   |  j  d ƒ \ } } } | S(   sÝ   
    Given text in "news" format, strip the headers, by removing everything
    before the first blank line.

    Parameters
    ----------
    text : string
        The text from which to remove the signature block.
    s   

(   t	   partition(   t   textt   _beforet
   _blanklinet   after(    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   strip_newsgroup_headerb   s    
sF   (writes in|writes:|wrote:|says:|said:|^In article|^Quoted from|^\||^>)c         C   s>   g  |  j  d ƒ D] } t j | ƒ s | ^ q } d j | ƒ S(   s=  
    Given text in "news" format, strip lines beginning with the quote
    characters > or |, plus lines that often introduce a quoted section
    (for example, because they contain the string 'writes:'.)

    Parameters
    ----------
    text : string
        The text from which to remove the signature block.
    s   
(   t   splitt	   _QUOTE_REt   searchR   (   R8   t   linet
   good_lines(    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   strip_newsgroup_quotingt   s    c         C   sŠ   |  j  ƒ  j d ƒ } xM t t | ƒ d d d ƒ D]/ } | | } | j  ƒ  j  d ƒ d k r2 Pq2 q2 W| d k r‚ d j | |  ƒ S|  Sd S(   s‰  
    Given text in "news" format, attempt to remove a signature block.

    As a rough heuristic, we assume that signatures are set apart by either
    a blank line or a line made of hyphens, and that it is the last such line
    in the file (disregarding blank lines at the end).

    Parameters
    ----------
    text : string
        The text from which to remove the signature block.
    s   
i   iÿÿÿÿt   -t    i    N(   t   stripR=   t   ranget   lenR   (   R8   t   linest   line_numR@   (    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   strip_newsgroup_footer„   s    #
R   i*   c         C   s+  t  d |  ƒ }  t |  t ƒ } t j j |  d ƒ } d }	 t j j | ƒ rÉ yI t | d ƒ  }
 |
 j	 ƒ  } Wd QXt
 j | d ƒ } t j | ƒ }	 WqÉ t k
 rÅ } d d GHd GHd d GH| GHqÉ Xn  |	 d k r| r t j d	 ƒ t d
 | d | ƒ }	 qt d ƒ ‚ n  | d k r(|	 | } n² | d k rÊt ƒ  } t ƒ  } t ƒ  } xH d D]@ } |	 | } | j | j ƒ | j | j ƒ | j | j ƒ qVW| | _ t j | ƒ | _ t j | ƒ | _ n t d | ƒ ‚ t t ƒ } t t | d d ƒ ƒ  } | j	 ƒ  } Wd QX| | _ d | k rPg  | j D] } t | ƒ ^ q2| _ n  d | k r„g  | j D] } t | ƒ ^ qf| _ n  d | k r¸g  | j D] } t  | ƒ ^ qš| _ n  | d k	 r›g  | D] } | j! j" | ƒ | f ^ qË} | j# ƒ  t$ | Œ  \ } } t j% | j | ƒ } | j | | _ | j | | _ t j& | | j ƒ | _ t | ƒ | _! t j | j d t' ƒ} | | } | j( ƒ  | _ n  | r't) | ƒ } t j* | j j+ d ƒ } | j, | ƒ | j | | _ | j | | _ t j | j d t' ƒ} | | } | j( ƒ  | _ n  | S(   sr
  Load the filenames and data from the 20 newsgroups dataset (classification).

    Download it if necessary.

    =================   ==========
    Classes                     20
    Samples total            18846
    Dimensionality               1
    Features                  text
    =================   ==========

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

    Parameters
    ----------
    data_home : optional, default: None
        Specify a download and cache folder for the datasets. If None,
        all scikit-learn data is stored in '~/scikit_learn_data' subfolders.

    subset : 'train' or 'test', 'all', optional
        Select the dataset to load: 'train' for the training set, 'test'
        for the test set, 'all' for both, with shuffled ordering.

    categories : None or collection of string or unicode
        If None (default), load all the categories.
        If not None, list of category names to load (other categories
        ignored).

    shuffle : bool, optional
        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 (default)
        Determines random number generation for dataset shuffling. Pass an int
        for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    remove : tuple
        May contain any subset of ('headers', 'footers', 'quotes'). Each of
        these are kinds of text that will be detected and removed from the
        newsgroup posts, preventing classifiers from overfitting on
        metadata.

        'headers' removes newsgroup headers, 'footers' removes blocks at the
        ends of posts that look like signatures, and 'quotes' removes lines
        that appear to be quoting another post.

        'headers' follows an exact standard; the other filters are not always
        correct.

    download_if_missing : optional, True by default
        If False, raise an IOError if the data is not locally available
        instead of trying to download the data from the source site.

    Returns
    -------
    bunch : Bunch object with the following attribute:
        - bunch.data: list, length [n_samples]
        - bunch.target: array, shape [n_samples]
        - bunch.filenames: list, length [n_samples]
        - bunch.DESCR: a description of the dataset.
        - bunch.target_names: a list of categories of the returned data,
          length [n_classes]. This depends on the `categories` parameter.
    t	   data_homet   20news_homet   rbNR   iP   t   _s   Cache loading faileds8   Downloading 20news dataset. This may take a few minutes.R   R   s   20Newsgroups dataset not foundR   R   t   alls5   subset can only be 'train', 'test' or 'all', got '%s't   descrs   twenty_newsgroups.rstt   headerst   footerst   quotest   dtypei    (   R   R   (   R   R   (-   R   R   t
   CACHE_NAMER   R   R   t   NoneR   R&   t   readR*   t   decodeR,   t   loadst	   ExceptionR!   R"   R   t   IOErrort   listt   extendt   datat   targett	   filenamest   npt   arrayt
   ValueErrorR    t   __file__t   DESCRR<   RJ   RB   t   target_namest   indext   sortt   zipt   in1dt   searchsortedt   objectt   tolistR   t   aranget   shapet   shuffle(   RK   t   subsett
   categoriesRp   t   random_stateR(   t   download_if_missingR   t   twenty_homeR4   R6   R5   t   uncompressed_contentt   eR^   t   data_lstR_   R`   t   module_patht   rst_filet   fdescrR8   t   catt   labelst   maskt   indices(    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   fetch_20newsgroups   sŒ    G					
		(((+


c         C   s|  t  d | ƒ } d } | r5 | d d j | ƒ 7} n  t | | d ƒ } t d | d d d d d	 t d
 d d | d | ƒ } t d | d d d d d	 t d
 d d | d | ƒ } t j j | ƒ rØ t	 j
 | ƒ \ }	 }
 n^ t d t j ƒ } | j | j ƒ j ƒ  }	 | j | j ƒ j ƒ  }
 t	 j |	 |
 f | d d ƒ|	 j t j ƒ }	 |
 j t j ƒ }
 t |	 d t ƒt |
 d t ƒ| j } |  d k r¡|	 } | j } ns |  d k r¿|
 } | j } nU |  d k rt j |	 |
 f ƒ j ƒ  } t j | j | j f ƒ } n t d |  ƒ ‚ t t ƒ } t t | d d ƒ ƒ  } | j  ƒ  } Wd QX| r]| | f St! d | d | d | d | ƒ S(   s
  Load the 20 newsgroups dataset and vectorize it into token counts (classification).

    Download it if necessary.

    This is a convenience function; the transformation is done using the
    default settings for
    :class:`sklearn.feature_extraction.text.CountVectorizer`. For more
    advanced usage (stopword filtering, n-gram extraction, etc.), combine
    fetch_20newsgroups with a custom
    :class:`sklearn.feature_extraction.text.CountVectorizer`,
    :class:`sklearn.feature_extraction.text.HashingVectorizer`,
    :class:`sklearn.feature_extraction.text.TfidfTransformer` or
    :class:`sklearn.feature_extraction.text.TfidfVectorizer`.

    =================   ==========
    Classes                     20
    Samples total            18846
    Dimensionality          130107
    Features                  real
    =================   ==========

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

    Parameters
    ----------
    subset : 'train' or 'test', 'all', optional
        Select the dataset to load: 'train' for the training set, 'test'
        for the test set, 'all' for both, with shuffled ordering.

    remove : tuple
        May contain any subset of ('headers', 'footers', 'quotes'). Each of
        these are kinds of text that will be detected and removed from the
        newsgroup posts, preventing classifiers from overfitting on
        metadata.

        'headers' removes newsgroup headers, 'footers' removes blocks at the
        ends of posts that look like signatures, and 'quotes' removes lines
        that appear to be quoting another post.

    data_home : optional, default: None
        Specify an download and cache folder for the datasets. If None,
        all scikit-learn data is stored in '~/scikit_learn_data' subfolders.

    download_if_missing : optional, True by default
        If False, raise an IOError if the data is not locally available
        instead of trying to download the data from the source site.

    return_X_y : boolean, default=False.
        If True, returns ``(data.data, data.target)`` instead of a Bunch
        object.

        .. versionadded:: 0.20

    Returns
    -------
    bunch : Bunch object with the following attribute:
        - bunch.data: sparse matrix, shape [n_samples, n_features]
        - bunch.target: array, shape [n_samples]
        - bunch.target_names: a list of categories of the returned data,
          length [n_classes].
        - bunch.DESCR: a description of the dataset.

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

        .. versionadded:: 0.20
    RK   t   20newsgroup_vectorizeds   remove-RC   s   .pklRq   R   Rr   Rp   Rs   i   R(   Rt   R   RT   t   compressi	   t   copyRO   sC   %r is not a valid subset: should be one of ['train', 'test', 'all']RP   s   twenty_newsgroups.rstNR^   R_   Rf   Re   ("   R   R   R   R€   RV   t   TrueR   R   R   R
   t   loadR   Ra   t   int16t   fit_transformR^   t   tocsrt	   transformt   dumpt   astypet   float64R   t   FalseRf   R_   t   spt   vstackt   concatenateRc   R    Rd   R&   RW   R   (   Rq   R(   RK   Rt   t
   return_X_yt   filebaset   target_filet
   data_traint	   data_testt   X_traint   X_testt
   vectorizerRf   R^   R_   Ry   Rz   R{   (    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   fetch_20newsgroups_vectorized<  sd    E			

(    (    (2   t   __doc__R   t   os.pathR    R   t   loggingR%   R,   R/   t   reR*   t   numpyRa   t   scipy.sparset   sparseRŽ   t   baseR   R   R   R   R   t   feature_extraction.textR   t   preprocessingR   t   utilsR	   R
   R   R   t	   getLoggert   __name__R!   R#   RU   R   R   R   R   R<   t   compileR>   RB   RJ   RV   R„   R€   R   R™   (    (    (    sA   lib/python2.7/site-packages/sklearn/datasets/twenty_newsgroups.pyt   <module>   sP   						œ	