U
    3d                  
   @   sh  d Z ddl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	Z	ddl
mZmZmZ ddl
mZ ddlZddlZddlmZ ddlmZ ddlZddlmZ ddlmZ ddlZddlZddlZdd	lmZ ze W n ek
r   dZY nX 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(Z(ddl)Z)ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5 ddddddddddg
Z6edZ7e7j8Z9ej:j;Z;e7j<Z=e7j>Z?e?Z@dd  ZAdeBfd!d"ZCG d#d$ d$ZDd%d& ZEd]d*dZd^d-d.ZFd_d/d0ZGzddlHZHeHjIjJe,d1d2ZKeHjIjJejLMd3d4kd5d2ZNeHjIjOe+d6d2ZPeHjIjOe- d7d2ZQeHjIjJe(jRjS d8d2ZTeHjIjJejUd9kd:d2ZVW n eWk
r   Y nX d;d< ZXd`d>d?ZYG d@dA dAZZdBdC Z[dDdE Z\dadGdHZ]dbdIdJZ^dKdL Z_dcdMdNZ`dddPdZadedQdRZbdfdSdTZcG dUdV dVejdZeG dWdX dXZfG dYdZ dZZgG d[d\ d\ZhdS )gzTesting utilities.    N)check_outputSTDOUTCalledProcessError)TimeoutExpired)Iterable)Sequencewraps)	signature)TestCase)assert_allclose)assert_almost_equal)assert_approx_equal)assert_array_equal)assert_array_almost_equal)assert_array_less)IS_PYPY	_IS_32BIT#_in_unstable_openblas_configuration)check_classification_targets)check_arraycheck_is_fitted	check_X_y)threadpool_infoassert_raisesassert_raises_regexpr   r   r   r   r   r   assert_run_python_scriptSkipTest__init__c              	   O   sv   t jdd`}t d | ||}ttdr:dd |D }t|dkrhtd| jd	d
d |D f W 5 Q R X |S )z?
    Parameters
    ----------
    func
    *args
    **kw
    TrecordalwaysFutureWarningc                 S   s   g | ]}|j tjk	r|qS  )categorynpZVisibleDeprecationWarning.0er#   r#   :/tmp/pip-unpacked-wheel-zrfo1fqw/sklearn/utils/_testing.py
<listcomp>k   s      z&assert_no_warnings.<locals>.<listcomp>r   z"Got warnings when calling %s: [%s], c                 s   s   | ]}t |V  qd S N)str)r'   warningr#   r#   r)   	<genexpr>p   s     z%assert_no_warnings.<locals>.<genexpr>)	warningscatch_warningssimplefilterhasattrr%   lenAssertionError__name__join)funcargskwwresultr#   r#   r)   assert_no_warnings\   s    	


r=   c                 C   sP   t | tr,t| tr,| j}tdj|dn t| rBt|d| S t|dS dS )a   Context manager and decorator to ignore warnings.

    Note: Using this (in both variants) will clear all warnings
    from all python modules loaded. In case you need to test
    cross-module-warning-logging, this is not your tool of choice.

    Parameters
    ----------
    obj : callable, default=None
        callable where you want to ignore the warnings.
    category : warning class, default=Warning
        The category to filter. If Warning, all categories will be muted.

    Examples
    --------
    >>> import warnings
    >>> from sklearn.utils._testing import ignore_warnings
    >>> with ignore_warnings():
    ...     warnings.warn('buhuhuhu')

    >>> def nasty_warn():
    ...     warnings.warn('buhuhuhu')
    ...     print(42)

    >>> ignore_warnings(nasty_warn)()
    42
    z'obj' should be a callable where you want to ignore warnings. You passed a warning class instead: 'obj={warning_name}'. If you want to pass a warning class to ignore_warnings, you should use 'category={warning_name}')warning_name)r$   N)	
isinstancetype
issubclassWarningr6   
ValueErrorformatcallable_IgnoreWarnings)objr$   r>   r#   r#   r)   ignore_warningsu   s    rH   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )rF   at  Improved and simplified Python warnings context manager and decorator.

    This class allows the user to ignore the warnings raised by a function.
    Copied from Python 2.7.5 and modified as required.

    Parameters
    ----------
    category : tuple of warning class, default=Warning
        The category to filter. By default, all the categories will be muted.

    c                 C   s(   d| _ tjd | _d| _g | _|| _d S )NTr0   F)_recordsysmodules_module_enteredlogr$   )selfr$   r#   r#   r)   r      s
    z_IgnoreWarnings.__init__c                    s   t   fdd}|S )z<Decorator to catch and hide warnings without visual nesting.c               
      s8   t  & t dj  | |W  5 Q R  S Q R X d S )Nignore)r0   r1   r2   r$   )r9   kwargsfnrO   r#   r)   wrapper   s    
z)_IgnoreWarnings.__call__.<locals>.wrapperr   )rO   rS   rT   r#   rR   r)   __call__   s    z_IgnoreWarnings.__call__c                 C   sP   g }| j r|d | jtjd k	r4|d| j  t| j}d|d|f S )Nzrecord=Truer0   z	module=%rz%s(%s)r+   )rI   appendrL   rJ   rK   r@   r6   r7   )rO   r9   namer#   r#   r)   __repr__   s    

z_IgnoreWarnings.__repr__c                 C   sP   | j rtd|  d| _ | jj| _| jd d  | j_| jj| _td| j	 d S )NzCannot enter %r twiceTrP   )
rM   RuntimeErrorrL   filters_filtersshowwarning_showwarningr0   r2   r$   )rO   r#   r#   r)   	__enter__   s    

z_IgnoreWarnings.__enter__c                 G   s8   | j std|  | j| j_| j| j_g | jd d < d S )Nz%Cannot exit %r without entering first)rM   rY   r[   rL   rZ   r]   r\   rN   )rO   exc_infor#   r#   r)   __exit__   s
    

z_IgnoreWarnings.__exit__N)	r6   
__module____qualname____doc__r   rU   rX   r^   r`   r#   r#   r#   r)   rF      s   		rF   c              
   O   s   z||| W nB | k
rP } z$t |}||kr@td||f W 5 d}~X Y n:X t| trrddd | D }n| j}td||jf dS )a  Helper function to test the message raised in an exception.

    Given an exception, a callable to raise the exception, and
    a message string, tests that the correct exception is raised and
    that the message is a substring of the error thrown. Used to test
    that the specific message thrown during an exception is correct.

    Parameters
    ----------
    exceptions : exception or tuple of exception
        An Exception object.

    message : str
        The error message or a substring of the error message.

    function : callable
        Callable object to raise error.

    *args : the positional arguments to `function`.

    **kwargs : the keyword arguments to `function`.
    zRError message does not include the expected string: %r. Observed error message: %rNz or c                 s   s   | ]}|j V  qd S r,   )r6   r&   r#   r#   r)   r/      s     z'assert_raise_message.<locals>.<genexpr>z%s not raised by %s)r-   r5   r?   tupler7   r6   )
exceptionsmessagefunctionr9   rQ   r(   error_messagenamesr#   r#   r)   assert_raise_message   s    
rj           T c           	   	   C   s^   g }t | t | } }| j|jg}|dkrDdd |D }t|}t| ||||||d dS )au  dtype-aware variant of numpy.testing.assert_allclose

    This variant introspects the least precise floating point dtype
    in the input argument and automatically sets the relative tolerance
    parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
    in scikit-learn).

    `atol` is always left to 0. by default. It should be adjusted manually
    to an assertion-specific value in case there are null values expected
    in `desired`.

    The aggregate tolerance is `atol + rtol * abs(desired)`.

    Parameters
    ----------
    actual : array_like
        Array obtained.
    desired : array_like
        Array desired.
    rtol : float, optional, default=None
        Relative tolerance.
        If None, it is set based on the provided arrays' dtypes.
    atol : float, optional, default=0.
        Absolute tolerance.
    equal_nan : bool, optional, default=True
        If True, NaNs will compare equal.
    err_msg : str, optional, default=''
        The error message to be printed in case of failure.
    verbose : bool, optional, default=True
        If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
        If actual and desired are not equal up to specified precision.

    See Also
    --------
    numpy.testing.assert_allclose

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.utils._testing import assert_allclose
    >>> x = [1e-5, 1e-3, 1e-1]
    >>> y = np.arccos(np.cos(x))
    >>> assert_allclose(x, y, rtol=1e-5, atol=0)
    >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
    >>> assert_allclose(a, 1e-5)
    Nc                 S   s   g | ]}|t jkrd ndqS )g-C6?Hz>)r%   Zfloat32)r'   dtyper#   r#   r)   r*   ?  s     z#assert_allclose.<locals>.<listcomp>)rtolatol	equal_nanerr_msgverbose)r%   Z
asanyarrayrn   maxnp_assert_allclose)	actualZdesiredro   rp   rq   rr   rs   ZdtypesZrtolsr#   r#   r)   r     s    5rm   &.>c                 C   s   t j| rtt j|rt|  } | }|   |  t| j|j|d t| j|j|d t| j	|j	|||d n4t j| st j|st| ||||d nt
ddS )a  Assert allclose for sparse and dense data.

    Both x and y need to be either sparse or dense, they
    can't be mixed.

    Parameters
    ----------
    x : {array-like, sparse matrix}
        First array to compare.

    y : {array-like, sparse matrix}
        Second array to compare.

    rtol : float, default=1e-07
        relative tolerance; see numpy.allclose.

    atol : float, default=1e-9
        absolute tolerance; see numpy.allclose. Note that the default here is
        more tolerant than the default for numpy.testing.assert_allclose, where
        atol=0.

    err_msg : str, default=''
        Error message to raise.
    )rr   )ro   rp   rr   zGCan only compare two sparse matrices, not a sparse matrix and an array.N)spsparseissparseZtocsrZsum_duplicatesr   indicesZindptrr   datarC   )xyro   rp   rr   r#   r#   r)   assert_allclose_dense_sparseM  s    r   c                 C   s   d|   kr| j|d dS )a~  Set random state of an estimator if it has the `random_state` param.

    Parameters
    ----------
    estimator : object
        The estimator.
    random_state : int, RandomState instance or None, default=0
        Pseudo random number generator state.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.
    random_state)r   N)
get_params
set_params)Z	estimatorr   r#   r#   r)   set_random_statew  s    r   zskipped on 32bit platforms)reasonZTRAVIStruezskip on travisznot compatible with PyPyz+OpenBLAS is unstable for this configurationzjoblib is in serial modedarwinz)Possible multi-process bug with some BLASc                   C   s   t tjddrtdd S )NZSKLEARN_SKIP_NETWORK_TESTSr   z-Text tutorial requires large dataset download)intosenvirongetr   r#   r#   r#   r)   check_skip_network  s    r   Fc                 C   sF   zt j| rt|  W n& tk
r@   |r<td|   Y nX dS )zuUtility function to cleanup a temporary folder if still existing.

    Copy from joblib.pool (for independence).
    z$Could not delete temporary folder %sN)r   pathexistsshutilrmtreeWindowsErrorr0   warn)Zfolder_pathr   r#   r#   r)   _delete_folder  s    r   c                   @   s*   e Zd ZdZd
ddZdd Zdd Zd	S )
TempMemmapzM
    Parameters
    ----------
    data
    mmap_mode : str, default='r'
    rc                 C   s   || _ || _d S r,   )	mmap_moder|   )rO   r|   r   r#   r#   r)   r     s    zTempMemmap.__init__c                 C   s   t | j| jdd\}| _|S )NT)r   return_folder)create_memmap_backed_datar|   r   temp_folder)rO   Zdata_read_onlyr#   r#   r)   r^     s      zTempMemmap.__enter__c                 C   s   t | j d S r,   )r   r   )rO   exc_typeexc_valexc_tbr#   r#   r)   r`     s    zTempMemmap.__exit__N)r   )r6   ra   rb   rc   r   r^   r`   r#   r#   r#   r)   r     s   
r   c                 C   sL   t j|| jd| jd}| d d  |d d < |  t j|| j|| jd}|S )Nzw+)rn   modeshape)r%   Zmemmaprn   r   flush)arrayfilenamer   fpZmemmap_backed_arrayr#   r#   r)   _create_memmap_backed_array  s       r   c                    sd   t | tjr$t d}t| |S t | trXtdd | D rX fddt| D S t	dd S )Nzdata.datc                 s   s   | ]}t |tjV  qd S r,   )r?   r%   ndarray)r'   Zeachr#   r#   r)   r/     s    z7_create_aligned_memmap_backed_arrays.<locals>.<genexpr>c              
      s,   g | ]$\}}t |t d | dqS )r|   z.dat)r   opr7   )r'   indexr   folderr   r#   r)   r*     s     z8_create_aligned_memmap_backed_arrays.<locals>.<listcomp>z`When creating aligned memmap-backed arrays, input must be a single array or a sequence of arrays)
r?   r%   r   r   r7   r   r   all	enumeraterC   )r|   r   r   r   r#   r   r)   $_create_aligned_memmap_backed_arrays  s    r   r   c           	      C   s   t jdd}ttjt|dd tdd t D }|r>d}|rPt	| ||}n&t
|d}t| | tj||d}|s~|n||f}|S )	aq  
    Parameters
    ----------
    data
    mmap_mode : str, default='r'
    return_folder :  bool, default=False
    aligned : bool, default=False
        If True, if input is a single numpy array and if the input array is aligned,
        the memory mapped array will also be aligned. This is a workaround for
        https://github.com/joblib/joblib/issues/563.
    Zsklearn_testing_)prefixT)r   c                 s   s2   | ]*}|d  dkr| dd dkrdV  qdS )Zinternal_apiZopenblasarchitectureZprescottTN)r   lower)r'   infor#   r#   r)   r/     s   z,create_memmap_backed_data.<locals>.<genexpr>zdata.pkl)r   )tempfilemkdtempatexitregister	functoolspartialr   anyr   r   r   r7   joblibdumpload)	r|   r   r   Zalignedr   Zhas_prescott_openblasZmemmap_backed_datar   r<   r#   r#   r)   r     s&      r   c                 C   sp   zt | j}W n tk
r&   g  Y S X dd | D }|rhdd | D }t|dkr`d}||fS |S dS )z!Helper to get function arguments.c                 S   s&   g | ]\}}|j |j|jfkr|qS r#   )kindVAR_POSITIONALVAR_KEYWORD)r'   keyparamr#   r#   r)   r*   /  s   z_get_args.<locals>.<listcomp>c                 S   s   g | ]}|j |jkr|jqS r#   )r   r   rW   )r'   r   r#   r#   r)   r*   5  s   r   N)r
   
parametersrC   itemsvaluesr4   )rg   varargsparamsr9   r#   r#   r)   	_get_args'  s    
r   c                 C   s\   g }t | }|r||j | j}|| jkrF||d|d  || j d|S )zGet function full name.

    Parameters
    ----------
    func : callable
        The function object.

    Returns
    -------
    name : str
        The function name.
    N.)inspect	getmodulerV   r6   rb   findr7   )r8   partsmodulequalnamer#   r#   r)   _get_func_nameA  s    

r   c                    s  ddl m} g } dkrg n  t| }|dr<|dr@|S t| rN|S |dd dkrd|S |dd	 d
krz|S tt fddt	| }t
|dkr|d dkr|d |dkrg }tjdd tdt z|| }W n tk
rn } zbdt|krPt|ddd }	|d| g|	 7 }| W Y  W  5 Q R  S |t| W 5 d}~X Y nN tk
r } z.||d t| g7 }| W Y W  5 Q R  S d}~X Y nX W 5 Q R X t
|rtd||d f g }
|d D ]\}}}| shd|krB|d|d dd  rB||d|  g7 }n&| drh||d|   g7 }d|kr|
|dd d qt
|dkr|S tt fdd|
}
g }	ttt
|
t
|D ]:}|| |
| kr|	d||| |
| f g7 }	 qqt
|t
|
kr8|	d|t
|
  g7 }	n(t
|t
|
k r`|	d |
t
|  g7 }	t
|	dkrrg S ddl}ddl}||
 }|| }|	d!g7 }	|	 d"d# |!||D  | |	 d| g| }|S )$ar  Helper to check docstring.

    Parameters
    ----------
    func : callable
        The function object to test.
    doc : str, default=None
        Docstring if it is passed manually to the test.
    ignore : list, default=None
        Parameters to ignore.

    Returns
    -------
    incorrect : list
        A list of string describing the incorrect results.
    r   )	docscrapeNzsklearn.zsklearn.externalsr   )Zsetup_moduleZteardown_module   Zestimator_checksc                    s   |  kS r,   r#   r}   rP   r#   r)   <lambda>      z,check_docstring_parameters.<locals>.<lambda>rO   Tr   errorz"potentially wrong underline length
   zIn function: z parsing error: zError for %s:
%sZ
Parameters:z9 There was no space between the param name and colon (%r)z6 Parameter %r has an empty type spec. Remove the colon*z` c                    s   |  kS r,   r#   r   r   r#   r)   r     r   zmThere's a parameter name mismatch in function docstring w.r.t. function signature, at index %s diff: %r != %rzbParameters in function docstring have less items w.r.t. function signature, first missing item: %sz`Parameters in function docstring have more items w.r.t. function signature, first extra item: %sz
Full diff:c                 s   s   | ]}|  V  qd S r,   )strip)r'   liner#   r#   r)   r/     s   z-check_docstring_parameters.<locals>.<genexpr>)"Znumpydocr   r   
startswithr   isdatadescriptorsplitlistfilterr   r4   remover0   r1   r2   UserWarningZFunctionDocr-   rV   	ExceptionrY   r   r   rstripendswithlstriprangemindifflibpprintpformat
splitlinesextendZndiff)r8   docrP   r   Z	incorrect	func_nameZparam_signaturerecordsexprf   Z
param_docsrW   Ztype_definitionZ	param_docir   r   Zparam_docs_formattedZparam_signature_formattedr#   r   r)   check_docstring_parameters[  s    


0

*



	



r   <   c              
   C   s  t jdd\}}t| zbt|d}|| d W 5 Q R X tj	|g}t
t
t
tjd}tj }ztj||d g|d< W n tk
r   ||d< Y nX |t|d}tjd}	|	r|	|d	 d< ||d
< zfzt|f|}
W n8 tk
r& } ztd|jd W 5 d}~X Y nX |
dkr@t|
dW n8 tk
rz } ztd|jd W 5 d}~X Y nX W 5 t| X dS )a  Utility to check assertions in an independent Python subprocess.

    The script provided in the source code should return 0 and not print
    anything on stderr or stdout.

    This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle

    Parameters
    ----------
    source_code : str
        The Python source code to execute.
    timeout : int, default=60
        Time in seconds before timeout.
    z_src_test_sklearn.py)suffixwbzutf-8z..
PYTHONPATH)cwdstderrenvZCOVERAGE_PROCESS_STARTr   timeoutzscript errored with output:
%sNr   z!script timeout, output so far:
%s)r   mkstempr   closeunlinkopenwriteencoderJ   
executabler   normpathr7   dirnamesklearn__file__r   copypathsepKeyErrorr   r   r   r   rY   outputdecoder5   r   )Zsource_coder   fdZsource_filefcmdr   r   rQ   Zcoverage_rcoutr(   r#   r#   r)   r     s>    



c                 C   sB  |dkr.|dkrt | S tj| |d S n|dkr^|dkrFt| S ttj| |d S n|dkrttj| |dS |dkrtjj| |dS |dkrt	d}|j
| ||d	S |d
krt	d}|j| |dS |dkrt	d}|j| |dS |dkr
t| d | d S |dkr$tjj| |dS |dkr>tjj| |dS dS )a  Convert a given container to a specific array-like with a dtype.

    Parameters
    ----------
    container : array-like
        The container to convert.
    constructor_name : {"list", "tuple", "array", "sparse", "dataframe",             "series", "index", "slice", "sparse_csr", "sparse_csc"}
        The type of the returned container.
    columns_name : index or array-like, default=None
        For pandas container supporting `columns_names`, it will affect
        specific names.
    dtype : dtype, default=None
        Force the dtype of the container. Does not apply to `"slice"`
        container.

    Returns
    -------
    converted_container
    r   N)rn   rd   r   ry   Z	dataframeZpandas)columnsrn   Zseriesr   slicer      Z
sparse_csrZ
sparse_csc)r   r%   Zasarraytolistrd   rx   ry   Z
csr_matrixpytestZimportorskipZ	DataFrameZSeriesZIndexr  Z
csc_matrix)	containerZconstructor_nameZcolumns_namern   pdr#   r#   r)   _convert_container!  s6    





r  c                 C   s   t | |||S )a[  Context manager to ensure exceptions are raised within a code block.

    This is similar to and inspired from pytest.raises, but supports a few
    other cases.

    This is only intended to be used in estimator_checks.py where we don't
    want to use pytest. In the rest of the code base, just use pytest.raises
    instead.

    Parameters
    ----------
    excepted_exc_type : Exception or list of Exception
        The exception that should be raised by the block. If a list, the block
        should raise one of the exceptions.
    match : str or list of str, default=None
        A regex that the exception message should match. If a list, one of
        the entries must match. If None, match isn't enforced.
    may_pass : bool, default=False
        If True, the block is allowed to not raise an exception. Useful in
        cases where some estimators may support a feature but others must
        fail with an appropriate error message. By default, the context
        manager will raise an exception if the block does not raise an
        exception.
    err_msg : str, default=None
        If the context manager fails (e.g. the block fails to raise the
        proper exception, or fails to match), then an AssertionError is
        raised with this message. By default, an AssertionError is raised
        with a default error message (depends on the kind of failure). Use
        this to indicate how users should fix their estimators to pass the
        checks.

    Attributes
    ----------
    raised_and_matched : bool
        True if an exception was raised and a match was found, False otherwise.
    )_Raises)expected_exc_typematchmay_passrr   r#   r#   r)   raisesU  s    %r  c                   @   s   e Zd Zdd Zdd ZdS )r  c                 C   sB   t |tr|n|g| _t |tr&|gn|| _|| _|| _d| _d S )NF)r?   r   expected_exc_typesr-   matchesr  rr   raised_and_matched)rO   r  r  r  rr   r#   r#   r)   r     s    z_Raises.__init__c                    s    d kr,| j rdS | jp"d| j }t|t fdd| jD s`| jd k	r\t| jndS | jd k	r| jpdd| jt}tfdd| jD st|d| _	dS )	NTzDid not raise: c                 3   s   | ]}t  |V  qd S r,   )rA   )r'   Zexpected_type)r   r#   r)   r/     s   z#_Raises.__exit__.<locals>.<genexpr>FzIThe error message should contain one of the following patterns:
{}
Got {}r   c                 3   s   | ]}t |t V  qd S r,   )researchr-   )r'   r  )	exc_valuer#   r)   r/     s     )
r  rr   r  r5   r   r  rD   r7   r-   r  )rO   r   r   _rr   r#   )r   r   r)   r`     s,    


 
z_Raises.__exit__N)r6   ra   rb   r   r`   r#   r#   r#   r)   r  }  s   r  c                   @   sP   e Zd ZdZdZdddZdddZd	d
 Zdd Zdd Z	dd Z
dd ZdS )MinimalClassifiera  Minimal classifier implementation with inheriting from BaseEstimator.

    This estimator should be tested with:

    * `check_estimator` in `test_estimator_checks.py`;
    * within a `Pipeline` in `test_pipeline.py`;
    * within a `SearchCV` in `test_search.py`.
    
classifierNc                 C   s
   || _ d S r,   r   rO   r   r#   r#   r)   r     s    zMinimalClassifier.__init__Tc                 C   s
   d| j iS Nr   r$  rO   deepr#   r#   r)   r     s    zMinimalClassifier.get_paramsc                 K   s"   |  D ]\}}t| || q| S r,   r   setattrrO   r   r   valuer#   r#   r)   r     s    zMinimalClassifier.set_paramsc                 C   s8   t ||\}}t| tj|dd\| _}| | _| S )NT)Zreturn_counts)r   r   r%   uniqueclasses_argmax_most_frequent_class_idx)rO   Xr~   countsr#   r#   r)   fit  s
    
zMinimalClassifier.fitc                 C   sH   t |  t|}|jd | jjf}tj|tjd}d|d d | jf< |S )Nr   )r   rn   g      ?)	r   r   r   r.  sizer%   zerosZfloat64r0  )rO   r1  Zproba_shapey_probar#   r#   r)   predict_proba  s    zMinimalClassifier.predict_probac                 C   s    |  |}|jdd}| j| S )Nr  )Zaxis)r7  r/  r.  )rO   r1  r6  Zy_predr#   r#   r)   predict  s    
zMinimalClassifier.predictc                 C   s   ddl m} ||| |S )Nr   )accuracy_score)sklearn.metricsr9  r8  )rO   r1  r~   r9  r#   r#   r)   score  s    zMinimalClassifier.score)N)T)r6   ra   rb   rc   _estimator_typer   r   r   r3  r7  r8  r;  r#   r#   r#   r)   r"    s   	

r"  c                   @   sH   e Zd ZdZdZdddZdddZd	d
 Zdd Zdd Z	dd Z
dS )MinimalRegressora  Minimal regressor implementation with inheriting from BaseEstimator.

    This estimator should be tested with:

    * `check_estimator` in `test_estimator_checks.py`;
    * within a `Pipeline` in `test_pipeline.py`;
    * within a `SearchCV` in `test_search.py`.
    Z	regressorNc                 C   s
   || _ d S r,   r$  r%  r#   r#   r)   r     s    zMinimalRegressor.__init__Tc                 C   s
   d| j iS r&  r$  r'  r#   r#   r)   r     s    zMinimalRegressor.get_paramsc                 K   s"   |  D ]\}}t| || q| S r,   r)  r+  r#   r#   r)   r     s    zMinimalRegressor.set_paramsc                 C   s$   t ||\}}d| _t|| _| S NT)r   
is_fitted_r%   Zmean_meanrO   r1  r~   r#   r#   r)   r3    s    zMinimalRegressor.fitc                 C   s*   t |  t|}tj|jd fd| j S )Nr   )r   )r   r   r%   Zonesr   r@  )rO   r1  r#   r#   r)   r8    s    zMinimalRegressor.predictc                 C   s   ddl m} ||| |S )Nr   )r2_score)r:  rB  r8  )rO   r1  r~   rB  r#   r#   r)   r;    s    zMinimalRegressor.score)N)T)r6   ra   rb   rc   r<  r   r   r   r3  r8  r;  r#   r#   r#   r)   r=    s   	

r=  c                   @   sJ   e Zd ZdZdddZdddZdd	 Zdd
dZdddZdddZ	dS )MinimalTransformera  Minimal transformer implementation with inheriting from
    BaseEstimator.

    This estimator should be tested with:

    * `check_estimator` in `test_estimator_checks.py`;
    * within a `Pipeline` in `test_pipeline.py`;
    * within a `SearchCV` in `test_search.py`.
    Nc                 C   s
   || _ d S r,   r$  r%  r#   r#   r)   r     s    zMinimalTransformer.__init__Tc                 C   s
   d| j iS r&  r$  r'  r#   r#   r)   r     s    zMinimalTransformer.get_paramsc                 K   s"   |  D ]\}}t| || q| S r,   r)  r+  r#   r#   r)   r     s    zMinimalTransformer.set_paramsc                 C   s   t | d| _| S r>  )r   r?  rA  r#   r#   r)   r3    s    zMinimalTransformer.fitc                 C   s   t |  t|}|S r,   )r   r   rA  r#   r#   r)   	transform  s    zMinimalTransformer.transformc                 C   s   |  ||||S r,   )r3  rD  rA  r#   r#   r)   fit_transform#  s    z MinimalTransformer.fit_transform)N)T)N)N)N)
r6   ra   rb   rc   r   r   r   r3  rD  rE  r#   r#   r#   r)   rC    s   




rC  )Nrk   Trl   T)rm   rw   rl   )r   )F)r   FF)F)NN)r   )NN)NFN)irc   r   os.pathr   r   r   r0   rJ   r   r   
subprocessr   r   r   r   r  
contextlibcollections.abcr   r   Zscipyrx   r	   r
   r   r   Zunittestr   r   	NameErrorZnumpy.testingr   ru   r   r   r   r   r   Znumpyr%   r   r  Zsklearn.utilsr   r   r   Zsklearn.utils.multiclassr   Zsklearn.utils.validationr   r   r   Zsklearn.utils.fixesr   __all__Z_dummyassertRaisesr   Zcaser   ZassertDictEqualZassert_dict_equalassertRaisesRegexZassert_raises_regexr   r=   rB   rH   rF   rj   r   r   r  markZskipifZskip_if_32bitr   r   Zskip_travisZxfailZfails_if_pypyZfails_if_unstable_openblasparallelmpZskip_if_no_parallelplatformZ!if_safe_multiprocessing_with_blasImportErrorr   r   r   r   r   r   r   r   r   r   r  r  AbstractContextManagerr  r"  r=  rC  r#   r#   r#   r)   <module>   s   
,9+         
I
*
   


,

 
3
4
(-1(