
    ^j;                       U 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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 dd
lmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZ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/Z0ddl1m2Z2m3Z3m4Z4m5Z5m6Z6 erddlm7Z7m8Z8 g dZ9ejt                  Z;ejt                  Z<e%d   Z=e%d   Z>e%d   Z?e%d   Z@e$eAeBeCf   ZDeeAeeAeBf   f   ZEe%e eA   e eF   df   ZGe%e eA   df   ZHe%e eB   e eF   e.j                  e6e,j                  f   ZKe%e.j                  e6e,j                  f   ZLe%e eB   e e eB      e.j                  e6e5e,j                  e,j                  f   ZNe%eAee.j                  e5e0j                  j                  de d   e e.j                     e,j                  f	   ZQe%e eB   e eF   e.j                  e6e5e,j                  e,j                  f   ZRe%eAee.j                  e5e0j                  j                  e,j                  f   ZSe%e.j                  e0j                  j                  e e0j                  j                     f   ZTe%e0j                  j                  e e0j                  j                     f   ZUe%e eB   e eF   e.j                  e6e,j                  f   ZVe%e e eB      e e eF      e eB   e eF   e.j                  e6e5e,j                  f   ZWdZXh dZY G d deZ      Z[deBdeCfdZ\deFdeAdeFfd Z]d!e.j                  de$e.j                  eFf   fd"Z^ G d# d$e      Z_ G d% d&      Z` e`       aaeebd'<   d(acd)add*ed+eAdeCfd,Ze	 	 dd*ed-eAd.eAddfd/Zfd0eeAgdf   deeAgdf   fd1Zgd2eAddfd3Zhd2eAddfd4Ziegd2eAddfd5       Zjd2ekddfd6Zl ej                  d7d8      d9k7  rej                  ej                  _p         ej                  dej                        Zr erel      e_r         ej                  ej                        dk7  r& e[ ej                         j                  d:            eFeBeCfZud;eFddfd<Zvd=edeCfd>Zwd?edeCfd@Zxd?edeCfdAZydBe.j                  dCdDde.j                  fdEZzd?edeCfdFZ{d?eddGfdHZ|d?eddIfdJZ}d?edeCfdKZ~d?edCdDdLeAde.j                  fdMZd?edeCfdNZd?edeCfdOZd?edeCfdPZej                  j                  Zejt                  e_p        ej                  ej                  ge_        dQedejt                  fdRZd?edCdDdLeAde.j                  fdSZdTdUdVeFde.j                  fdWZdTdUdVeFde.j                  fdXZdTdUdVeFde.j                  fdYZdTdUdVeFde.j                  fdZZd[eAdej                  fd\Zd]ed^e e   dej"                  fd_Zd=edefd`Zde%eFeBeAe f   deAfdaZd?e"eeAef      deAfdbZ G dc dd      Z G de dfe      Z G dg dh      ZdieAdeeAef   djedeeAef   fdkZdlZ	 dZdZdmZdnZ	 dZdZ	 dZdZdmZdnZ	 dZdZ	 dZdZ	 eeeeedoZ	 eedpZd?e.j                  de.j                  fdqZd?e.j                  de$e?eFe.j                  f   fdrZd?e.j                  de$e=eFe.j                  f   fdsZdCedeCfdtZdue6ddfdvZd?e5dwdDde.j                  fdxZd?e5dyeHdzeGd{e"e e       de$e.j                  e eA   e%e eA   e eF   f   e e    f   f
d|Z	 dd{e"e e       d}e"e%eAef      deAfd~Z	 	 dd}e"e%eAef      de"eA   de"e e       fdZ G d dejj                        Z G d d      Z G d d      Zee.j                  ege$e.j                  e.j                  f   f   Ze%ee.j                  egeDf   ee.j                  ege eD   f   f   Z G d de!      Z G d d      Zy)zWrapper for C API of LightGBM.   )_LIB    N)OrderedDict)deepcopy)Enum)wraps)SEEK_ENDenviron)getsize)Path)NamedTemporaryFile)TYPE_CHECKINGAnyCallableDictIterableIteratorList
NamedTupleOptionalSetTupleUnion)PANDAS_INSTALLEDconcatpd_CategoricalDtypepd_DataFrame	pd_Series)Literal	TypeGuard)BoosterDatasetLGBMDeprecationWarningLightGBMErrorregister_loggerSequence)zctypes._Pointer[ctypes.c_int32]zctypes._Pointer[ctypes.c_int64])z-ctypes.Array[ctypes._Pointer[ctypes.c_int32]]z-ctypes.Array[ctypes._Pointer[ctypes.c_int64]])zctypes._Pointer[ctypes.c_float]z ctypes._Pointer[ctypes.c_double])z-ctypes.Array[ctypes._Pointer[ctypes.c_float]]z.ctypes.Array[ctypes._Pointer[ctypes.c_double]]zLiteral['auto']r&   gz8>   ovaovrsoftmax
multiclassmulticlassovamulticlass_ovac                       e Zd ZdZy)r$   zError thrown by LightGBM.N__name__
__module____qualname____doc__     Y/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/lightgbm/basic.pyr$   r$      s    #r4   r$   xreturnc                 4    t          | cxk  xr	 t         k  S c S N)ZERO_THRESHOLDr6   s    r5   _is_zeror<      s    ?a1>1111r4   
total_nrowparamsc           	          t        j                  d      }t        t        j                  t        j
                  |       t        |      t        j                  |                   |j                  S )Nr   )	ctypesc_int
_safe_callr   LGBM_GetSampleCountc_int32_c_strbyrefvalue)r=   r>   
sample_cnts      r5   _get_sample_countrI      sR    aJ  NN:&6NLL$	
 r4   matc                 ,   | j                   t        j                  t        j                  fv r| j                   }nt        j                  }| j                  d   r	d}t
        }nd}t        }t        j                  | ||      }|j                  |      |fS )NF_CONTIGUOUSFC)dtypeorderrP   )	rO   npfloat32float64flags_C_API_IS_COL_MAJOR_C_API_IS_ROW_MAJORasarrayravel)rJ   rO   rP   layoutdatas        r5   _np2d_to_np1dr\      su    
yyRZZ,,		


yy $$::ce4D::E:"F**r4   c                       e Zd ZdZdZdZy)_MissingTypeNoneNaNZeroN)r/   r0   r1   NONENANZEROr3   r4   r5   r^   r^      s    D
CDr4   r^   c                   ,    e Zd ZdeddfdZdeddfdZy)_DummyLoggermsgr7   Nc                     t        |       y r9   )printselfrg   s     r5   infoz_DummyLogger.info   s	    c
r4   c                 2    t        j                  |d       y )N   )
stacklevel)warningswarnrj   s     r5   warningz_DummyLogger.warning   s    ca(r4   )r/   r0   r1   strrl   rr   r3   r4   r5   rf   rf      s(      )3 )4 )r4   rf   _LOGGERrl   rr   loggermethod_namec                 .    t        t        | |d             S r9   )callablegetattr)ru   rv   s     r5   _has_methodrz      s    GFK677r4   info_method_namewarning_method_namec                 d    t        | |      rt        | |      st        d| d| d      | a|a|ay)a,  Register custom logger.

    Parameters
    ----------
    logger : Any
        Custom logger.
    info_method_name : str, optional (default="info")
        Method used to log info messages.
    warning_method_name : str, optional (default="warning")
        Method used to log warning messages.
    zLogger must provide 'z' and 'z' methodN)rz   	TypeErrorrt   _INFO_METHOD_NAME_WARNING_METHOD_NAME)ru   r{   r|   s      r5   r%   r%      sL      v/0FL_8`/0@/AI\H]]efgg G(.r4   funcc                 H     g t               dt        ddf fd       }|S )z;Join log messages from native library which come by chunks.rg   r7   Nc                     | j                         dk(  rdj                        } g  |       S j                  |        y )N )stripjoinappend)rg   r   msg_normalizeds    r5   wrapperz)_normalize_native_string.<locals>.wrapper   s>     99;"''.)CN9!!#&r4   )r   rs   )r   r   r   s   ` @r5   _normalize_native_stringr      s3     "N
4['S 'T ' ' Nr4   rg   c                 8     t        t        t              |        y r9   ry   rt   r   rg   s    r5   	_log_infor     s    'GG&',r4   c                 8     t        t        t              |        y r9   )ry   rt   r   r   s    r5   _log_warningr     s    *GG)*3/r4   c                 8     t        t        t              |        y r9   r   r   s    r5   _log_nativer   
  s    'GG&',r4   c                 J    t        t        | j                  d                   y)z.Redirect logs from native library into Python.utf-8N)r   rs   decoder   s    r5   _log_callbackr     s    CJJw'()r4   LIGHTGBM_BUILD_DOCFalseTruer   retc                 f    | dk7  r,t        t        j                         j                  d            y)zCheck the return value from C API call.

    Parameters
    ----------
    ret : int
        The return value from C API calls.
    r   r   N)r$   r   LGBM_GetLastErrorr   )r   s    r5   rB   rB      s/     axD224;;GDEE r4   objc                 F    	 t        |        y# t        t        f$ r Y yw xY w)zCCheck whether object is a number or not, include numpy number, etc.TF)floatr~   
ValueErrorr   s    r5   _is_numericr   ,  s*    c
z"  s      r[   c                 j    t        | t        j                        xr t        | j                        dk(  S )z(Check whether data is a numpy 1-D array.r   
isinstancerR   ndarraylenshaper[   s    r5   _is_numpy_1d_arrayr   7  s%    dBJJ'@C

Oq,@@r4   c                     t        | t        j                        sy| j                  }t	        |      dk(  xr |d   dk(  S )z+Check whether data is a column numpy array.F   r   )r   rR   r   r   r   )r[   r   s     r5   _is_numpy_column_arrayr   <  s7    dBJJ'JJEu:?,uQx1},r4   arrayrO   znp.typing.DTypeLikec                 J    | j                   |k(  r| S | j                  |d      S )z Cast numpy array to given dtype.FrO   copy)rO   astype)r   rO   s     r5   _cast_numpy_array_to_dtyper   D  s&    {{e<<e%<00r4   c                 L    t        | t              xr |  xs t        | d         S )z!Check whether data is a 1-D list.r   )r   listr   r   s    r5   _is_1d_listr   K  s$    dD!H4x'G;tAw3GHr4   zTypeGuard[List[np.ndarray]]c                 J    t        | t              xr t        d | D              S )Nc              3   P   K   | ]  }t        |t        j                           y wr9   )r   rR   r   .0r6   s     r5   	<genexpr>z+_is_list_of_numpy_arrays.<locals>.<genexpr>Q  s     )R*Q

*C)Rs   $&r   r   allr   s    r5   _is_list_of_numpy_arraysr   P  s    dD!Rc)RT)R&RRr4   zTypeGuard[List[Sequence]]c                 J    t        | t              xr t        d | D              S )Nc              3   <   K   | ]  }t        |t                y wr9   )r   r&   r   s     r5   r   z(_is_list_of_sequences.<locals>.<genexpr>U  s     )Pa*Q*A)Ps   r   r   s    r5   _is_list_of_sequencesr   T  s    dD!Pc)P4)P&PPr4   c                 p    t        |       xs* t        |       xs t        |       xs t        | t              S )z'Check whether data is a 1-D collection.)r   r   r   r   r   r   s    r5   _is_1d_collectionr   X  s2    d#w'=d'Cw{SWGXw\fgkmv\wwr4   namec                    t        |       rt        | |      S t        |       r't        d       | j	                         }t        ||      S t        |       rt        j                  | |      S t        | t              r:t        | j                         j                         t        j                  | |      S t        dt        |       j                   d| d      )z Convert data to numpy 1-D array.z$Converting column-vector to 1d arrayrO   Wrong type() for z5.
It should be list, numpy 1-D array or pandas Series)r   r   r   r   rY   r   rR   rX   r   r   _check_for_bad_pandas_dtypesto_framedtypesr~   typer/   )r[   rO   r   r   s       r5   _list_to_1d_numpyr   ]  s     $)$66		%;<

)%77	T	zz$e,,	D)	$$T]]_%;%;<zz$e,,$t*--.fTF:pq
 	
r4   c                     t        | t        j                        xr, t        | j                        dk(  xr | j                  d   dkD  S )z(Check whether data is a numpy 2-D array.r   r   r   r   s    r5   _is_numpy_2d_arrayr   u  s9    dBJJ'VC

Oq,@VTZZPQ]UVEVVr4   c                 b    t        | t              xr t        |       dkD  xr t        | d         S )z!Check whether data is a 2-D list.r   )r   r   r   r   r   s    r5   _is_2d_listr   z  s*    dD!Lc$i!mLDG8LLr4   c                 V    t        |       xs t        |       xs t        | t              S )z'Check whether data is a 2-D collection.)r   r   r   r   r   s    r5   _is_2d_collectionr     s#    d#Z{4'8ZJt\<ZZr4   	pycapsulec                 @    t        j                  t        | d            S )zHExtract the raw pointer from a PyCapsule returned by __arrow_c_stream__.s   arrow_array_stream)r@   c_void_p_pycapsule_get_pointer)r   s    r5   %_extract_arrow_stream_capsule_pointerr     s    ??1)=RSTTr4   c                 4   t        |       rt        | |      S t        |       rt        j                  | |      S t        | t              r+t        | j                         t        | j                  |      S t        dt        |       j                   d| d      )z Convert data to numpy 2-D array.r   r   r   zA.
It should be list of lists, numpy 2-D array or pandas DataFrame)r   r   r   rR   r   r   r   r   r   valuesr~   r   r/   r[   rO   r   s      r5   _data_to_2d_numpyr     s     $)$664xxE**$%$T[[1)$++u==

d4j))*& 7J 	J r4   cptrctypes._Pointerlengthc                     t        | t        j                  t        j                              r0t        j
                  j                  | |f      j                         S t        d      )z6Convert a ctypes float pointer array to a numpy array.r   zExpected float pointer)	r   r@   POINTERc_floatrR   	ctypeslibas_arrayr   RuntimeErrorr   r   s     r5   _cfloat32_array_to_numpyr     J    $v~~67||$$T&$;@@BB344r4   c                     t        | t        j                  t        j                              r0t        j
                  j                  | |f      j                         S t        d      )z7Convert a ctypes double pointer array to a numpy array.r   zExpected double pointer)	r   r@   r   c_doublerR   r   r   r   r   r   s     r5   _cfloat64_array_to_numpyr     sJ    $v78||$$T&$;@@BB455r4   c                     t        | t        j                  t        j                              r0t        j
                  j                  | |f      j                         S t        d      )4Convert a ctypes int pointer array to a numpy array.r   zExpected int32 pointer)	r   r@   r   rD   rR   r   r   r   r   r   s     r5   _cint32_array_to_numpyr     r   r4   c                     t        | t        j                  t        j                              r0t        j
                  j                  | |f      j                         S t        d      )r   r   zExpected int64 pointer)	r   r@   r   c_int64rR   r   r   r   r   r   s     r5   _cint64_array_to_numpyr     r   r4   stringc                 J    t        j                  | j                  d            S )z$Convert a Python string to C string.r   )r@   c_char_pencode)r   s    r5   rE   rE     s    ??6==122r4   ctyper   c                 $     | t        |      z  | S )z"Convert a Python array to C array.r   )r   r   s     r5   _c_arrayr     s    ECK&))r4   c                     t        | t        j                  t        j                  t        j                  f      r| j                         S t        | t        j                        r| j                         S | S )z3Convert numpy classes to JSON serializable objects.)r   rR   integerfloatingbool_itemr   tolistr   s    r5   _json_default_with_numpyr    sJ    #

BKK:;xxz	C	$zz|
r4   c                 t    t        | t              rdj                  d | D              }d| dS t        |       S )N,c              3   2   K   | ]  }t        |        y wr9   )rs   )r   vals     r5   r   z_to_string.<locals>.<genexpr>  s     2CH2   [])r   r   r   rs   )r6   val_lists     r5   
_to_stringr
    s7    !T882228*A1vr4   c                    | | syg }| j                         D ]  \  }}t        |t        t        t        f      st        |      r4|j                  | ddj                  t        t        |                    `t        |t        t        t        f      st        |      r|j                  | d|        |t        d| dt        |      j                           dj                  |      S )z>Convert Python dictionary to string, which is passed to C API.r   =r  zUnknown type of parameter:z, got: )itemsr   r   tuplesetr   r   r   mapr
  rs   r   _NUMERIC_TYPESr   r~   r   r/   )r[   pairskeyr  s       r5   _param_dict_to_strr    s    |4EJJL ZScD%-.2DS2ILLC5#((3z3+?"@!ABCc489[=MLLC5#(_8VDIDVDVCWXYYZ 88E?r4   c                   0    e Zd ZdZd	dZdedededdfdZy)
	_TempFilez,Proxy class to workaround errors on Windows.r7   c                     t        dd      5 }|j                  | _        t        | j                        | _        d d d        | S # 1 sw Y   | S xY w)Nlightgbm_tmp_T)prefixdelete)r   r   r   path)rk   fs     r5   	__enter__z_TempFile.__enter__  sF    tD 	(DITYYDI	( 	( s   ,AAexc_typeexc_valexc_tbNc                 n    | j                   j                         r| j                   j                          y y r9   )r  is_fileunlink)rk   r  r   r!  s       r5   __exit__z_TempFile.__exit__  s'    99II r4   )r7   r  )r/   r0   r1   r2   r  r   r%  r3   r4   r5   r  r    s+    6 s C D r4   r  c                       e Zd ZdZy)r#   zCustom deprecation warning.Nr.   r3   r4   r5   r#   r#     s    %r4   r#   c                       e Zd ZdZedeeee   f   fd       Ze	dede
e   fd       Ze	dedee   fd       Ze	dede
e   fd       Zy)	_ConfigAliasesNr7   c                     d} t        j                  d      }t        j                  |       }t        j                  t        j                  |            }t        t        j                  t        j                  |       t        j                  |      |             |j                  }|| kD  rt        j                  |      }t        j                  t        j                  |            }t        t        j                  t        j                  |      t        j                  |      |             t        j                  |j                  j                  d      d       S )N   r   r   c                 ^    | j                         D ci c]  \  }}||g|z    c}}S c c}}w r9   r  )r   kvs      r5   <lambda>z7_ConfigAliases._get_all_param_aliases.<locals>.<lambda>   s0    adajajalImY]YZ\]!aSSTW*Im Ims   )object_hook)r@   r   create_string_bufferr   	addressofrB   r   LGBM_DumpParamAliasesrF   rG   jsonloadsr   )
buffer_lentmp_out_lenstring_bufferptr_string_buffer
actual_lens        r5   _get_all_param_aliasesz%_ConfigAliases._get_all_param_aliases  s
   
nnQ'33J?"OOF,<,<],KL&&z*[)!	
 !&&

""77
CM &0@0@0O P**NN:.LL-% zz&&w/=m
 	
r4   argsc                     | j                   | j                         | _         t               }|D ]"  }|j                  | j	                  |             $ |S r9   )aliasesr<  r  update
get_sorted)clsr=  r   is       r5   getz_ConfigAliases.get#  sL    ;;446CKe 	*AJJs~~a()	*
r4   r   c                 ~    | j                   | j                         | _         | j                   j                  ||g      S r9   )r?  r<  rD  )rB  r   s     r5   rA  z_ConfigAliases.get_sorted,  s3    ;;446CK{{tdV,,r4   c                     | j                   | j                         | _         t        |      }|D ]8  }| j                   j                         D ]  }||v s|j	                  |        8 : |S r9   )r?  r<  r  r   r@  )rB  r=  r   argr?  s        r5   get_by_aliasz_ConfigAliases.get_by_alias2  sm    ;;446CK$i 	C;;--/ '>JJw'	
 
r4   )r/   r0   r1   r?  staticmethodr   rs   r   r<  classmethodr   rD  rA  rH  r3   r4   r5   r(  r(    s    G
Dd3i$8 
 
8  C   -c -d3i - -
 	 	S 	 	r4   r(  main_param_namedefault_valuec                 ~   t        |      }t        j                  |       }|D cg c]
  }|| k7  s	| }}| |j                         v r|D ]  }|j	                  |d        |S |D ]  }||j                         v s||   || <    n | |j                         v r|D ]  }|j	                  |d        |S ||| <   |S c c}w )a  Get a single parameter value, accounting for aliases.

    Parameters
    ----------
    main_param_name : str
        Name of the main parameter to get a value for. One of the keys of ``_ConfigAliases``.
    params : dict
        Dictionary of LightGBM parameters.
    default_value : Any
        Default value to use for the parameter, if none is found in ``params``.

    Returns
    -------
    params : dict
        A ``params`` dict with exactly one value for ``main_param_name``, and all aliases ``main_param_name`` removed.
        If both ``main_param_name`` and one or more aliases for it are found, the value of ``main_param_name`` will be preferred.
    N)r   r(  rA  keyspop)rK  r>   rL  r?  aparams         r5   _choose_param_valuerR  ?  s    & fF''8G!:QQ/%9q:G: &++-' 	$EJJud#	$  FKKM!&,UmF?#
 &++-' 	$EJJud#	$ ,F?M- ;s
   
B:B:ir   rn   )labelweight
init_scoregroupposition)splitgainc                     t        | t        j                        rZt        | j                  t        j                        r6| j                  j
                  s t        d       t        j                  |       S | S )z2Fix the memory of multi-dimensional sliced object.zsUsage of np.ndarray subset (sliced data) is not recommended due to it will double the peak memory cost in LightGBM.)r   rR   r   baserU   c_contiguousr   r   r   s    r5   _convert_from_sliced_objectr]    sQ    $

#
499bjj(Izz&&J 774= Kr4   c                    t        |       rt        j                  |       } t        |       rt	        |       } | j
                  j                  sJ | j                  t        j                  k(  rC| j                  j                  t        j                  t        j                              }t        }n| j                  t        j                  k(  rC| j                  j                  t        j                  t        j                              }t         }n;t#        d| j                   d      t#        dt%        |       j&                   d      ||| fS )z(Get pointer of float numpy array / list.z,Expected np.float32 or np.float64, met type()Unknown type()r   rR   rX   r   r]  rU   r\  rO   rS   r@   data_asr   r   _C_API_DTYPE_FLOAT32rT   r   _C_API_DTYPE_FLOAT64r~   r   r/   r[   ptr_data	type_datas      r5   _c_float_arrayrg    s    4zz$$*40zz&&&&::#{{**6>>&..+IJH,IZZ2::%{{**6>>&//+JKH,IJ4::,VWXYY-T
(;(;'<A>??i&&r4   c                    t        |       rt        j                  |       } t        |       rt	        |       } | j
                  j                  sJ | j                  t        j                  k(  rC| j                  j                  t        j                  t        j                              }t        }n| j                  t        j                  k(  rC| j                  j                  t        j                  t        j                              }t         }n;t#        d| j                   d      t#        dt%        |       j&                   d      ||| fS )z&Get pointer of int numpy array / list.z(Expected np.int32 or np.int64, met type(r_  r`  )r   rR   rX   r   r]  rU   r\  rO   int32r@   ra  r   rD   _C_API_DTYPE_INT32int64r   _C_API_DTYPE_INT64r~   r   r/   rd  s      r5   _c_int_arrayrm    s    4zz$$*40zz&&&&::!{{**6>>&..+IJH*IZZ288#{{**6>>&..+IJH*IFtzzlRSTUU-T
(;(;'<A>??i&&r4   c                     t        t        dt        d             }t        | t        j                  t        j
                  t        j                  f      xr t        | t        j                  |f       S )Nfloat128)ry   rR   r   
issubclassr   r   r   timedelta64)rO   ro  s     r5   _is_allowed_numpy_dtyperr    sQ    r:tDz2Hebjj"++rxx@Aw*UZ]_]k]kmu\vJwFwwr4   pandas_dtypes_seriesc                     | j                         D cg c]!  \  }}t        |j                        s| d| # }}}|rt        ddj	                  |             y c c}}w )Nz: zIpandas dtypes must be int, float or bool.
Fields with bad pandas dtypes: z, )r  rr  r   r   r   )rs  column_namepandas_dtypebad_pandas_dtypess       r5   r   r     s|     *>)C)C)E%K&|'8'89 -r,( 
 XY]YbYbctYuXvw
 	
 s   &Atarget_dtypec                    t        | j                         	 | j                  |d      S # t        $ r  | j	                  |d      j
                  cY S t        $ r$ | j                  |t        j                        cY S w xY w)NFr   r   )rO   na_value)	r   r   to_numpyr~   r   r   r   rR   nan)r[   rx  s     r5   _pandas_to_numpyr~    st     !-	B}}<e}<< < {{<e{4;;; B}}<"&&}AABs   * &A>)A>=A>feature_namecategorical_featurepandas_categoricalc                    t        | j                        dk7  s| j                  d   dk  rt        d      | j                  d      } |dk(  r"| j                  D cg c]  }t        |       }}t        | j                  | j                  d	      D cg c]  \  }}t        |t              s| }}}|D cg c]  }| |   j                  j                  r|  }}|0|D cg c]$  }t        | |   j                  j                        & }}nt        |      t        |      k7  rt        d
      t        ||d	      D ]U  \  }}t        | |   j                  j                        t        |      k7  s5| |   j                  j                  |      | |<   W |r7| |   j                  d       j!                  dt"        j$                  i      | |<   |dk(  r|}| j                  D cg c]  }|j&                   }	}|	j)                  t"        j*                         t#        j,                  |	 }
t/        | |
      |||fS c c}w c c}}w c c}w c c}w c c}w )Nr   r   r   z/Input data must be 2 dimensional and non empty.F)deepautoTstrictz9train and valid dataset categorical_feature do not match.c                 .    | j                   j                  S r9   )catcodesr;   s    r5   r/  z#_data_from_pandas.<locals>.<lambda>  s     r4   rx  )r   r   r   r   columnsrs   zipr   r   r   r  orderedr   
categoriesset_categoriesapplyreplacerR   r}  r   r   rS   result_typer~  )r[   r  r  r  colrO   cat_colscat_cols_not_orderedcategory	df_dtypesrx  s              r5   _data_from_pandasr    s#    4::!tzz!}q0JKK 99%9 D v,0LL9SC99 "$,,DIUZX]_rMsH  7?&\sd3immF[F[s&\&\!HPQd49==#;#;<QQx=C 233XYY +=dK 	CMCDIMM,,-h? IMM88BS		C h--.CDLLbRTRXRX\ZX f$2)-55I5RZZ >>9-L 	L9	 7 : ']Q 6s*   H<I-I8II#)I%I	file_namec                     t        j                  | t              }d| d}|(t        |d      5 }|j	                  |       d d d        |S |S # 1 sw Y   |S xY w)Ndefaultz
pandas_categorical:
rP  )r5  dumpsr  openwrite)r  r  categorical_json
pandas_strr  s        r5   _dump_pandas_categoricalr  "  sf     zz"4>VW()9(:"=J)S! 	 QGGJ	 :	 s   AA	model_strc                 p   d}t        |       }| t        |        }t        | d      5 }	 t        ||      }|j	                  |t
               |j                         }t        |      dk\  rn|dz  }G	 d d d        d   j                  d      j                         }|j                  |      sK|d   j                  d      j                         }n(|&|j                  dd|      }||d  j                         }j                  |      r!t        j                  |t        |      d        S y # 1 sw Y   xY w)	Nzpandas_categorical:rbr   r  r   r  r   )r   r   r  maxseekr	   	readlinesr   r   
startswithrfindr5  r6  )	r  r  
pandas_keyoffset
max_offsetr  lines	last_lineidxs	            r5   _load_pandas_categoricalr  .  s4    'J*oFi((
)T" 	aVZ0vx(u:?! 
 	 "I$$W-335	##J/b	((1779I		oodAv.cdO))+	J'zz)C
O$5677#	 	s   A	D,,D5c                       e Zd ZdZdZej                  deee	e
e   f   dej                  fd       Zej                  defd       Zy)r&   a  
    Generic data access interface.

    Object should support the following operations:

    .. code-block::

        # Get total row number.
        >>> len(seq)
        # Random access by row index. Used for data sampling.
        >>> seq[10]
        # Range data access. Used to read data in batch when constructing Dataset.
        >>> seq[0:100]
        # Optionally specify batch_size to control range data read size.
        >>> seq.batch_size

    - With random access, **data sampling does not need to go through all data**.
    - With range data access, there's **no need to read all data into memory thus reduce memory usage**.

    .. versionadded:: 3.3.0

    Attributes
    ----------
    batch_size : int
        Default size of a batch.
    i   r  r7   c                     t        d      )a  Return data for given row index.

        A basic implementation should look like this:

        .. code-block:: python

            if isinstance(idx, numbers.Integral):
                return self._get_one_line(idx)
            elif isinstance(idx, slice):
                return np.stack([self._get_one_line(i) for i in range(idx.start, idx.stop)])
            elif isinstance(idx, list):
                # Only required if using ``Dataset.subset()``.
                return np.array([self._get_one_line(i) for i in idx])
            else:
                raise TypeError(f"Sequence index must be integer, slice or list, got {type(idx).__name__}")

        Parameters
        ----------
        idx : int, slice[int], list[int]
            Item index.

        Returns
        -------
        result : numpy 1-D array or numpy 2-D array
            1-D array if idx is int, 2-D array if idx is slice or list.
        z=Sub-classes of lightgbm.Sequence must implement __getitem__()NotImplementedError)rk   r  s     r5   __getitem__zSequence.__getitem__h  s    8 ""abbr4   c                     t        d      )z"Return row count of this sequence.z9Sub-classes of lightgbm.Sequence must implement __len__()r  rk   s    r5   __len__zSequence.__len__  s     ""]^^r4   N)r/   r0   r1   r2   
batch_sizeabcabstractmethodr   intslicer   rR   r   r  r  r3   r4   r5   r&   r&   J  sp    6 JcuS%c%:; c

 c c: 	_ _ _r4   c                   t   e Zd ZdZdedeee      deee	f   de
fdZedddeee	f   d	d fd
       Zedeeef   deee	f   d	d fd       Zd3dZd	eee	f   fdZ	 	 	 	 	 	 	 d4dededede
de
de
de
de
d	efdZdedededed	ef
dZdej2                  dedededeej2                     d	eej2                  ef   fdZdej2                  dededed	eej2                  ef   f
dZd eej<                  j>                  ej<                  j@                  f   d!ej2                  d"d#d$d#d%d#d&ed'ed(e
d	e!fd)Z"d*ej<                  j@                  dedededeej2                     d	eej2                  ef   fd+Z#d*ej<                  j@                  dededed	ee!ef   f
d,Z$d*ej<                  j@                  dededed	ee!ef   f
d-Z%d.ej<                  j>                  dededed	ee!ef   f
d/Z&d.ej<                  j>                  dededed	ee!ef   f
d0Z'de(jR                  dededed	eej2                  ef   f
d1Z*d	efd2Z+y)5_InnerPredictorz_InnerPredictor of LightGBM.

    Not exposed to user.
    Used only for prediction, usually used for continued training.

    .. note::

        Can be converted from Booster, but cannot be converted to Booster.
    booster_handler  pred_parametermanage_handlec                    || _         || _        || _        t        |      | _        t        j                  d      }t        t        j                  | j                   t        j                  |                   |j                  | _        y)aX  Initialize the _InnerPredictor.

        Parameters
        ----------
        booster_handle : object
            Handle of Booster.
        pandas_categorical : list of list, or None
            If provided, list of categories for ``pandas`` categorical columns.
            Where the ``i``th element of the list contains the categories for the ``i``th categorical feature.
        pred_parameter : dict
            Other parameters for the prediction.
        manage_handle : bool
            If ``True``, free the corresponding Booster on the C++ side when this Python object is deleted.
        r   N)_handle!_InnerPredictor__is_manage_handler  r  r  r@   rA   rB   r   LGBM_BoosterGetNumClassesrF   rG   	num_class)rk   r  r  r  r  out_num_classs         r5   __init__z_InnerPredictor.__init__  sm    * &"/"40@Q**]+	
 ',,r4   boosterr!   r7   c                     t        j                  d      }t        t        j                  |j
                  t        j                  |                    | |j
                  |j                  |d      S )zInitialize an ``_InnerPredictor`` from a ``Booster``.

        Parameters
        ----------
        booster : Booster
            Booster.
        pred_parameter : dict
            Other parameters for the prediction.
        r   Fr  r  r  r  )r@   rA   rB   r   LGBM_BoosterGetCurrentIterationr  rF   r  )rB  r  r  out_cur_iters       r5   from_boosterz_InnerPredictor.from_booster  s_     ||A00\*	
 "??&99)	
 	
r4   
model_filec           	      0   t        j                         }t        j                  d      }t        t	        j
                  t        t        |            t        j                  |      t        j                  |                    | |t        |      |d      S )a  Initialize an ``_InnerPredictor`` from a text file containing a LightGBM model.

        Parameters
        ----------
        model_file : str or pathlib.Path
            Path to the model file.
        pred_parameter : dict
            Other parameters for the prediction.
        r   r  Tr  )
r@   r   rA   rB   r   LGBM_BoosterCreateFromModelfilerE   rs   rF   r  )rB  r  r  r  out_num_iterationss        r5   from_model_filez_InnerPredictor.from_model_file  sy      *#\\!_00s:'/0^,	
 )7*M)	
 	
r4   Nc                     	 | j                   r)t        t        j                  | j                               y y # t
        $ r Y y w xY wr9   )r  rB   r   LGBM_BoosterFreer  AttributeErrorr  s    r5   __del__z_InnerPredictor.__del__  s>    	&&400>? ' 		s   48 	AAc                     | j                   j                         }|j                  dd        |j                  dd        |S )Nhandler  )__dict__r   rO  )rk   thiss     r5   __getstate__z_InnerPredictor.__getstate__  s5    }}!!#4 D!r4   r[   start_iterationnum_iteration	raw_score	pred_leafpred_contribdata_has_headervalidate_featuresc	                 t	   t        |t              rt        d      t        |t              r|r|j                  D 	cg c]  }	t        |	       }
}	t        j                  t        |
      z         }|
D 	cg c]  }	|	j                  d       c}	|dd t        t        j                  | j                  |t        j                  t        |
                         t        |t              rt        |dd| j                         d   }t"        }|rt$        }|rt&        }|rt(        }t        |t
        t*        f      rt-               5 }t        t        j.                  | j                  t1        t        |            t        j                  |      t        j                  |      t        j                  |      t        j                  |      t1        | j2                        t1        |j4                                     t7        j8                  |j4                  t6        j:                        }|j<                  d   }ddd       nqt        |t>        j@                  jB                        r| jE                  ||||      \  }}n3t        |t>        j@                  jF                        r| jI                  ||||	      \  }}nt        |t6        jJ                        r| jM                  ||||
      \  }}ntO        jP                  |      r,| jS                  tU        jV                  |      |||      \  }}nt        |tX              r/	 t7        jZ                  |      }| jM                  ||||
      \  }}nC	 ta        d       t>        j@                  jC                  |      }| jE                  ||||      \  }}|rjg                  t6        jh                        }t        tX        t>        j@                  jj                  f      }|sU|jl                  k7  s|s|rB|jl                  |z  dk(  r|jo                  |d      }|S t_        d|jl                   d| d      |S c c}	w c c}	w # 1 sw Y   xY w# t\        $ r}t_        d      |d}~ww xY w# t\        $ r'}t        dtc        |      jd                         |d}~ww xY w)aU  Predict logic.

        Parameters
        ----------
        data : str, pathlib.Path, numpy array, pandas DataFrame, scipy.sparse, pyarrow Table or polars DataFrame
            Data source for prediction.
            If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM).

        .. versionadded:: 4.2.0
            Support for ``pyarrow`` inputs

        .. versionadded:: 4.7.0
            Support for ``polars`` inputs

        start_iteration : int, optional (default=0)
            Start index of the iteration to predict.
        num_iteration : int, optional (default=-1)
            Iteration used for prediction.
        raw_score : bool, optional (default=False)
            Whether to predict raw scores.
        pred_leaf : bool, optional (default=False)
            Whether to predict leaf index.
        pred_contrib : bool, optional (default=False)
            Whether to predict feature contributions.
        data_has_header : bool, optional (default=False)
            Whether data has header.
            Used only for txt data.
        validate_features : bool, optional (default=False)
            If True, ensure that the features used to predict match the ones used to train.
            Used only if data is pandas DataFrame.

            .. versionadded:: 4.0.0

        Returns
        -------
        result : numpy array, scipy.sparse or list of scipy.sparse
            Prediction result.
            Can be sparse or a list of sparse objects (each element represents predictions for one class) for feature contributions (when ``pred_contrib=True``).
        zGCannot use Dataset instance for prediction, please use raw data insteadr   Nr  r[   r  r  r  r   r   csrr  r  predict_typecscr  r  r  )rJ   r  r  r  )r[   r  r  r  z(Cannot convert data list to numpy array.z'Converting data to scipy sparse matrix.zCannot predict data for type r  zLength of predict result (z) cannot be divide nrow (r_  )8r   r"   r~   r   r  rs   r@   r   r   r   rB   r    LGBM_BoosterValidateFeatureNamesr  rA   r  r  _C_API_PREDICT_NORMAL_C_API_PREDICT_RAW_SCORE_C_API_PREDICT_LEAF_INDEX_C_API_PREDICT_CONTRIBr   r  LGBM_BoosterPredictForFilerE   r  r   rR   loadtxtrT   r   scipysparse
csr_matrix_InnerPredictor__pred_for_csr
csc_matrix_InnerPredictor__pred_for_cscr   _InnerPredictor__pred_for_np2dnwdis_into_dataframe"_InnerPredictor__pred_for_narwhalsnwfrom_nativer   r   BaseExceptionr   r   r   r/   r   ri  spmatrixsizereshape)rk   r[   r  r  r  r  r  r  r  r6   
data_names	ptr_namesr  r  predsnrowerrr  	is_sparses                      r5   predictz_InnerPredictor.predict  s-   d dG$effdL).?*.,,7Q#a&7J73z?:=I7AB!AHHW-BIaL55LLLLZ1 dL)$#$*#'#:#:	
 D -3L4L1LdS$K( &33s4y)_5\2_5]3t223qvv	 

166<{{1~& & ell556-- /+)	 . KE4 ell556-- /+)	 . KE4 bjj).. /+)	 / KE4 ""4(22^^D) /+)	 3 KE4 d#Vxx~ .. /+)	 / KE4`FGll--d3 -- /+)	 . KE4 LL*EutU\\-B-B&CD	ejjD0IzzD A%dB/  !#=ejj\Ibcgbhhi!jkkS 8B4& &` ! V !KLRUUV ! `"?T
@S@S?T UV\__`sH   Q4QC2Q?Q* .*R Q'*	R3Q??R	R7"R22R7r  r  c                   |t         kD  rt        dt          d      t        j                  d      }t	        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |      t        j                  |                   |j                  S )zGet size of prediction result.zXLightGBM cannot perform prediction for data with number of rows greater than MAX_INT32 (zP).
You can split your data into chunks and then concatenate predictions for themr   )
_MAX_INT32r$   r@   r   rB   r   LGBM_BoosterCalcNumPredictr  rA   rF   rG   )rk   r  r  r  r  n_predss         r5   __get_num_predsz_InnerPredictor.__get_num_preds  s     *??Il K<<  ..#++T"\*_-]+W%		
 }}r4   rJ   r
  c                    t        |      \  }}t        |      \  }}	}
| j                  |||j                  d   |      }|&t	        j
                  |t        j                        }n1t        |j                        dk7  st        |      |k7  rt        d      t        j                  d      }t        t        j                  | j                  |t        j                  |	      t        j                   |j                  d         t        j                   |j                  d         t        j                  |      t        j                  |      t        j                  |      t        j                  |      t#        | j$                        t        j&                  |      |j                  j)                  t        j*                  t        j,                                           ||j.                  k7  rt        d      ||j                  d   fS )Nr   r  r  r  r  r   r   +Wrong length of pre-allocated predict array Wrong length for predict results)r\   rg  _InnerPredictor__get_num_predsr   rR   emptyrT   r   r   r@   r   rB   r   LGBM_BoosterPredictForMatr  rA   rD   rE   r  rF   ra  r   r   rG   )rk   rJ   r  r  r  r
  r[   rZ   re  type_ptr_data_r  out_num_predss                r5   __inner_predict_np2dz$_InnerPredictor.__inner_predict_np2d  s    %S)f%3D%9"-&&+'1%	 ' 
 =HHWBJJ7E"c%jG&;JKKq)**]+syy|,syy|,V$\*_-]+t**+]+$$V^^FOO%DE	
  m)))?@@ciil""r4   c           
         t        |j                        dk7  rt        d      |j                  d   }|t        kD  r,t	        j
                  t        |t              }t	        j                  dgt        |      z   |gz         D cg c]   }| j                  ||t        |      |      " }}t	        j                  dg|z   t        j                        j                         }	t	        j                  t        |      t        j                        }
t!        t	        j"                  ||      t!        |	|	dd d	      d	      D ]!  \  }\  }}| j%                  |||||
|| 
       # |
|fS | j%                  ||||d
      S c c}w )zPredict for a 2-D numpy matrix.r   z1Input numpy.ndarray or list must be 2 dimensionalr   r  r   r   NTr  )rJ   r  r  r  r
  )r   r   r   r  rR   arangediffr   r  r  r   intpcumsumr  sumrT   r  array_split#_InnerPredictor__inner_predict_np2d)rk   rJ   r  r  r  r  sectionsrC  r  n_preds_sectionsr
  chunkstart_idx_predend_idx_preds                 r5   __pred_for_np2dz_InnerPredictor.__pred_for_np2d  s    syy>QPQQyy|*yyT:>H !tH~!5!>?  $$$3"/Q!-	 % G   "xxgRWWELLNHHS\<E9<sH-s3CEUVWVXEYbf/gpt: 
55 ))$3"/!-|< * 	
 $;,, /+) -  1s   %E?cs	out_shapeout_ptr_indptrr   out_ptr_indicesout_ptr_dataindptr_type	data_typeis_csrc	                    |d   }	|d   }
|t         k(  rt        ||
      }n"|t        k(  rt        ||
      }nt	        d      |t
        k(  rt        ||	      }n"|t        k(  rt        ||	      }nt	        d      t        ||	      }|j                  j                  d   }|s|dz  }t        j                  ||j                  d   |z        }g }d}|D ]  }||j                  d   dz
     }|||d   z   ||z    }|||d   z   ||z    }||z  }|j                  d   |j                  d   dz   g}|r3|j                  t        j                  j!                  |||f|             |j                  t        j                  j#                  |||f|              t%        t'        j(                  |||t+        j,                  |      t+        j,                  |                   t/        |      dk(  r|d   S |S )Nr   r   r   z'Expected int32 or int64 type for indptrz)Expected float32 or float64 type for data)rj  r   rl  r   r~   rb  r   rc  r   indptrr   rR   rX  r   r  r  r  r  rB   r   LGBM_BoosterFreePredictSparser@   rA   r   )rk   r-  r.  r/  r0  r1  r2  r3  r4  data_indices_len
indptr_len
out_indptrout_dataout_indicesper_class_indptr_shapeout_indptr_arrayscs_output_matricesr  	cs_indptrmatrix_indptr_len
cs_indicescs_datacs_shapes                          r5   __create_sparse_nativez&_InnerPredictor.__create_sparse_native  s    %Q<q\
,,/^JWJ../^JWJEFF,,/\JZ[H../\JZ[HGHH,/JZ[!#!3"a'"HHZ1A1A!1DG]1]^* 	oI ))//!*<q*@ A$Vil%:VFW=WXJv	!4v@Q7QRG''FRXXa[1_5H"))%,,*A*A7JXaBbdl*mn"))%,,*A*A7JXaBbdl*mn	o 	..[)Y'	
 !"a'%a((!!r4   r  c                    t        |j                        dz
  }| j                  ||||      }|&t        j                  |t        j
                        }n1t        |j                        dk7  st        |      |k7  rt        d      t        j                  d      }t        |j                        \  }	}
}t        |j                        \  }}}|j                  d   t        k  sJ |j                  j                  t        j                   d      }t#        t%        j&                  | j(                  |	t        j*                  |
      |j                  j-                  t        j.                  t        j0                              |t        j*                  |      t        j                  t        |j                              t        j                  t        |j                              t        j                  |j                  d         t        j*                  |      t        j*                  |      t        j*                  |      t3        | j4                        t        j6                  |      |j                  j-                  t        j.                  t        j8                                           ||j:                  k7  rt        d      ||fS )	Nr   r  r   r  r   Frz  r  )r   r6  r  rR   r  rT   r   r   r@   r   rm  rg  r[   r  indicesr   ri  rB   r   LGBM_BoosterPredictForCSRr  rA   ra  r   rD   rE   r  rF   r   rG   )rk   r  r  r  r  r
  r  r  r  
ptr_indptrtype_ptr_indptrr  re  r  csr_indicess                  r5   __inner_predict_csrz#_InnerPredictor.__inner_predict_csrV  s     3::"&&+'%	 ' 
 =HHWBJJ7E"c%jG&;JKKq))5cjj)A&
OQ%3CHH%="-yy|z)))kk(((>**_-""**6>>&..+IJ]+s3::/s388}-syy|,\*_-]+t**+]+$$V^^FOO%DE	
& m)))?@@d{r4   c                    t        |j                        \  }}}t        |j                        \  }}	}
|j                  j                  t        j                  d      }t        }|t        k(  r) t        j                  t        j                               }n( t        j                  t        j                               } t        j                  t        j                               }|	t        k(  r) t        j                  t        j                               }n( t        j                  t        j                                }t        j"                  dt        j$                        }t'        t)        j*                  | j,                  |t        j.                  |      |j                  j1                  t        j                  t        j                              |t        j.                  |	      t        j                  t3        |j                              t        j                  t3        |j                              t        j                  |j4                  d         t        j.                  |      t        j.                  |      t        j.                  |      t7        | j8                        t        j.                  |      |j                  j1                  t        j                  t        j                              t        j:                  |      t        j:                  |      t        j:                  |                   | j=                  |||||||	d      }t3        |j                        dz
  }||fS )NFrz  r   r   r   Tr-  r.  r/  r0  r1  r2  r3  r4  )rm  r6  rg  r[   rG  r   rR   ri  _C_API_MATRIX_TYPE_CSRrj  r@   r   rD   r   rb  r   r   r  rk  rB   r   LGBM_BoosterPredictSparseOutputr  rA   ra  r   r   rE   r  rF   %_InnerPredictor__create_sparse_native)rk   r  r  r  r  rI  rJ  __re  r  r  rK  matrix_typer/  r0  r1  r.  matricesr  s                      r5   __inner_predict_csr_sparsez*_InnerPredictor.__inner_predict_csr_sparse  sQ    +7szz*B'
OR%3CHH%="-kk(((>,00;V^^FNN;=N;V^^FNN;=N8&..8:0096>>&..9;L:6>>&//:<LHHQbhh/	00_-""**6>>&..+IJ]+s3::/s388}-syy|,\*_-]+t**+[)  (()GH^,_-\*%	
, ..)+%'# / 	
 3::"~r4   c           
         |t         k(  r| j                  ||||      S t        |j                        dz
  }|t        kD  r-dgt        t        j                  t        |t                    z   |gz   }t        j                  |      D cg c]   }| j                  ||t        |      |      " }}t        j                  dg|z   t        j                        j                         }	t        j                  t        |      t        j                         }
t#        t#        ||dd d      t#        |	|	dd d      d      D ]'  \  \  }}\  }}| j%                  ||| ||||
|| 	       ) |
|fS | j%                  ||||d	      S c c}w )
zPredict for a CSR data.r  r   r   r  r   NTr  )r  r  r  r  r
  )r  )_InnerPredictor__inner_predict_csr_sparser   r6  r  r   rR   r   r!  r  r  r   r"  r#  r  r$  rT   r  "_InnerPredictor__inner_predict_csr)rk   r  r  r  r  r  r'  rC  r  r(  r
  	start_idxend_idxr*  r+  s                  r5   __pred_for_csrz_InnerPredictor.__pred_for_csr  s    1122 /+)	 3   3::"*sT"))Jj"IJJdVSH *  $$$3"/Q!-	 % G   "xxgRWWELLNHHS\<EHKHhqrl48$&6qr&:4HI D$G&D~| ((Ig.$3"/!-|< )  $;++ /+) ,  5s   %Fr  c                    t        |j                        \  }}}t        |j                        \  }}	}
|j                  j                  t        j                  d      }t        }|t        k(  r) t        j                  t        j                               }n( t        j                  t        j                               } t        j                  t        j                               }|	t        k(  r) t        j                  t        j                               }n( t        j                  t        j                                }t        j"                  dt        j$                        }t'        t)        j*                  | j,                  |t        j.                  |      |j                  j1                  t        j                  t        j                              |t        j.                  |	      t        j                  t3        |j                              t        j                  t3        |j                              t        j                  |j4                  d         t        j.                  |      t        j.                  |      t        j.                  |      t7        | j8                        t        j.                  |      |j                  j1                  t        j                  t        j                              t        j:                  |      t        j:                  |      t        j:                  |                   | j=                  |||||||	d      }|j4                  d   }||fS )NFrz  r   r   r   rN  )rm  r6  rg  r[   rG  r   rR   ri  _C_API_MATRIX_TYPE_CSCrj  r@   r   rD   r   rb  r   r   r  rk  rB   r   rP  r  rA   ra  r   r   rE   r  rF   rQ  )rk   r  r  r  r  rI  rJ  rR  re  r  r  csc_indicesrS  r/  r0  r1  r.  rT  r  s                      r5   __inner_predict_sparse_cscz*_InnerPredictor.__inner_predict_sparse_csc  sL    +7szz*B'
OR%3CHH%="-kk(((>,00;V^^FNN;=N;V^^FNN;=N8&..8:0096>>&..9;L:6>>&//:<LHHQbhh/	00_-""**6>>&..+IJ]+s3::/s388}-syy|,\*_-]+t**+[)  (()GH^,_-\*%	
, ..)+%'# / 	
 yy|~r4   c                    |j                   d   }|t        kD  r#| j                  |j                         |||      S |t        k(  r| j                  ||||      S | j                  ||||      }t        j                  |t        j                        }t        j                  d      }t        |j                        \  }	}
}t        |j                        \  }}}|j                   d   t        k  sJ |j                   j#                  t        j$                  d      }t'        t)        j*                  | j,                  |	t        j.                  |
      |j                  j1                  t        j2                  t        j4                              |t        j.                  |      t        j                  t7        |j                              t        j                  t7        |j                              t        j                  |j                   d         t        j.                  |      t        j.                  |      t        j.                  |      t9        | j:                        t        j<                  |      |j                  j1                  t        j2                  t        j>                                           ||j@                  k7  rtC        d      ||fS )	zPredict for a CSC data.r   r  r  r  r   Frz  r  )"r   r  r  tocsrr  )_InnerPredictor__inner_predict_sparse_cscr  rR   r  rT   r@   r   rm  r6  rg  r[   rG  r   ri  rB   r   LGBM_BoosterPredictForCSCr  rA   ra  r   rD   r   rE   r  rF   r   rG   r   )rk   r  r  r  r  r  r  r
  r  rI  rJ  rR  re  r  r  r^  s                   r5   __pred_for_cscz_InnerPredictor.__pred_for_csc1  s1    yy|*&&IIK /+)	 '   1122 /+)	 3   &&+'%	 ' 
 

3q)*6szz*B'
OR%3CHH%="-yy|z)))kk(((>**_-""**6>>&..+IJ]+s3::/s388}-syy|,\*_-]+t**+]+$$V^^FOO%DE	
& m)))?@@d{r4   c                    | j                  |||j                  d   |      }t        j                  |t        j                        }t        j                  d      }|j                         }t        t        j                  | j                  t        |      t        j                  |      t        j                  |      t        j                  |      t        | j                        t        j                   |      |j
                  j#                  t        j$                  t
        j&                                           ||j(                  k7  rt+        d      ||j                  d   fS )z!Predict for a narwhals DataFrame.r   r  r   r  )r  r   rR   r  rT   r@   r   __arrow_c_stream__rB   r   !LGBM_BoosterPredictForArrowStreamr  r   rA   rE   r  rF   ra  r   r   rG   r   )	rk   r[   r  r  r  r  r
  r  r   s	            r5   __pred_for_narwhalsz#_InnerPredictor.__pred_for_narwhalsn  s    &&+'A%	 ' 
 

3q) ++-	225i@\*_-]+t**+]+$$V^^FOO%DE		
 m)))?@@djjm##r4   c                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S zGet the index of the current iteration.

        Returns
        -------
        cur_iter : int
            The index of the current iteration.
        r   r@   rA   rB   r   r  r  rF   rG   rk   r  s     r5   current_iterationz!_InnerPredictor.current_iteration  H     ||A00\*	
 !!!r4   r7   N)r   r  FFFFF),r/   r0   r1   r2   _BoosterHandler   r   r   rs   r   boolr  rJ  r  r   r   r  r  r  _LGBM_PredictDataTyper  _LGBM_PredictReturnTyper  r  rR   r   r   r&  r  r  r  r  r  _LGBM_PredictSparseReturnTyperQ  rX  rW  r  rb  r  r  	DataFramer  rm  r3   r4   r5   r  r    s   !-&!- %T$Z0!- S#X	!-
 !-F 

 S#X
 
	
 
8 
#t)$
 S#X
 
	
 
<d38n   !" %"'^#^ ^ 	^
 ^ ^ ^ ^  ^ 
!^@  	
   
:'#ZZ'# '# 	'#
 '# 

#'# 
rzz3	'#R-ZZ- - 	-
 - 
rzz3	-^<"%,,))5<<+B+BBC<" ::<" *	<"
 +<" (<" <" <" <" 
'<"|0\\$$0 0 	0
 0 

#0 
rzz3	0d8\\$$8 8 	8
 8 
,c1	28t3\\$$3 3 	3
 3 
,c1	23j8\\$$8 8 	8
 8 
,c1	28t;\\$$; ; 	;
 ; 
,c1	2;z"$ll"$ "$ 	"$
 "$ 
rzz3	"$H"3 "r4   r  c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 	 dTdedee   ded    dee   dee   dee	   d	e
d
edeeeef      dedee   fdZdUdZdedej*                  fdZdededd fdZdeej*                     deej*                     dededd f
dZdej*                  dd fdZdeeef   fdZdVdZdee   dedeeee   ej*                  f      dd fdZ dee   dee   ded    dee   dee   dee	   dee   d	e
d
edeeeef      dee   dd fdZ!e"d ee#   d!e$e   de%ej*                     fd"       Z&d ee#   dede'eej*                     eej*                     f   fd#Z(d ee#   dee   dd fd$Z)d%ej*                  d&edee   dd fd'Z*d(eej*                     d&edee   dd fd)Z+d*e,jZ                  j\                  d&edee   dd fd+Z/d,e,jZ                  j`                  d&edee   dd fd-Z1de2jf                  d&edee   dd fd.Z4e"deeef   d/eeef   d0e5e   defd1       Z6dVd2Z7	 	 	 	 	 	 dWdedee   dee   dee   dee	   deeeef      dee   dd fd3Z8	 dXdee   deeeef      dd fd4Z9d5eee:f   dd fd6Z;deeeef      dd fd7Z<dVd8Z=d9edee>   dd fd:Z?d9edeej*                     fd;Z@d
edd fd<ZAdee   dd fd=ZBdYd>ZCd	e
dd fd?ZDdee   dd fd@ZEdee   dd fdAZFdee	   dd fdBZGdee   dd fdCZHdee   dd fdDZIdee   fdEZJdee   fdFZKdee   fdGZLdee	   fdHZMdee   fdIZNdee   fdJZOdee   fdKZPdefdLZQdefdMZRdNeeef   defdOZSdZdPede5d    fdQZTd[dRZUd5eee:f   dd fdSZVy)\r"   aO  
    Dataset in LightGBM.

    LightGBM does not train on raw data.
    It discretizes continuous features into histogram bins, tries to combine categorical features,
    and automatically handles missing and infinite values.

    This class handles that preprocessing, and holds that alternative representation of the input data.
    Nr[   rS  	referencerT  rV  rU  r  r  r>   free_raw_datarW  c                 .   d| _         || _        || _        || _        || _        || _        || _        || _        || _        || _	        t        |	      | _        |
| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        y)a  Initialize Dataset.

        Parameters
        ----------
        data : str, pathlib.Path, numpy array, pandas DataFrame, scipy.sparse, Sequence, list of Sequence, list of numpy array, pyarrow Table or polars DataFrame
            Data source of Dataset.
            If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM) or a LightGBM Dataset binary file.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        label : list, numpy 1-D array, pandas Series / one-column DataFrame, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Label of the data.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        reference : Dataset or None, optional (default=None)
            If this is Dataset for validation, training data should be used as reference.
        weight : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Weight for each instance. Weights should be non-negative.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        group : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Group/query data.
            Only used in the learning-to-rank task.
            sum(group) = n_samples.
            For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
            where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), pyarrow ChunkedArray, pyarrow Table (for multi-class task), polars Series, polars DataFrame (for multi-class task) or None, optional (default=None)
            Init score for Dataset.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        feature_name : list of str, or 'auto', optional (default="auto")
            Feature names.
            If 'auto' and data is pandas DataFrame, pyarrow Table, or polars DataFrame, data columns names are used.
        categorical_feature : list of str or int, or 'auto', optional (default="auto")
            Categorical features.
            If list of int, interpreted as indices.
            If list of str, interpreted as feature names (need to specify ``feature_name`` as well).
            If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.
            All values in categorical features will be cast to int32 and thus should be less than int32 max value (2147483647).
            Large values could be memory consuming. Consider using consecutive integers starting from zero.
            All negative values in categorical features will be treated as missing values.
            The output cannot be monotonically constrained with respect to a categorical feature.
            Floating point numbers in categorical features will be rounded towards 0.
        params : dict or None, optional (default=None)
            Other parameters for Dataset.
        free_raw_data : bool, optional (default=True)
            If True, raw data is freed after constructing inner Dataset.
        position : numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Position of items used in unbiased learning-to-rank task.
        NTr   F)r  r[   rS  rw  rT  rV  rW  rU  r  r  r   r>   rx  used_indices_need_slice
_predictorr  _params_back_upversion
_start_row_has_non_default_feature_names)rk   r[   rS  rw  rT  rV  rU  r  r  r>   rx  rW  s               r5   r  zDataset.__init__  s    t 26	
"
 $<HJ] v&*15598<9= 5:+r4   r7   c                 D    	 | j                          y # t        $ r Y y w xY wr9   )_free_handler  r  s    r5   r  zDataset.__del__$  s%    	 		s    	r=   c          
         t        | j                               }t        ||      }t        j                  |t        j
                        }t        |      \  }}}t        j                  d      }t        t        j                  t        j                  |      t        |      |t        j                  |                   ||j                  k(  sJ |S )aD  Get an array of randomly chosen indices from this ``Dataset``.

        Indices are sampled without replacement.

        Parameters
        ----------
        total_nrow : int
            Total number of rows to sample from.
            If this value is greater than the value of parameter ``bin_construct_sample_cnt``, only ``bin_construct_sample_cnt`` indices will be used.
            If Dataset has multiple input data, this should be the sum of rows of every file.

        Returns
        -------
        indices : numpy array
            Indices for sampled data.
        r   r   )r  
get_paramsrI   rR   r  ri  rm  r@   rD   rB   r   LGBM_SampleIndicesrE   rF   rG   )rk   r=   	param_strrH   rG  re  r  actual_sample_cnts           r5   _create_sample_indiceszDataset._create_sample_indices*  s    " 't'89	&z9=
((:RXX6%g.!Q"NN1-##z*y!./		
 .44444r4   ref_datasetc           	          t        j                         | _        t        t	        j
                  |t        j                  |      t        j                  | j                                     | S )ag  Create dataset from a reference dataset.

        Parameters
        ----------
        total_nrow : int
            Number of rows expected to add to dataset.
        ref_dataset : object
            Handle of reference dataset to extract metadata from.

        Returns
        -------
        self : Dataset
            Constructed Dataset object.
        )r@   r   r  rB   r   LGBM_DatasetCreateByReferencer   rF   )rk   r=   r  s      r5   _init_from_ref_datasetzDataset._init_from_ref_datasetL  sN    & (..z*T\\*	
 r4   sample_datasample_indicesrH   c                    t        |      }t        |      |k(  sJ d       t        |      D ]  }||   j                  t        j                  k7  rt        d| d||   j                   d      ||   j                  t        j                  k7  sct        d| d||   j                   d        t        j                  t        j                        |z         } t        j                  t        j                        |z         }t        |      D ]*  }t        ||         d   ||<   t        ||         d   ||<   , t        j                  |D 	cg c]  }	t        |	       c}	t        j                        }
t        |
      \  }}}t        j                         | _        t!        | j#                               }t%        t'        j(                  t        j*                  |t        j                  t        j                  t        j                                    t        j*                  |t        j                  t        j                  t        j                                    t        j                  |      |t        j                  |      t        j                  |      t        j,                  |      t/        |      t        j0                  | j                        	             | S c c}	w )	a  Create Dataset from sampled data structures.

        Parameters
        ----------
        sample_data : list of numpy array
            Sample data for each column.
        sample_indices : list of numpy array
            Sample data row index for each column.
        sample_cnt : int
            Number of samples.
        total_nrow : int
            Total number of rows for all input files.

        Returns
        -------
        self : Dataset
            Constructed Dataset object.
        z&#sample data column != #column indiceszsample_data[z] type z is not doublezsample_indices[z is not int32r   r   )r   rangerO   rR   doubler   ri  r@   r   r   rD   rg  rm  r   r   r  r  r  rB   r   #LGBM_DatasetCreateFromSampledColumncastr   rE   rF   )rk   r  r  rH   r=   ncolrC  sample_col_ptrindices_col_ptrdnum_per_colnum_per_col_ptrr  
params_strs                 r5   _init_from_samplezDataset._init_from_samplei  sE   2 >";4'Q)QQ't 	eA1~##ryy0 <s'+a.:N:N9O~!^__a &&"((2 ?1#W^A=N=T=T<UUb!cdd		e 0Vv~~foo/NQU/U.X /TfnnV^^.Lt.S-Vt 	DA .{1~ >q AN1!-nQ.?!@!COA	D hh?1A?rxxP ,[ 9A('(9:
44NFNN6>>&//;Z,[\OV^^FNN6>><Z-[\t$z*z*z*z"T\\*
	
 %  @s   K$c                    |j                   \  }}|j                  |j                        }t        |      \  }}}t	        t        j                  | j                  ||t        j                  |      t        j                  |      t        j                  | j                                     | xj                  |z  c_
        | S )zAdd rows to Dataset.

        Parameters
        ----------
        data : numpy 1-D array
            New data to add to the Dataset.

        Returns
        -------
        self : Dataset
            Dataset object.
        )r   r  r  rg  rB   r   LGBM_DatasetPushRowsr  r@   rD   r  )rk   r[   r  r  data_ptrr3  r  s          r5   
_push_rowszDataset._push_rows  s     ZZ
d||DII&!/!5)Q%%t$t$t/		
 	4r4   c                     | j                   \t        j                  ddddddddd	d
ddddddddddd      }| j                   j                         D ci c]  \  }}||v s|| c}}S i S c c}}w )zGet the used parameters in the Dataset.

        Returns
        -------
        params : dict
            The used parameters in this Dataset object.
        bin_construct_sample_cntr  data_random_seedenable_bundlefeature_pre_filterforcedbins_filenamegroup_columnheaderignore_columnis_enable_sparselabel_columnlinear_treemax_binmax_bin_by_featuremin_data_in_binpre_partitionprecise_float_parser	two_rounduse_missingweight_columnzero_as_missing)r>   r(  rD  r  )rk   dataset_paramsr-  r.  s       r5   r  zDataset.get_params  s     ;;"+//*%"$%"$!&!+N. &*[[%6%6%8PTQA<OAqDPPI Qs   A+ A+c                     | j                   /t        t        j                  | j                                d | _         d| _        | j
                  d | _        | S )NT)r  rB   r   LGBM_DatasetFreer{  rz  r[   r  s    r5   r  zDataset._free_handle  sJ    <<#t,,T\\:;DL(DIr4   	predictorrz  c                 N    d}t        |t        t        f      r3 j                  't	         fdt
        j                  d      D              } j                         }|u|j                  |d|      }|j                         }|Ɖ j                  rJ t        |t        t        f      rt        j                  ||j                  z  t        j                        }|t        |      k(  sJ t!        t        |            D ]G  }t!        |j                        D ]-  }	|||   |j                  z  |	z      |||j                  z  |	z   <   / I |}|j                  dkD  rt        j                  |j"                  t        j                        }
t!        |      D ]:  }t!        |j                        D ]   }	|||j                  z  |	z      |
|	|z  |z   <   " < |
}n? j$                  1t        j&                   j$                  dt        j                  	      }n S  j)                  |        S )
NFc              3   V   K   | ]   }j                   j                  |d        " yw)FN)r>   rD  )r   aliasrk   s     r5   r   z7Dataset._set_init_score_by_predictor.<locals>.<genexpr>  s      !jE$++//%"?!js   &)r  T)r[   r  r  r   r   g        )
fill_valuerO   )r   rs   r   r>   anyr(  rD  num_datar  rY   r{  rR   r  r  rT   r   r  r  rU  	full_likeset_init_score)rk   r  r[   rz  r  r  rU  sub_init_scorerC  jnew_init_scores   `          r5   _set_init_score_by_predictorz$Dataset._set_init_score_by_predictor  s     dS$K(T[[-D!!j^M_M_`hMi!jjO==? CLCTCT / DU DJ
 $))+J'++++dS$K0%'XXh9L9L.LTVT^T^%_N#s<'8888"3|#45 !&y':':!; AJT ,Q)2E2E E IKN1y/B/B+BQ+FG
 "0J""Q&!#*//!Lx cA"9#6#67 c;Ea)J]J]F]`aFa;bq8|a'78cc ,
__(doo#RZZXJKJ'r4   c           
         |	d | _         | S ||j                  | _        |j                  }	t        |t              r#t        |||	| j                        \  }}}	| _        t        j                  |      r2|dk(  r-t        j                  |      j                  j                         }|dk7  | _        |
i n|
}
t        j                  | j                  j                         j"                  j%                         }|
j%                         D ]  }||v st'        | d| d        t        |	t(              r#t+               }i }t        |t(              rt-        |      D ci c]  \  }}||
 }}}|	D ]q  }t        |t.              r||v r|j1                  ||          ,t        |t2              r|j1                  |       Nt5        dt7        |      j8                   d| d       |rqt:        j=                  d      D ]K  }||
v st        |
|   t(              rt+        |
|         |k(  st'        | d	       |
j?                  |d        M tA        |      |
d
<   tC        |
      }|
| _"        d }t        |tF              r|jI                         j                   }n|t5        d      t        |t.        tJ        f      rttM        jN                         | _         tQ        tS        jT                  tW        t/        |            tW        |      |tM        jX                  | j                                      nt        |tZ        j\                  j^                        r| ja                  |||       ngt        |tZ        j\                  jb                        r| je                  |||       n-t        |tf        jh                        r| jk                  |||       nt        j                  |      r(| jm                  t        j                  |      ||       nt        |t(              rXto        |      dkD  rJtq        |      r| js                  |||       ntu        |      r| jw                  ||       ndt5        d      t        |tx              r| jw                  |g|       n4	 tZ        j\                  j_                  |      }| ja                  |||       || j}                  |       | j                         t        d      || j                  |       || j                  |       || j                  |       t        |t              r.| j                  |t'        d       | j                  ||d        n7|| j                  |       n#|!t5        dt7        |      j8                         | j                  |      S c c}}w # tz        $ r'}t5        dt7        |      j8                         |d }~ww xY w)Nr  r  zD keyword has been found in `params` and will be ignored.
Please use z< argument of the Dataset constructor to pass this parameter.r   z) or unknown name(z) in categorical_featurer  z in param dict is overridden.categorical_columnz4Reference dataset should be None or dataset instance)r  r  r  )r  r  r  )rJ   r  r  )r[   r  r  r   )matsr  r  )seqsr  z,Data list can only be of ndarray or SequencezCannot initialize Dataset from zLabel should not be NonezBThe init_score will be overridden by the prediction of init_model.r  r[   rz  zWrong predictor type )Ir  r  r  r   r   r  r  r   r  r  schemanamesr  inspect	signature	__class__
_lazy_init
parametersrN  r   r   r  	enumeraters   addr  r~   r   r/   r(  rD  rO  sortedr  r>   r"   	constructr   r@   r   rB   r   LGBM_DatasetCreateFromFilerE   rF   r  r  r  _Dataset__init_from_csrr  _Dataset__init_from_cscrR   r   _Dataset__init_from_np2d_Dataset__init_from_narwhalsr   r   _Dataset__init_from_list_np2dr   _Dataset__init_from_seqsr&   r  	set_label	get_labelr   
set_weight	set_groupset_positionr  r|  r  r  set_feature_name)rk   r[   rS  rw  rT  rV  rU  r  r  r  r>   rW  
args_namesr  categorical_indicesfeature_dictrC  r   	cat_aliasr  r  r  r  s                          r5   r  zDataset._lazy_init   sb    <DLK &/&B&BD#"+"?"?dL)O`)$7#'#:#:	PLD, 3T5L   &<6+A>>$/66<<>L
 /;f.D+ ~6&&t~~'@'@ALLQQS
;;= 	Cj e ""%&bd	 )40"%%L,-7@7NOGAtaOO+ ydC(T\-A'++L,>?c*'++D1#k$t*2E2E1FFXY]X^^v$wxxy #!/!3!34I!J 4I F* *6)+<d CFS\L]H^buHu(I;6S)TU

9d34 066I/J+,'/
i)#--/77K"RSSdS$K(!??,DL//3t9%:&LL.	 ell556  Tjk Zell556  Tjk Zbjj)!!dz{![""4(%%2>>$+?Jdo%pd#D	A'-**Yd*e&t,%%4[%I NOOh'!!v;!Gbll--d3$$Q\$] NN5!>>#788OOF#NN5!h'i1&:+Aab--	[_-`#
+"3DO4L4L3MNOO$$\22]  Pr ! b"A$t*BUBUAV WX^aabs   V93V? ?	W/"W**W/r  rG  c              #     K   d}d}| |   }|D ]v  }||k\  sJ d       ||t        |      z   k\  r*|t        |      z  }|dz  }| |   }||t        |      z   k\  r*||z
  }||   }|j                  d   r|n|j                          x y w)Nr   z+sample indices are expected to be monotonicr   OWNDATA)r   rU   r   )r  rG  r  seq_idseqrow_id	id_in_seqrows           r5   _yield_row_from_seqlistzDataset._yield_row_from_seqlist  s     6l 	>FV#R%RR#FSX--#c("!6l FSX-- Ii.C9-#388:=	>s   AB0Bc                   | j                  |      }t        j                  t        | j	                  ||                  }|j
                  }g }g }t        j                  t        |      t        j                        }|D ]`  }t        j                  |      t        kD  t        j                  |      z  }	||	   }
||	   }|j                  |
       |j                  |       b ||fS )zSample data from seqs.

        Mimics behavior in c_api.cpp:LGBM_DatasetCreateFromMats()

        Returns
        -------
            sampled_rows, sampled_row_indices
        )r=   r   )r  rR   r   r   r  Tr   r   ri  absr:   isnanr   )rk   r  r=   rG  sampledfilteredfiltered_idxsampled_row_ranger  col_predicatefiltered_colfiltered_row_idxs               r5   __samplezDataset.__sample  s     ---D ((4 < <T7 KLM))IIc'l"((C 	2CVVC[>9RXXc]JM}-L0?OOL) 01	2 %%r4   c                   t        d |D              }|| j                  ||       nOt        | j                               }t	        ||      }| j                  ||      \  }}| j                  ||||       |D ]a  }t        |      }	t        |dd      xs t        j                  }
t        d|	|
      D ]%  }t        ||
z   |	      }| j                  |||        ' c | S )z
        Initialize data from list of Sequence objects.

        Sequence: Generic Data Access Object
            Supports random access and access by batch if properly defined by user

        Data scheme uniformity are trusted, not checked
        c              3   2   K   | ]  }t        |        y wr9   r   )r   r  s     r5   r   z+Dataset.__init_from_seqs.<locals>.<genexpr>  s     2cS2r  N)r  r=   r  r   )r$  r  r  r  rI   _Dataset__sampler  r   ry   r&   r  r  minr  )rk   r  r  r=   r  rH   r  col_indicesr  r  r  startends                r5   __init_from_seqszDataset.__init_from_seqs  s     2T22
 "''
K@*4??+<=I*:yAJ'+}}$:}'V$K"";ZT 	0Cs8D lD9PX=P=PJq$
3 0%*,d3E#/0	0 r4   rJ   r  c                   t        |j                        dk7  rt        d      t        j                         | _        t        |      \  }}t        |      \  }}}t        t        j                  |t        j                  |      t        j                  |j                  d         t        j                  |j                  d         t        j                  |      t        |      |t        j                  | j
                                     | S )z(Initialize data from a 2-D numpy matrix.r   )Input numpy.ndarray must be 2 dimensionalr   r   )r   r   r   r@   r   r  r\   rg  rB   r   LGBM_DatasetCreateFromMatrA   rD   rE   rF   )	rk   rJ   r  r  r[   rZ   re  r  r  s	            r5   __init_from_np2dzDataset.__init_from_np2d  s     syy>QHII($S)f%3D%9"-**]+syy|,syy|,V$z"T\\*		
 r4   r  c                   |d   j                   d   }t        j                  t        |      ft        j                        }|d   j
                  t        j                  k(  r5 t        j                  t        j                        t        |      z         }n4 t        j                  t        j                        t        |      z         }t        j                  t        |      z         }g }d}	t        |      D ]  \  }
}t        |j                         dk7  rt        d      |j                   d   |k7  rt        d      |j                   d   ||
<   t        |      \  }}t        |      \  }}}|	dk7  r||	k7  rt        d      |||
<   |||
<   |}	|j!                  |        t        j"                         | _        t'        t)        j*                  t        j,                  t        |            t        j.                  |t        j                  t        j                  t        j                                    t        j                  |	      |j                  j1                  t        j                  t        j,                              t        j,                  |      |t3        |      |t        j4                  | j$                        	             | S )z2Initialize data from a list of 2-D numpy matrices.r   r   r  r   r  z-Input arrays must have same number of columnsz Input chunks must have same type)r   rR   r  r   ri  rO   rT   r@   r   r   r   rA   r  r   r\   rg  r   r   r  rB   r   LGBM_DatasetCreateFromMatsrD   r  ra  rE   rF   )rk   r  r  r  r  r  re  layoutsholdersr  rC  rJ   rZ   chunk_ptr_datachunk_type_ptr_dataholders                   r5   __init_from_list_np2dzDataset.__init_from_list_np2d
	  s    Aw}}QxxTbhh/7==BJJ&Cv7#d)CFHBv~~6TBEH<<#d)+.o 	#FAs399~" !LMMyy|t# !PQQiilDG',KC:H:M7N/"':m'K !CDD(HQKGAJ/MNN6"#	#& (++s4y)HfnnV^^FOO5T&UV]+##FNN6>>$BCt$z"T\\*
	
 r4   r  c                   t        |j                        t        |j                        k7  r7t        dt        |j                         dt        |j                               t	        j
                         | _        t        |j                        \  }}}t        |j                        \  }}}	|j                  d   t        k  sJ |j                  j                  t        j                  d      }
t        t!        j"                  |t	        j$                  |      |
j                  j'                  t	        j(                  t        j*                              |t	        j$                  |      t	        j,                  t        |j                              t	        j,                  t        |j                              t	        j,                  |j                  d         t/        |      |t	        j0                  | j                                     | S )z"Initialize data from a CSR matrix.Length mismatch:  vs r   Frz  )r   rG  r[   r   r@   r   r  rm  r6  rg  r   r  r   rR   ri  rB   r   LGBM_DatasetCreateFromCSRrA   ra  r   rD   r   rE   rF   )rk   r  r  r  rI  rJ  rR  re  r  r  rK  s              r5   __init_from_csrzDataset.__init_from_csrA	  f    s{{s388},0S[[1A0B$s388}oVWW(*6szz*B'
OR%3CHH%="-yy|z)))kk(((>**_-""**6>>&..+IJ]+s3::/s388}-syy|,z"T\\*	
 r4   r  c                   t        |j                        t        |j                        k7  r7t        dt        |j                         dt        |j                               t	        j
                         | _        t        |j                        \  }}}t        |j                        \  }}}	|j                  d   t        k  sJ |j                  j                  t        j                  d      }
t        t!        j"                  |t	        j$                  |      |
j                  j'                  t	        j(                  t        j*                              |t	        j$                  |      t	        j,                  t        |j                              t	        j,                  t        |j                              t	        j,                  |j                  d         t/        |      |t	        j0                  | j                                     | S )z"Initialize data from a CSC matrix.r  r  r   Frz  )r   rG  r[   r   r@   r   r  rm  r6  rg  r   r  r   rR   ri  rB   r   LGBM_DatasetCreateFromCSCrA   ra  r   rD   r   rE   rF   )rk   r  r  r  rI  rJ  rR  re  r  r  r^  s              r5   __init_from_csczDataset.__init_from_cscd	  r  r4   c          
          |j                         }t        j                         | _        t	        t        j                  t        |      t        |      |t        j                  | j                                     | S )z*Initialize data from a narwhals DataFrame.)
rf  r@   r   r  rB   r   !LGBM_DatasetCreateFromArrowStreamr   rE   rF   )rk   r[   r  r  r   s        r5   __init_from_narwhalszDataset.__init_from_narwhals	  sb     ++-	 (225i@z"T\\*		
 r4   other_paramsignore_keysc                     |j                         D ]  \  }}||vs|| vs	| |   |k7  s y | j                         D ]  \  }}||vs||vs	|||   k7  s y y)a  Compare two dictionaries with params ignoring some keys.

        It is only for the warning purpose.

        Parameters
        ----------
        params : dict
            One dictionary with parameters to compare.
        other_params : dict
            Another dictionary with parameters to compare.
        ignore_keys : set
            Keys that should be ignored during comparing two dictionaries.

        Returns
        -------
        compare_result : bool
          Returns whether two dictionaries with params are equal.
        FTr,  )r>   r  r  r-  r.  s        r5   _compare_params_for_warningz#Dataset._compare_params_for_warning	  sz    2 !&&( 	!DAq#F?fQi1n 	! LLN 	!DAq#L(Aa,@ 	! r4   c                 @	   | j                   | j                  | j                  j                         }| j                         }||k7  rC| j                  ||t        j                  d            st        d       | j                  |       | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                   | j"                  d| j$                         n[t'        | j                  t(        j*                  d      }|j,                  j.                  sJ | j                  j                  t)        j0                  | j                  j                        j3                  t(        j*                  d	
      }t)        j4                  t)        j6                  t9        t;        |            |      | j                     d      \  }| _        t=        j>                         | _         tA        | j$                        }tC        tE        jF                  | j                  jI                         j                   |j<                  jK                  t=        jL                  t<        jN                              t=        jN                  |jP                  d         tS        |      t=        jT                  | j                                      | jV                  s| jY                          | j                  | j[                  | j                         | j                  | j]                  | j                         | j_                         ta        d      tc        | j                   td              r| j                   | j                  j                   ur| jY                          | jg                  | j                   | j                  |       n| j                  | j                  | j                  d| j                  | j                  | j                  | j                   | j"                  | jh                  | j$                  | j                         | jV                  rd| _
        | jk                         | _        | S )zsLazy init.

        Returns
        -------
        self : Dataset
            Constructed Dataset object.
        Nr  )r>   r  r  z1Overriding the parameters from Reference Dataset.r  )r[   rS  rw  rT  rV  rW  rU  r  r  r  r>   rz  r   Frz  )repeatsT)return_countsr   zLabel should not be None.r  )r[   rS  rw  rT  rV  rU  r  r  r  r>   rW  )6r  rw  r  r  r(  rD  r   _update_paramsrz  r  r[   rS  rT  rV  rW  rU  r|  r  r>   r   rR   ri  rU   r\  r   r   uniquerepeatr  r   r@   r   r  rB   r   LGBM_DatasetGetSubsetr  ra  r   rD   r   rE   rF   rx  get_datar  r  r  r   r   r  r  r  get_feature_name)rk   reference_paramsr>   rz  
group_infor  r  s          r5   r  zDataset.construct	  sl    <<~~)#'>>#<#<#> *--;;%%5$2$6$67L$M < 
 %%XY''(89$$,OO!YY"jj"&..#{{"jj!%#'??"&//%)%6%6,2#{{ $  $5!.. hh+$L
 (--::::~~++7%'XXdnn.B.B%C%J%J288Z_%J%`
(*		IIeC
O&<jQRVRcRcdtx)4: $*??#4DL!3DKK!@J22 NN446>>(//77v~~8VW"NN<+=+=a+@A":."LL6  --zz-tzz2}}0))$--8~~'/()DEE"4??OD OO4>>3L3LL99&*ooDIIT` : 
 **";;**#"oo!%!2!2(,(@(@;;!]]    !! 	 $ 5 5 7Dr4   c                     t        ||| |||||| j                  	      }| j                  |_        | j                  |_        |S )aJ  Create validation data align with current Dataset.

        Parameters
        ----------
        data : str, pathlib.Path, numpy array, pandas DataFrame, scipy.sparse, Sequence, list of Sequence, list of numpy array, pyarrow Table or polars DataFrame
            Data source of Dataset.
            If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM) or a LightGBM Dataset binary file.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        label : list, numpy 1-D array, pandas Series / one-column DataFrame, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Label of the data.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        weight : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Weight for each instance. Weights should be non-negative.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        group : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Group/query data.
            Only used in the learning-to-rank task.
            sum(group) = n_samples.
            For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
            where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), pyarrow ChunkedArray, pyarrow Table (for multi-class task), polars Series, polars DataFrame (for multi-class task) or None, optional (default=None)
            Init score for Dataset.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        params : dict or None, optional (default=None)
            Other parameters for validation Dataset.
        position : numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Position of items used in unbiased learning-to-rank task.

        Returns
        -------
        valid : Dataset
            Validation Dataset with reference to self.
        )rS  rw  rT  rV  rW  rU  r>   rx  )r"   rx  r|  r  )	rk   r[   rS  rT  rV  rU  r>   rW  r   s	            r5   create_validzDataset.create_valid 
  sP    T !,,

 !%!8!8
r4   c                     || j                   }t        d| | j                  | j                  || j                        }| j
                  |_        | j                  |_        t        |      |_        |S )a  Get subset of current Dataset.

        Parameters
        ----------
        used_indices : list of int
            Indices used to create the subset.
        params : dict or None, optional (default=None)
            These parameters will be passed to Dataset constructor.

        Returns
        -------
        subset : Dataset
            Subset of the current Dataset.
        N)rw  r  r  r>   rx  )	r>   r"   r  r  rx  r|  r  r  rz  )rk   rz  r>   r   s       r5   subsetzDataset.subsety
  sm    & >[[F** $ 8 8,,
 !%!8!8!,/
r4   filenamec           
          t        t        j                  | j                         j                  t        t        |                         | S )a  Save Dataset to a binary file.

        .. note::

            Please note that `init_score` is not saved in binary file.
            If you need it, please set it again after loading Dataset.

        Parameters
        ----------
        filename : str or pathlib.Path
            Name of the output file.

        Returns
        -------
        self : Dataset
            Returns self.
        )rB   r   LGBM_DatasetSaveBinaryr  r  rE   rs   rk   r-  s     r5   save_binaryzDataset.save_binary
  s=    $ 	'' ((s8}%	
 r4   c                     s S t              d fd} j                  	 |         S t        j                  t	        t         j                              t	        t                          }|dk7  rQ j                   |         j                           S t        t        j                         j                  d             S )Nc                      j                   s _         y t        j                         _        j                   j                          y r9   )r>   r   r}  r@  )r>   rk   s   r5   r@  z&Dataset._update_params.<locals>.update
  s4    ;;$'/'<$""6*r4   r   r   ro  )r   r  r   LGBM_DatasetUpdateParamCheckingrE   r  r>   r[   r  r$   r   r   )rk   r>   r@  r   s   ``  r5   r!  zDataset._update_params
  s    K&!	+ <<H  66)$++67)&12C ax99(H%%'  ((>(>(@(G(G(PQQr4   c                 `    | j                   !t        | j                        | _        d | _        | S r9   )r  r   r}  r>   r  s    r5   _reverse_update_paramszDataset._reverse_update_params
  s+    <<"4#7#78DK#'D r4   
field_namec                    | j                   t        d| d      |dt        t        j                  | j                   t        |      dt        j                  d      t        j                  t        |                      | S t        j                  |      st        j                  |      rt        |t        t        f      sxt        j                   |d      j#                         }t        t        j$                  | j                   t        |      t'        |                   | xj(                  dz  c_        | S |dk(  rat*        j,                  }t/        |      rt1        |||	      }njt3        |      r!t5        |||	      }|j7                  d
      }n>t9        d      |dv rt*        j:                  }nt*        j<                  }t1        |||	      }|j>                  t*        j<                  k(  s|j>                  t*        j,                  k(  rtA        |      \  }}}nF|j>                  t*        j:                  k(  rtC        |      \  }}}nt9        d|j>                   d      |t        |   k7  rt9        d      t        t        j                  | j                   t        |      |t        j                  tE        |            t        j                  |                   | xj(                  dz  c_        | S )a  Set property into the Dataset.

        Parameters
        ----------
        field_name : str
            The field name of the information.
        data : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), pyarrow ChunkedArray, pyarrow Table (for multi-class task), polars Series, polars DataFrame (for multi-class task) or None
            The data to be set.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        Returns
        -------
        self : Dataset
            Dataset with set property.
        NzCannot set z before construct datasetr   T)allow_seriesr   rU  r   rM   rQ   zinit_score must be list, numpy 1-D array or pandas Series.
In multiclass classification init_score can also be a list of lists, numpy 2-D array or pandas DataFrame.>   rV  rW  z-Expected np.float32/64 or np.int32, met type(r_  zInput type error for set_field)#r  	ExceptionrB   r   LGBM_DatasetSetFieldrE   r@   rA   _FIELD_TYPE_MAPPERr  r   is_into_seriesr   r   r   r  r  rf  #LGBM_DatasetSetFieldFromArrowStreamr   r~  rR   rT   r   r   r   r   rY   r~   ri  rS   rO   rg  rm  r   )rk   r7  r[   r   rO   re  rf  r  s           r5   	set_fieldzDataset.set_field
  sm   2 <<k*5NOPP<))LL:&LLOLL!3J!?@ K !!$'3+=+=d+CZ<+N
 t$?RRTI88LL:&9)D LLALK %JJE &(d%jQ"4((d%jQzzz,@ 
 22

$$e*MD ::#tzzRZZ'?%3D%9"HiZZ288#%1$%7"HiKDJJ<WXYZZ*:66<==%%z"SY'Y'	
 	r4   c                    | j                   t        d| d      t        j                  d      }t        j                  d      } t        j                  t        j
                               }t        t        j                  | j                   t        |      t        j                  |      t        j                  |      t        j                  |                   |j                  t        |   k7  rt        d      |j                  dk(  ry|j                  t        k(  rMt        t        j                   |t        j                  t        j"                              |j                        }n|j                  t$        k(  rMt'        t        j                   |t        j                  t        j(                              |j                        }nk|j                  t*        k(  rMt-        t        j                   |t        j                  t        j.                              |j                        }nt        d      |dk(  r9| j1                         }|j2                  |z  }|d	kD  r|j5                  ||fd
      }|S )ad  Get property from the Dataset.

        Can only be run on a constructed Dataset.

        Unlike ``get_group()``, ``get_init_score()``, ``get_label()``, ``get_position()``, and ``get_weight()``,
        this method ignores any raw data passed into ``lgb.Dataset()`` on the Python side, and will only read
        data from the constructed C++ ``Dataset`` object.

        Parameters
        ----------
        field_name : str
            The field name of the information.

        Returns
        -------
        info : numpy array or None
            A numpy array with information from the Dataset.
        NzCannot get z before construct Datasetr   zReturn type error for get_fieldr   zUnknown typerU  r   rM   rQ   )r  r:  r@   rA   r   r   rB   r   LGBM_DatasetGetFieldrE   rF   rG   r<  r~   rj  r   r  rD   rb  r   r   rc  r   r   r  r  r  )rk   r7  r8  out_typer   arrr  num_classess           r5   	get_fieldzDataset.get_field7  s   & <<k*5NOPPll1o<<?-fnnV__-/%%z"[)S!X&	
 >>/
;;=>>!>>//([[fnnV^^&DE"((C ^^33*[[fnnV^^&DE"((C ^^33*[[fnnV__&EF"((C
 N++%}}H((h.KQkk8["9kE
r4   c                     | j                   |k(  r| S | j                  g| j                   || _         | j                         S |dk(  r| S | j                   dk7  rt        dt	        |              || _         | j                         S t        d      )a&  Set categorical features.

        Parameters
        ----------
        categorical_feature : list of str or int, or 'auto'
            Names or indices of categorical features.

        Returns
        -------
        self : Dataset
            Dataset with set categorical features.
        r  zIcategorical_feature in Dataset is overridden.
New categorical_feature is zrCannot set categorical feature after freed raw data, set free_raw_data=False when construct Dataset to avoid this.)r  r[   r  r   r   r$   )rk   r  s     r5   set_categorical_featurezDataset.set_categorical_featuret  s      ##'::K99 ''/+>(((**$.++v5 66:;N6O5PR ,?(((**P r4   c                    || j                   | S t        |t              rVt        | j                   t              r<|| j                   k(  r-|j                         | j                   j                         k(  r| S | j                  	|| _         | S | j
                  1|| _         | j                  | j                   | j
                  d       | S | j                  g| j                  [| j                  j
                  E|| _         | j                  | j                   | j                  j
                  | j                         | S t        d      )zSet predictor for continued training.

        It is not recommended for user to call this function.
        Please use init_model argument in engine.train() or engine.cv() instead.
        Nr  zhCannot set predictor after freed raw data, set free_raw_data=False when construct Dataset to avoid this.)
r|  r   r  rm  r  r[   r  rz  rw  r$   )rk   r  s     r5   _set_predictorzDataset._set_predictor  s.    !8K	?3
4??Tc8dT__,++-1R1R1TT<<'DO( ' YY"'DO--//YY! . "  *t~~/IdnnNaNaNm'DO--//^^((!.. .  	  P r4   c                 V   | j                  |j                        j                  |j                        j	                  |j
                         | j                         j                  |j                               r| S | j                  || _	        | j                         S t        d      )a  Set reference Dataset.

        Parameters
        ----------
        reference : Dataset
            Reference that is used as a template to construct the current Dataset.

        Returns
        -------
        self : Dataset
            Dataset with set reference.
        zhCannot set reference after freed raw data, set free_raw_data=False when construct Dataset to avoid this.)rG  r  r  r  rI  r|  get_ref_chainintersectionr[   rw  r  r$   )rk   rw  s     r5   set_referencezDataset.set_reference  s     	$$Y%B%BCTT""	

.--
.,,Y-D-D-FGK99 &DN$$&&P r4   c                    |dk7  r|| _         d| _        | j                  ||dk7  rt        |      | j	                         k7  r)t        dt        |       d| j	                          d      |D cg c]  }t        |       }}t        t        j                  | j                  t        t        j                  |      t        j                  t        |                         | S c c}w )zSet feature name.

        Parameters
        ----------
        feature_name : list of str
            Feature names.

        Returns
        -------
        self : Dataset
            Dataset with set feature name.
        r  TzLength of feature_name(z) and num_feature() don't match)r  r  r  r   num_featurer   rE   rB   r   LGBM_DatasetSetFeatureNamesr   r@   r   rA   )rk   r  r   c_feature_names       r5   r  zDataset.set_feature_name  s     6! ,D26D/<<#(@\U[E[< D$4$4$66 -c,.?-@@RSWScScSeRffst  8DDtfTlDND00LLV__n=LL\!23  Es   0C$c                    || _         | j                  t        |t              rRt	        |j
                        dkD  rt        d      t        j                  t        |t        j                              }nYt        j                  |      st        j                  |      rt        |t              s|}nt        |t        j                  d      }| j!                  d|       | j#                  d      | _         | S )a  Set label of Dataset.

        Parameters
        ----------
        label : list, numpy 1-D array, pandas Series / one-column DataFrame, pyarrow ChunkedArray, polars Series or None
            The label information to be set into Dataset.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        Returns
        -------
        self : Dataset
            Dataset with set label.
        r   z0DataFrame for label cannot have multiple columnsr  rS  r   )rS  r  r   r   r   r  r   rR   rY   r~  rS   r  r   r=  r   r   r?  rE  )rk   rS  label_arrays      r5   r  zDataset.set_label  s    & 
<<#%.u}}%)$%WXX hh'7BJJ'WX''.#2D2DU2KU_`egpUq#/U"**SZ[NN7K00DJr4   c                    |Zt        j                  |      r+t        j                  |d      dk(  j	                         rd}nt        j                  |dk(        rd}|| _        | j                  k|it        |t              st        j                  |      st        |t
        j                  d      }| j                  d|       | j                  d      | _        | S )a  Set weight of each instance.

        Parameters
        ----------
        weight : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None
            Weight to be set for each data point. Weights should be non-negative.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        Returns
        -------
        self : Dataset
            Dataset with set weight.
        NT)series_onlyr   rT  r   )r  r=  r  r  r   rR   rT  r  r   r   r   rS   r?  rE  )rk   rT  s     r5   r  zDataset.set_weight  s    . !!&)NN6t<AFFH!F!$ <<#(:&),C4F4Fv4N*bjjxXNN8V,..2DKr4   c                     || _         | j                  *|(| j                  d|       | j                  d      | _         | S )a  Set init score of Booster to start from.

        Parameters
        ----------
        init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), pyarrow ChunkedArray, pyarrow Table (for multi-class task), polars Series, polars DataFrame (for multi-class task) or None
            Init score for Booster.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        Returns
        -------
        self : Dataset
            Dataset with set init score.
        rU  )rU  r  r?  rE  )rk   rU  s     r5   r  zDataset.set_init_scoreD  s=    , %<<#
(>NN<4"nn\:DOr4   c                 0   || _         | j                  |t        |t              st	        j
                  |      st        |t        j                  d      }| j                  d|       | j                  d      }|t        j                  |      | _         | S )aS  Set group size of Dataset (used for ranking).

        Parameters
        ----------
        group : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None
            Group/query data.
            Only used in the learning-to-rank task.
            sum(group) = n_samples.
            For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
            where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        Returns
        -------
        self : Dataset
            Dataset with set group.
        rV  r   )rV  r  r   r   r  r=  r   rR   ri  r?  rE  r!  )rk   rV  constructed_groups      r5   r  zDataset.set_group`  s|    4 
<<#(9%+33E3Ee3L)uBHH7SNN7E* $w 7 ,WW%67
r4   c                    || _         | j                  k|it        |t              st	        j
                  |      st        |t        j                  d      }| j                  d|       | j                  d      | _         | S )ax  Set position of Dataset (used for ranking).

        Parameters
        ----------
        position : numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Position of items used in unbiased learning-to-rank task.

        Returns
        -------
        self : Dataset
            Dataset with set position.
        rW  r   )rW  r  r   r   r  r=  r   rR   ri  r?  rE  )rk   rW  s     r5   r  zDataset.set_position  sg      !<<#(<(I.c6H6H6R,("((Q[\NN:x0 NN:6DMr4   c                    | j                   t        d      | j                         }t        j                  d      }d}t        j
                  d      }t        |      D cg c]  }t        j                  |       }}t        j                  |z  t        t        j                  |       }t        t        j                  | j                   t        j                  |      t        j                  |      t        j
                  |      t        j                  |      |             ||j                  k7  rt!        d      |j                  }||k  rt        |      D cg c]  }t        j                  |       }}t        j                  |z  t        t        j                  |       }t        t        j                  | j                   t        j                  |      t        j                  |      t        j
                  |      t        j                  |      |             t        |      D 	cg c]   }	||	   j                  j#                  d      " c}	S c c}w c c}w c c}	w )zGet the names of columns (features) in the Dataset.

        Returns
        -------
        feature_names : list of str
            The names of columns (features) in the Dataset.
        z0Cannot get feature_name before construct datasetr      6Length of feature names doesn't equal with num_featurer   )r  r$   rP  r@   rA   c_size_tr  r2  r   r  r3  rB   r   LGBM_DatasetGetFeatureNamesrF   rG   r   r   
rk   rP  r8  reserved_string_buffer_sizerequired_string_buffer_sizer  string_buffersptr_string_buffersactual_string_buffer_sizerC  s
             r5   r&  zDataset.get_feature_name  s    << RSS&&(ll1o&)#&,ooa&8#\abm\noWX&556QRoo$oo;c&BRBRTb>cd,,[)[) ;<89"		
 ++++UVV$?$E$E!&)BB^cdo^pqYZf99:STqNq"(//K"?#fFVFVXfBg!h00LLLL-LL-OO$=>LL!<=&	 BG{ASTAq!''..w7TT; p" r Us   !II.%I c                 ^    | j                   | j                  d      | _         | j                   S )a  Get the label of the Dataset.

        Returns
        -------
        label : list, numpy 1-D array, pandas Series / one-column DataFrame, pyarrow ChunkedArray, polars Series or None
            The label information from the Dataset.
            For a constructed ``Dataset``, this will only return a numpy array.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs
        rS  )rS  rE  r  s    r5   r  zDataset.get_label  s(     ::0DJzzr4   c                 ^    | j                   | j                  d      | _         | j                   S )a  Get the weight of the Dataset.

        Returns
        -------
        weight : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None
            Weight for each data point from the Dataset. Weights should be non-negative.
            For a constructed ``Dataset``, this will only return ``None`` or a numpy array.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs
        rT  )rT  rE  r  s    r5   
get_weightzDataset.get_weight  s(     ;;..2DK{{r4   c                 ^    | j                   | j                  d      | _         | j                   S )av  Get the initial score of the Dataset.

        Returns
        -------
        init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), pyarrow ChunkedArray, pyarrow Table (for multi-class task), polars Series, polars DataFrame (for multi-class task) or None
            Init score of Booster.
            For a constructed ``Dataset``, this will only return ``None`` or a numpy array.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs
        rU  )rU  rE  r  s    r5   get_init_scorezDataset.get_init_score  s(     ??""nn\:DOr4   c                 (   | j                   t        d      | j                  rL| j                  ?| j                  2| j                  j
                  | _        | j
                  t        | j
                  t        j                  t        j                  j                  f      r$| j
                  | j                  ddf   | _        nt        | j
                  t              r8| j
                  j                  | j                     j                         | _        nOt        | j
                  t              r | j
                  | j                     | _        nt!        j"                  | j
                        rUt        j$                  | j                        }t'        j(                  | j
                        |   j+                         | _        nt-        | j
                        r`t/        | j
                        dkD  rHt        j$                  t1        | j3                  | j
                  | j                                    | _        n,t5        dt7        | j
                        j8                   d       d| _        | j
                  t;        d      | j
                  S )a  Get the raw data of the Dataset.

        Returns
        -------
        data : str, pathlib.Path, numpy array, pandas DataFrame, scipy.sparse, Sequence, list of Sequence, list of numpy array, pyarrow Table, polars DataFrame, or None
            Raw data used in the Dataset construction.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs
        Nz(Cannot get data before construct Datasetr   zCannot subset z. type of raw data.
Returning original raw dataFzjCannot call `get_data` after freed raw data, set free_raw_data=False when construct Dataset to avoid this.)r  r:  r{  rz  rw  r[   r   rR   r   r  r  r  r   ilocr   r&   r  r   r   r  r  	to_nativer   r   r   r  r   r   r/   r$   )rk   rG  s     r5   r%  zDataset.get_data  s    <<FGG 1 1 =$..B\++DIyy$dii"**ell6K6K)LM $		$*;*;Q*> ?DI		<8 $		t/@/@ A F F HDI		84 $		$*;*; <DI**4995 hht'8'89G "tyy 9' B L L NDI*4995#dii.1:L "d.J.J499VZVgVg.h)i jDI (dii)A)A(BBqr  %D99P  yyr4   c                     | j                   F| j                  d      | _         | j                   $t        j                  | j                         | _         | j                   S )a=  Get the group of the Dataset.

        Returns
        -------
        group : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None
            Group/query data.
            Only used in the learning-to-rank task.
            sum(group) = n_samples.
            For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
            where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
            For a constructed ``Dataset``, this will only return ``None`` or a numpy array.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs
        rV  )rV  rE  rR   r!  r  s    r5   	get_groupzDataset.get_group-  sF    & ::0DJzz%WWTZZ0
zzr4   c                 ^    | j                   | j                  d      | _         | j                   S )aK  Get the position of the Dataset.

        Returns
        -------
        position : numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None
            Position of items used in unbiased learning-to-rank task.
            For a constructed ``Dataset``, this will only return ``None`` or a numpy array.
        rW  )rW  rE  r  s    r5   get_positionzDataset.get_positionG  s(     ==  NN:6DM}}r4   c                     | j                   ]t        j                  d      }t        t	        j
                  | j                   t        j                  |                   |j                  S t        d      )zGet the number of rows in the Dataset.

        Returns
        -------
        number_of_rows : int
            The number of rows in the Dataset.
        r   z,Cannot get num_data before construct dataset)	r  r@   rA   rB   r   LGBM_DatasetGetNumDatarF   rG   r$   rk   r   s     r5   r  zDataset.num_dataT  s\     <<#,,q/C++LLLL% 99 NOOr4   c                     | j                   ]t        j                  d      }t        t	        j
                  | j                   t        j                  |                   |j                  S t        d      )zGet the number of columns (features) in the Dataset.

        Returns
        -------
        number_of_columns : int
            The number of columns (features) in the Dataset.
        r   z/Cannot get num_feature before construct dataset)	r  r@   rA   rB   r   LGBM_DatasetGetNumFeaturerF   rG   r$   rt  s     r5   rP  zDataset.num_featureh  s\     <<#,,q/C..LLLL% 99 QRRr4   featurec           	      n   | j                   t        |t              r| j                  j	                  |      }n|}t        j                  d      }t        t        j                  | j                   t        j                  |      t        j                  |                   |j                  S t        d      )aF  Get the number of bins for a feature.

        .. versionadded:: 4.0.0

        Parameters
        ----------
        feature : int or str
            Index or name of the feature.

        Returns
        -------
        number_of_bins : int
            The number of constructed bins for the feature in the Dataset.
        r   z3Cannot get feature_num_bin before construct dataset)r  r   rs   r  indexr@   rA   rB   r   LGBM_DatasetGetFeatureNumBinrF   rG   r$   )rk   rw  feature_indexr   s       r5   feature_num_binzDataset.feature_num_bin|  s     <<#'3' $ 1 1 7 7 @ ',,q/C11LLLL/LL% 99 UVVr4   	ref_limitc                     | }t               }t        |      |k  r]t        |t              r;|j	                  |       |j
                  |j
                  |vr|j
                  }n	 |S 	 |S t        |      |k  r]|S )a  Get a chain of Dataset objects.

        Starts with r, then goes to r.reference (if exists),
        then to r.reference.reference, etc.
        until we hit ``ref_limit`` or a reference loop.

        Parameters
        ----------
        ref_limit : int, optional (default=100)
            The limit number of references.

        Returns
        -------
        ref_chain : set of Dataset
            Chain of references of the Datasets.
        )r  r   r   r"   r  rw  )rk   r}  head	ref_chains       r5   rK  zDataset.get_ref_chain  s|    " "%%	)ny($(d#NN.T^^95T>>D   )ny( r4   c                 	   | j                   |j                   t        d      t        t        j                  | j                   |j                                | j
                  du }t        | j
                        j                  }|j
                  	d| _        n| j
                  t        | j
                  t        j                        r#t        |j
                  t        j                        r2t        j                  | j
                  |j
                  f      | _        nBt        |j
                  t        j                  j                        r@t        j                  | j
                  |j
                  j                         f      | _        nt        |j
                  t               r<t        j                  | j
                  |j
                  j"                  f      | _        n~d| _        nut        | j
                  t        j                  j                        r| j
                  j%                         }t        |j
                  t        j                  t        j                  j                  f      r>t        j                  j                  | j
                  |j
                  f|      | _        nt        |j
                  t               rHt        j                  j                  | j
                  |j
                  j"                  f|      | _        nNd| _        nEt        | j
                  t               r#t&        st)        d      t        |j
                  t        j                        r3t+        | j
                  t!        |j
                        fdd      | _        nt        |j
                  t        j                  j                        rAt+        | j
                  t!        |j
                  j                               fdd      | _        nSt        |j
                  t               r*t+        | j
                  |j
                  fdd      | _        nd| _        nd| _        | j
                  :dt        |j
                        j                   d	| d
}||rdndz  }t-        |       | j/                         | _        t-        d       d| _        d| _        | S )a^  Add features from other Dataset to the current Dataset.

        Both Datasets must be constructed before calling this method.

        Parameters
        ----------
        other : Dataset
            The Dataset to take features from.

        Returns
        -------
        self : Dataset
            Dataset with the new features added.
        NzJBoth source and target Datasets must be constructed before adding features)formatztCannot add features to DataFrame type of raw data without pandas installed. Install pandas and restart your session.r   T)axisignore_indexzCannot add features from z type of raw data to z type of raw data.
z<Set free_raw_data=False when construct Dataset to avoid thiszFreeing raw datazkResetting categorical features.
You can set new categorical features via ``set_categorical_feature`` methodr  )r  r   rB   r   LGBM_DatasetAddFeaturesFromr[   r   r/   r   rR   r   hstackr  r  r  toarrayr   r   	getformatr   r$   r   r   r&  r  r  r  )rk   otherwas_noneold_self_data_typesparse_formaterr_msgs         r5   add_features_fromzDataset.add_features_from  s\    <<5==#8ijj,,	
 99$!$))_55::DIYY"$))RZZ0ejj"**5 "		499ejj*A BDI

ELL,A,AB "		499ejj6H6H6J*K LDI

L9 "		499ejj6G6G*H IDI $DIDIIu||'<'<= $		 3 3 5ejj2::u||7L7L*MN % 3 3TYY

4KTa 3 bDI

L9 % 3 3TYY

@Q@Q4R[h 3 iDI $DIDII|4''C 
 ejj"**5 &		<

3K'LSTcg hDI

ELL,A,AB &		<

@R@R@T3U'V]^mq rDI

L9 &		5::'>QUY ZDI $DI 	99+D,<,E,E+FF[%&&:<  RZN`rG ! 113Z	
 $* "&r4   c           
          t        t        j                  | j                         j                  t        t        |                         | S )aK  Save Dataset to a text file.

        This format cannot be loaded back in by LightGBM, but is useful for debugging purposes.

        Parameters
        ----------
        filename : str or pathlib.Path
            Name of the output file.

        Returns
        -------
        self : Dataset
            Returns self.
        )rB   r   LGBM_DatasetDumpTextr  r  rE   rs   r0  s     r5   
_dump_textzDataset._dump_text
  s=     	%% ((s8}%	
 r4   )
NNNNNr  r  NTNro  )r7   r"   )NNNNNNr9   )rw  r"   r7   r"   )d   )r  r"   r7   r"   )Wr/   r0   r1   r2   _LGBM_TrainDataTyper   _LGBM_LabelType_LGBM_WeightType_LGBM_GroupType_LGBM_InitScoreType_LGBM_FeatureNameConfiguration%_LGBM_CategoricalFeatureConfigurationr   rs   r   rq  _LGBM_PositionTyper  r  r  rR   r   r  _DatasetHandler  r   r  r  r  r  r  r   r  r  rI  r&   r   r   r  r   r  r  r  r  r  r  r  r  r  r  r  ru  r  r   r  r  r*  r,  r   r1  r!  r6  _LGBM_SetFieldTyper?  rE  rG  rI  rM  r  r  r  r  r  r  r&  r  rh  rj  r%  ro  rq  r  rP  r|  rK  r  r  r3   r4   r5   r"   r"     s    ,0)--1+/487=EK+/"15s:!s: (s: I&	s:
 )*s: (s: 01s: 5s: Cs: c3h(s: s: -.s:j C  BJJ  D $ 
	:>"**%> RZZ(> 	>
 > 
>@rzz i <#DcN #J)O,) ") uT#Y

%:;<	)
 
)V3*+3 (3 I&	3
 )*3 (3 013 O,3 53 C3 c3h(3 -.3 
3B >d8n >x} >QYZ\ZdZdQe > >&X &C &E$rzzJZ\`acakak\lJlDm &8  8n  n-	 
 
 D ZZ 	
 n- 
85 2::5 	5
 n-5 
5n! \\$$! 	!
 n-! 
!F! \\$$! 	!
 n-! 
!F ll 	
 n- 
.  S#X  38n  X	 
 
   D]D ,0-1+/48+/15W!W (W )*	W
 (W 01W c3h(W -.W 
Wx ,0 3i  c3h(  
	 DE#t)$4  4Xd38n%= ) 8^^ )*^ 
	^@;C ;HRZZ,@ ;z$B$ 
$L%O,% 
%N8-K PY >x8 Y B%)*% 
%N01 
8#(# 
#J-. 
0+U$s) +UZ8O4 &H%56 &)< = &((#67 (T8O4 4h'9: P# P(SS S(WuS#X W3 W@s S^ <N`5d#3 	 r4   r"   c                   r    e Zd ZU dZeed<   eed<   eed<   eed<   dZe	e   ed<   de
fd	Zdefd
ZdefdZy)
EvalResulta  
    Result from computing an evaluation metric on a dataset.

    In ``lightgbm<4.7.0``, evaluation results were stored in tuples like this:

      * train(): ``(dataset_name, metric_name, metric_value, maximize)``
      * cv(): ``(dataset_name, metric_name, mean(metric_value), maximize, std_dev(metric_value))``

    Parameters
    ----------
    dataset_name : str
        Unique identifier for the dataset this result was computed on.
    metric_name : str
        Unique identifier for the metric (e.g. "rmse").
    metric_value : float
        Value of the evaluation metric.
    maximize : bool
        Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.
    metric_std_dev : float or None
        If not ``None``, the standard deviation of metric values computed over a range of results.
        For example, used when aggregating over cross-validation folds in ``cv()``.
    dataset_namemetric_namemetric_valuemaximizeNmetric_std_devr7   c                 &    | j                         syy)N      )is_cv_resultr  s    r5   r  zEvalResult.__len__P  s      "r4   c              #      K   d}|t        |       k  r0t        | | j                  |          |dz  }|t        |       k  r/y y w)Nr   r   )r   ry   _fields)rk   rC  s     r5   __iter__zEvalResult.__iter__V  sA     #d)m$Q00FA #d)ms   ?AAc                     | j                   duS )z
        Whether the result was created by ``cv()``.

        If ``True``:

          * ``metric_value`` = mean of ``metric_name`` over CV folds
          * ``metric_std_dev`` = standard deviation of ``metric_name`` over CV folds
        N)r  r  s    r5   r  zEvalResult.is_cv_result\  s     ""$..r4   )r/   r0   r1   r2   rs   __annotations__r   rq  r  r   r  r  r   r  r  r3   r4   r5   r  r  2  sR    . N&*NHUO* # 	/d 	/r4   r  c                      e Zd ZdZ	 	 	 	 d]deeeef      dee   dee	ee
f      dee   fdZd^d	Zd_d
Zdededd fdZdeeef   fdZdeeef   ddfdZdeeef   fdZd_dZd_dZ	 	 	 d`de	ee   ee   ef   dedededd f
dZd_dZdefdZdedd fdZdededd fdZdeeef   dd fdZ	 	 dadee   d ee   defd!Z d"e!jD                  d#e!jD                  defd$Z#d_d%Z$defd&Z%defd'Z&defd(Z'de(fd)Z)de(fd*Z*	 dbdeded+ee	e+ee+   f      dee,   fd,Z-	 dbd+ee	e+ee+   f      dee,   fd-Z.	 dbd+ee	e+ee+   f      dee,   fd.Z/	 	 	 dcd/e	ee
f   d0ee   d1ed2edd f
d3Z0	 	 ddd1ed4edd fd5Z1dedd fd6Z2	 	 	 dcd0ee   d1ed2edefd7Z3	 	 	 	 ded0ee   d1ed2ed8ee4eeef   geeef   f      deeef   f
d9Z5	 	 	 	 	 	 	 dfde6d1ed0ee   d:ed;ed<ed=ed>edede7fd?Z8	 	 	 	 	 	 	 	 	 	 dgde9d@e:dAe(dBee   dCee;   dDee<   dEee=   dFe>dGe?dHeeeef      dIed>ededd fdJZ@dKedLede(fdMZAdKedLedNe(dd fdOZBdefdPZCdee   fdQZD	 	 dhd2edRee   de!jD                  fdSZE	 	 didTe	eef   dUee	eef      dVede	eFe!jD                  e!jD                  f   e!jD                  ef   fdWZGdXedYed+ee	e+ee+   f      dee,   fdZZHdYede!jD                  fd[ZId^d\ZJy)jr!   zBooster in LightGBM.Nr>   	train_setr  r  c           	         t        j                         | _        d| _        d| _        d| _        d| _        d| _        i | _        |i n
t        |      }|t        |t              s!t        dt        |      j                         t        d|d      }|d   |j!                  dd       n|d   }t        |t"              rt%        |j'                  d	            }n>t        |t(        t*        f      rt%        |      }d	j-                  |      }nt/        d
      t        d||      }t        d|d      }| j1                  ||d   |j3                  dd      |d          |j5                          |j7                  |j9                                t;        |      }t=        t?        j@                  |j                  tC        |      t        jD                  | j                                     || _#        g | _$        g | _%        d| _&        |jN                  | _(        | jP                  =t=        t?        jR                  | j                  | jP                  j                               t        jT                  d      }t=        t?        jV                  | j                  t        jD                  |                   |jX                  | _-        dg| _.        dg| _/        | ja                          |jb                  | _1        |jd                  | _3        || _9        y|t        jT                  d      }	t=        t?        jh                  tC        t#        |            t        jD                  |	      t        jD                  | j                                     t        jT                  d      }t=        t?        jV                  | j                  t        jD                  |                   |jX                  | _-        tk        |      | _1        |rtm        d       | jo                         }|| _9        y|6| jq                  |       |rtm        d       | jo                         }|| _9        yt        d      )a  Initialize the Booster.

        Parameters
        ----------
        params : dict or None, optional (default=None)
            Parameters for Booster.
        train_set : Dataset or None, optional (default=None)
            Training dataset.
        model_file : str, pathlib.Path or None, optional (default=None)
            Path to the model file.
        model_str : str or None, optional (default=None)
            Model will be loaded from this string.
        FTtrainingr  N.Training data should be Dataset instance, met machinesrK  r>   rL  r  zInvalid machines in params.num_machineslocal_listen_portp0  time_outx   )r  r  listen_time_outr  r   r   r  z;Ignoring params argument, using parameters from model file.z=Ignoring params argument, using parameters from model string.z[Need at least one training dataset or model file or model string to create Booster instance):r@   r   r  _network_Booster__need_reload_eval_info_train_data_name_Booster__set_objective_to_nonebest_iteration
best_scorer   r   r"   r~   r   r/   rR  rO  rs   r   rX  r   r  r   r   set_networkrD  r  r@  r  r  rB   r   LGBM_BoosterCreaterE   rF   r  
valid_setsname_valid_sets_Booster__num_datasetr|  _Booster__init_predictorLGBM_BoosterMergerA   r  rG   _Booster__num_class_Booster__inner_predict_buffer_Booster__is_predicted_cur_iter_Booster__get_eval_infor  r~  train_set_versionr  r  r   _get_loaded_parammodel_from_stringr>   )
rk   r>   r  r  r  r  num_machines_from_machine_listr  r  r  s
             r5   r  zBooster.__init__k  s   ( ('+$ *',$ 68~8F+; i1"PQUV_Q`QiQiPj kll( *"F j!)

:t,!*-h,589L5M24+658]2"xx1H$%BCC,$2!"@
 -$7!"'
   %&,-@&A$*JJz3$?!'!7	 !  !MM)..01+F3J''%%:&LL. 'DN-/DO.0D !"D$-$8$8D!$$0**--55 #LLOM..LLLL/  -22DGKfD',17D(  "&/&B&BD#%.%6%6D"@ ? #!'a443z?+LL!34LL. #LLOM..LLLL/  -22D&>&TD#Z[++-F  """9-\]++-F
  m r4   r7   c                     	 | j                   r| j                          	 | j                  )t	        t        j                  | j                               y y # t        $ r Y Bw xY w# t        $ r Y y w xY wr9   )r  free_networkr  r  rB   r   r  r  s    r5   r  zBooster.__del__  sl    	}}!!#	||'400>? (  		
  		s"   A 4A$ 	A! A!$	A0/A0c                 $    | j                  d       S r9   )__deepcopy__r  s    r5   __copy__zBooster.__copy__  s      &&r4   r=  kwargsc                 >    | j                  d      }t        |      S )Nr  r  r  )model_to_stringr!   )rk   r=  r  r  s       r5   r  zBooster.__deepcopy__  s     ((r(:	++r4   c                     | j                   j                         }|d   }|j                  dd        |j                  dd        || j                  d      |d<   |S )Nr  r  r  r  r  )r  r   rO  r  )rk   r  r  s      r5   r  zBooster.__getstate__  s[    }}!!#id#t$"222DDOr4   statec           	      |   |j                  d|j                  dd             }|}t        j                         }t        j                  d      }t	        t        j                  t        |      t        j                  |      t        j                  |                   ||d<   | j                  j                  |       y )Nr  r  r   )rD  r@   r   rA   rB   r   LGBM_BoosterLoadModelFromStringrE   rF   r  r@  )rk   r  r  r  r  s        r5   __setstate__zBooster.__setstate__  s    IIi8T)BC	 __&F!'a449%LL!34LL(  &E)U#r4   c           	         d}t        j                  d      }t        j                  |      }t        j                  t        j                  |            }t        t        j                  | j                  t        j                  |      t        j                  |      |             |j                  }||kD  rt        j                  |      }t        j                  t        j                  |            }t        t        j                  | j                  t        j                  |      t        j                  |      |             t        j                  |j                  j                  d            S )Nr*  r   r   )r@   r   r2  r   r3  rB   r   LGBM_BoosterGetLoadedParamr  rF   rG   r5  r6  r   )rk   r7  r8  r9  r:  r;  s         r5   r  zBooster._get_loaded_param   s   
nnQ'33J?"OOF,<,<],KL++z*[)!		
 !&&

""77
CM &0@0@0O P//LLNN:.LL-%	 zz---44W=>>r4   c                     | j                   j                  dd       | j                   j                  dd       d| _        | S )zFree Booster's Datasets.

        Returns
        -------
        self : Booster
            Booster without Datasets.
        r  Nr  r   )r  rO  r  r  s    r5   free_datasetzBooster.free_dataset<  s9     	+t,,-r4   c                 "    g | _         g | _        | S r9   )r  r  r  s    r5   _free_bufferzBooster._free_bufferI  s    &(#')$r4   r  r  r  r  c           
      (   t        |t        t        f      rdj                  |      }t	        t        j                  t        |      t        j                  |      t        j                  |      t        j                  |                   d| _
        | S )a1  Set the network configuration.

        Parameters
        ----------
        machines : list, set or str
            Names of machines.
        local_listen_port : int, optional (default=12400)
            TCP listen port for local machines.
        listen_time_out : int, optional (default=120)
            Socket time-out in minutes.
        num_machines : int, optional (default=1)
            The number of machines for distributed learning application.

        Returns
        -------
        self : Booster
            Booster with set network.
        r  T)r   r   r  r   rB   r   LGBM_NetworkInitrE   r@   rA   r  )rk   r  r  r  r  s        r5   r  zBooster.set_networkN  sq    2 hs,xx)H!!x ./_-\*		
 r4   c                 N    t        t        j                                d| _        | S )zFree Booster's network.

        Returns
        -------
        self : Booster
            Booster with freed network.
        F)rB   r   LGBM_NetworkFreer  r  s    r5   r  zBooster.free_networkt  s!     	4((*+r4   c                    t         st        d      | j                         dk(  rt        d      dt        t        t
        f   dt        fd	 	 	 	 ddt        t        t
        f   dt        dt        t           d	t        t        t              d
t        t           dt        t        t
        f   ffd	 	 	 	 ddt        t        t
        f   dt        dt        t           d	t        t        t              d
t        t           dt        t        t        t
        f      ffd| j                         }|d	   }g }|d   D ]"  }|j                   |d   |d   |             $ t        ||d   j                               S )a  Parse the fitted model and return in an easy-to-read pandas DataFrame.

        The returned DataFrame has the following columns.

            - ``tree_index`` : int64, which tree a node belongs to. 0-based, so a value of ``6``, for example, means "this node is in the 7th tree".
            - ``node_depth`` : int64, how far a node is from the root of the tree. The root node has a value of ``1``, its direct children are ``2``, etc.
            - ``node_index`` : str, unique identifier for a node.
            - ``left_child`` : str, ``node_index`` of the child node to the left of a split. ``None`` for leaf nodes.
            - ``right_child`` : str, ``node_index`` of the child node to the right of a split. ``None`` for leaf nodes.
            - ``parent_index`` : str, ``node_index`` of this node's parent. ``None`` for the root node.
            - ``split_feature`` : str, name of the feature used for splitting. ``None`` for leaf nodes.
            - ``split_gain`` : float64, gain from adding this split to the tree. ``NaN`` for leaf nodes.
            - ``threshold`` : float64, value of the feature used to decide which side of the split a record will go down. ``NaN`` for leaf nodes.
            - ``decision_type`` : str, logical operator describing how to compare a value to ``threshold``.
              For example, ``split_feature = "Column_10", threshold = 15, decision_type = "<="`` means that
              records where ``Column_10 <= 15`` follow the left side of the split, otherwise follows the right side of the split. ``None`` for leaf nodes.
            - ``missing_direction`` : str, split direction that missing values should go to. ``None`` for leaf nodes.
            - ``missing_type`` : str, describes what types of values are treated as missing.
            - ``value`` : float64, predicted value for this leaf node, multiplied by the learning rate.
            - ``weight`` : float64 or int64, sum of Hessian (second-order derivative of objective), summed over observations that fall in this node.
            - ``count`` : int64, number of records in the training data that fall into this node.

        Returns
        -------
        result : pandas DataFrame
            Returns a pandas DataFrame of the parsed model.
        zxThis method cannot be run without pandas installed. You must install pandas and restart your session to use this method.r   z<There are no trees in this Booster and thus nothing to parsetreer7   c                 &    d| j                         v S )Nsplit_index)rN  r  s    r5   _is_split_nodez2Booster.trees_to_dataframe.<locals>._is_split_node  s     DIIK//r4   
node_depth
tree_indexfeature_namesparent_nodec                    dt         t        t        f   dt        t           dt        f	fd}dt         t        t        f   dt        t
        t              dt        t           f	fd}dt         t        t        f   dt        fd}t               }||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<    	|       rd || d
   |      |d
<    || d   |      |d<   | d   |d<   | d   |d<   | d   |d<   | d   rdnd|d<   | d   |d<   | d   |d<   | d   |d<   | d   |d<   |S | d   |d<    ||       s| d   |d<   | d   |d<   |S ) Nr  r  r7   c                 n    || dnd} |       }|rdnd}| j                  |rdndd      }| | | S )N-r   SLr  
leaf_indexr   )rD  )r  r  tree_numis_split	node_typenode_numr  s         r5   _get_node_indexzOBooster.trees_to_dataframe.<locals>.create_node_record.<locals>._get_node_index  sS     0:/Ej\+2)$/#+C	88XM<QRS"I;xj99r4   r  c                 B     |       r|
|| d      }|S | d   }|S d }|S )Nsplit_featurer3   )r  r  r  r  s      r5   _get_split_featurezRBooster.trees_to_dataframe.<locals>.create_node_record.<locals>._get_split_feature  sK    
 "$'$0'4T/5J'K
 $# (,O'< $# $(L##r4   c                 >    t        | j                               ddhk(  S )N
leaf_value
leaf_count)r  rN  r  s    r5   _is_single_node_treezTBooster.trees_to_dataframe.<locals>.create_node_record.<locals>._is_single_node_tree  s    499;'L,+GGGr4   r  
node_index
left_childright_childparent_index)r  r  r  
split_gain	thresholddecision_typemissing_directionmissing_typerG   rT  countdefault_leftleftrightinternal_valueinternal_weightinternal_countr  leaf_weightr  )r   rs   r   r   r  r   rq  r   )
r  r  r  r  r  r  r  r  noder  s
            r5   create_node_recordz6Booster.trees_to_dataframe.<locals>.create_node_record  s#   	:38n	:$SM	: 	:$38n$  (S	2$ #	$H4S> Hd H 6A]D!+D!+D!0z!BD!%D"&D#.D $6DP]$^D!!%D $D$(D!(,D$%#'D  DM!DN DM d#%4T,5G%T\"&5d=6I:&V]#%),%7\"$($5[!(,_(=_%6:>6JFPW()'+N';^$ $%5 6W!%&7!8X $%5 6W K !%\ 2W+D1%)-%8DN$($6DMKr4   c           	           | ||||      }|g} 
|       r2ddg}|D ])  } | |   |dz   |||d         }	|j                  |	       + |S )N)r  r  r  r  r  r  r  r   r  )extend)r  r  r  r  r  r  reschildrenchildsubtree_listr  r  tree_dict_to_node_lists             r5   r  z:Booster.trees_to_dataframe.<locals>.tree_dict_to_node_list  s     &%%+'D &Cd#(-8% 
-E#9!%[#->#-&3$($6$L JJ|,
- Jr4   	tree_infotree_structure)r  r  r  r  )r   NNN)r   r$   	num_treesr   rs   r   rq  r  r   r   
dump_modelr  r   rN  )rk   
model_dictr  
model_listr  r  r  r  s        @@@r5   trees_to_dataframezBooster.trees_to_dataframe  s   8  W 
 >>q  ^__	0c3h 	0D 	0
  (,15)-G	sCx.G	G	 !G	 $DI.	G	
 "#G	 #s(^G	V  (,15)-	sCx.		 !	 $DI.		
 "#	 $sCx.!	B __&
"?3
{+ 	D&./D<N^k	 J
10B0B0DEEr4   r   c                     || _         | S )zSet the name to the training Dataset.

        Parameters
        ----------
        name : str
            Name for the training Dataset.

        Returns
        -------
        self : Booster
            Booster with set training Dataset name.
        )r  )rk   r   s     r5   set_train_data_namezBooster.set_train_data_name  s     !%r4   r[   c                 2   t        |t              s!t        dt        |      j                         |j
                  | j                  urt        d      t        t        j                  | j                  |j                         j                               | j                  j                  |       | j                  j                  |       | xj                   dz  c_        | j"                  j                  d       | j$                  j                  d       | S )a  Add validation data.

        Parameters
        ----------
        data : Dataset
            Validation data.
        name : str
            Name of validation data.

        Returns
        -------
        self : Booster
            Booster with set validation data.
        z0Validation data should be Dataset instance, met zHAdd validation data failed, you should use same predictor for these datar   NF)r   r"   r~   r   r/   r|  r  r$   rB   r   LGBM_BoosterAddValidDatar  r  r  r   r  r  r  r  )rk   r[   r   s      r5   	add_validzBooster.add_valid.  s     $(NtTXzObObNcdee??$"7"77 jkk)) ((	
 	t$##D)a##**40$$++E2r4   c                     t        |      }|r2t        t        j                  | j                  t        |                   | j                  j                  |       | S )zReset parameters of Booster.

        Parameters
        ----------
        params : dict
            New parameters for Booster.

        Returns
        -------
        self : Booster
            Booster with new parameters.
        )r  rB   r   LGBM_BoosterResetParameterr  rE   r>   r@  )rk   r>   r  s      r5   reset_parameterzBooster.reset_parameterN  sO     (/
//LL:& 	6"r4   fobjc                 j   |2| j                   | j                  j                  k7  r| j                  }d}n)|| j                  u xr | j                   |j                  k(  }||st        |t              s!t        dt        |      j                         |j                  | j                  urt        d      || _        t        t        j                  | j                  | j                  j                         j                               d| j                   d<   | j                  j                  | _         t#        j$                  d      }|| j&                  rt        d      t        t        j(                  | j                  t#        j*                  |                   t-        | j.                        D cg c]  }d c}| _        |j2                  dk(  S | j&                  sd| j5                  d	d
i      _         || j7                  d      | j                        \  }}| j9                  ||      S c c}w )a  Update Booster for one iteration.

        Parameters
        ----------
        train_set : Dataset or None, optional (default=None)
            Training data.
            If None, last training data is used.
        fobj : callable or None, optional (default=None)
            Customized objective function.
            Should accept two parameters: preds, train_data,
            and return (grad, hess).

                preds : numpy 1-D array or numpy 2-D array (for multi-class task)
                    The predicted values.
                    Predicted values are returned before any transformation,
                    e.g. they are raw margin instead of probability of positive class for binary task.
                train_data : Dataset
                    The training dataset.
                grad : numpy 1-D array or numpy 2-D array (for multi-class task)
                    The value of the first order derivative (gradient) of the loss
                    with respect to the elements of preds for each sample point.
                hess : numpy 1-D array or numpy 2-D array (for multi-class task)
                    The value of the second order derivative (Hessian) of the loss
                    with respect to the elements of preds for each sample point.

            For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes],
            and grad and hess should be returned in the same format.

        Returns
        -------
        produced_empty_tree : bool
            ``True`` if the tree(s) produced by this iteration did not have any splits.
            This usually means that training is "finished" (calling ``update()`` again
            will not change the model's predictions). However, that is not always the
            case. For example, if you have added any randomness (like column sampling by
            setting ``feature_fraction_bynode < 1.0``), it is possible that another call
            to ``update()`` would produce a non-empty tree.
        NFr  zJReplace training data failed, you should use same predictor for these datar   z-Cannot update due to null objective function.r   T	objectivenonedata_idx)gradhess)r  r  r~  r   r"   r~   r   r/   r|  r  r$   rB   r   LGBM_BoosterResetTrainingDatar  r  r  r@   rA   r  LGBM_BoosterUpdateOneIterrF   r  r  r  rG   r-  _Booster__inner_predict_Booster__boost)rk   r  r.  is_the_same_train_setproduced_empty_treer  r4  r5  s           r5   r@  zBooster.updatef  s   X !7!74>>;Q;Q!QI$)!$-$?$oDDZDZ^g^o^oDo! )>i1"PQUV_Q`QiQiPj kll##4+@+@@#$pqq&DN22LLNN,,.66 .2D''*%)^^%;%;D"$ll1o<++#$STT..LLLL!45 <AASAS;T+UaE+UD(&,,11//VZ$$k6%:;Sd22A2>OJD$<<T<55 ,Vs   3	H0r4  r5  c                   | j                   dkD  r$|j                  d      }|j                  d      }t        |t        j                  d      }t        |t        j                  d      }|j
                  j                  sJ |j
                  j                  sJ t        |      t        |      k7  r$t        dt        |       dt        |       d	      | j                  j                         }t        |      || j                   z  k7  r4t        dt        |       dt        |       d
| d| j                    d	      t        j                  d      }t        t        j                  | j                   |j                  j#                  t        j$                  t        j&                              |j                  j#                  t        j$                  t        j&                              t        j(                  |                   t+        | j,                        D cg c]  }d c}| _        |j0                  dk(  S c c}w )a  Boost Booster for one iteration with customized gradient statistics.

        .. note::

            Score is returned before any transformation,
            e.g. it is raw margin instead of probability of positive class for binary task.
            For multi-class task, score are numpy 2-D array of shape = [n_samples, n_classes],
            and grad and hess should be returned in the same format.

        Parameters
        ----------
        grad : numpy 1-D array or numpy 2-D array (for multi-class task)
            The value of the first order derivative (gradient) of the loss
            with respect to the elements of score for each sample point.
        hess : numpy 1-D array or numpy 2-D array (for multi-class task)
            The value of the second order derivative (Hessian) of the loss
            with respect to the elements of score for each sample point.

        Returns
        -------
        produced_empty_tree : bool
            ``True`` if the tree(s) produced by this iteration did not have any splits.
            This usually means that training is "finished" (calling ``__boost()`` again
            will not change the model's predictions). However, that is not always the
            case. For example, if you have added any randomness (like column sampling by
            setting ``feature_fraction_bynode < 1.0``), it is possible that another call
            to ``__boost()`` would produce a non-empty tree.
        r   rM   rQ   gradientr   hessianzLengths of gradient (z) and Hessian (rO  z$) don't match training data length (z() * number of models per one iteration (r_  r   F)r  rY   r   rR   rS   rU   r\  r   r   r  r  r@   rA   rB   r   LGBM_BoosterUpdateOneIterCustomr  ra  r   r   rF   r  r  r  rG   )rk   r4  r5  num_train_datar;  r  s         r5   __boostzBooster.__boost  s   D a::C:(D::C:(D d"**:N d"**9Mzz&&&&zz&&&&t9D	!4SYKsSWykYfghh002t9)9)999'D	{/#d) M55C4D E77;7G7G6HK 
 %ll1o00##FNN6>>$BC##FNN6>>$BC01		
 8=T=O=O7P'Q!'Q$"((A-- (Rs   	H>c                     t        t        j                  | j                               t	        | j
                        D cg c]  }d c}| _        | S c c}w )zRollback one iteration.

        Returns
        -------
        self : Booster
            Booster with rolled back one iteration.
        F)rB   r   LGBM_BoosterRollbackOneIterr  r  r  r  )rk   r  s     r5   rollback_one_iterzBooster.rollback_one_iter  sD     	433DLLAB7<T=O=O7P'Q!'Q$ (Rs    	Ac                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S rj  rk  rl  s     r5   rm  zBooster.current_iteration  rn  r4   c                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S )zGet number of models per iteration.

        Returns
        -------
        model_per_iter : int
            The number of models per iteration.
        r   )r@   rA   rB   r    LGBM_BoosterNumModelPerIterationr  rF   rG   )rk   model_per_iters     r5   num_model_per_iterationzBooster.num_model_per_iteration  sH      a11^,	
 ###r4   c                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S )zGet number of weak sub-models.

        Returns
        -------
        num_trees : int
            The number of weak sub-models.
        r   )r@   rA   rB   r   LGBM_BoosterNumberOfTotalModelr  rF   rG   )rk   r!  s     r5   r!  zBooster.num_trees#  sF     LLO	//Y'	
 r4   c                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S )zGet upper bound value of a model.

        Returns
        -------
        upper_bound : float
            Upper bound value of the model.
        r   )r@   r   rB   r   LGBM_BoosterGetUpperBoundValuer  rF   rG   rt  s     r5   upper_boundzBooster.upper_bound4  G     ooa //S!	
 yyr4   c                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S )zGet lower bound value of a model.

        Returns
        -------
        lower_bound : float
            Lower bound value of the model.
        r   )r@   r   rB   r   LGBM_BoosterGetLowerBoundValuer  rF   rG   rt  s     r5   lower_boundzBooster.lower_boundE  rO  r4   fevalc                 H   t        |t              st        d      d}|| j                  u rd}n;t	        t        | j                              D ]  }|| j                  |   u s|dz   } n |dk(  r!| j                  ||       | j                  dz
  }| j                  |||      S )a  Evaluate for data.

        Parameters
        ----------
        data : Dataset
            Data for the evaluating.
        name : str
            Name of the data.
        feval : callable, list of callable, or None, optional (default=None)
            Customized evaluation function.
            Each evaluation function should accept two parameters: preds, eval_data,
            and return (metric_name, metric_value, maximize) or list of such tuples.

                preds : numpy 1-D array or numpy 2-D array (for multi-class task)
                    The predicted values.
                    For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes].
                    If custom objective function is used, predicted values are returned before any transformation,
                    e.g. they are raw margin instead of probability of positive class for binary task in this case.
                eval_data : Dataset
                    A ``Dataset`` to evaluate.
                metric_name : str
                    Unique identifier for the metric (e.g. "custom_adjusted_mse").
                metric_value : float
                    Value of the evaluation metric.
                maximize : bool
                    Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.

        Returns
        -------
        result : list[EvalResult]
            List of ``lightgbm.EvalResult`` objects, named tuples of the form
            (dataset_name, metric_name, metric_value, maximize).
        z"Can only eval for Dataset instancer  r   r   	data_namer3  rS  )
r   r"   r~   r  r  r   r  r*  r  _Booster__inner_eval)rk   r[   r   rS  r3  rC  s         r5   evalzBooster.evalV  s    N $(@AA4>>!H3t/0 4??1-- 1uH
 r>NN4&))A-H  4(% PPr4   c                 >    | j                  | j                  d|      S )a  Evaluate for training data.

        Parameters
        ----------
        feval : callable, list of callable, or None, optional (default=None)
            Customized evaluation function.
            Each evaluation function should accept two parameters: preds, eval_data,
            and return (metric_name, metric_value, maximize) or list of such tuples.

                preds : numpy 1-D array or numpy 2-D array (for multi-class task)
                    The predicted values.
                    For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes].
                    If custom objective function is used, predicted values are returned before any transformation,
                    e.g. they are raw margin instead of probability of positive class for binary task in this case.
                eval_data : Dataset
                    The training dataset.
                metric_name : str
                    Unique identifier for the metric (e.g. "custom_adjusted_mse").
                metric_value : float
                    Value of the evaluation metric.
                maximize : bool
                    Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.

        Returns
        -------
        result : list[EvalResult]
            List of ``lightgbm.EvalResult`` objects, named tuples of the form
            (dataset_name, metric_name, metric_value, maximize).
        r   rU  )rW  r  )rk   rS  s     r5   
eval_trainzBooster.eval_train  s$    B   4+@+@1TY ZZr4   c           	          t        d| j                        D cg c]-  }| j                  | j                  |dz
     ||      D ]  }| / c}}S c c}}w )a  Evaluate for validation data.

        Parameters
        ----------
        feval : callable, list of callable, or None, optional (default=None)
            Customized evaluation function.
            Each evaluation function should accept two parameters: preds, eval_data,
            and return (metric_name, metric_value, maximize) or list of such tuples.

                preds : numpy 1-D array or numpy 2-D array (for multi-class task)
                    The predicted values.
                    For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes].
                    If custom objective function is used, predicted values are returned before any transformation,
                    e.g. they are raw margin instead of probability of positive class for binary task in this case.
                eval_data : Dataset
                    The validation dataset.
                metric_name : str
                    Unique identifier for the metric (e.g. "custom_adjusted_mse").
                metric_value : float
                    Value of the evaluation metric.
                maximize : bool
                    Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.

        Returns
        -------
        result : list
            List of ``lightgbm.EvalResult`` objects, named tuples of the form
            (dataset_name, metric_name, metric_value, maximize).
        r   rU  )r  r  rW  r  )rk   rS  rC  r   s       r5   
eval_validzBooster.eval_valid  sj    F 1d001
))D4H4HQ4OZ[ch)i
  

 	
 
s   2Ar-  r  r  importance_typec                 N   || j                   }t        |   }t        t        j                  | j
                  t        j                  |      t        j                  |      t        j                  |      t        t        |                         t        | j                  |       | S )a  Save Booster to file.

        Parameters
        ----------
        filename : str or pathlib.Path
            Filename to save Booster.
        num_iteration : int or None, optional (default=None)
            Index of the iteration that should be saved.
            If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
            If <= 0, all iterations are saved.
        start_iteration : int, optional (default=0)
            Start index of the iteration that should be saved.
        importance_type : str, optional (default="split")
            What type of feature importance should be saved.
            If "split", result contains numbers of times the feature is used in a model.
            If "gain", result contains total gains of splits which use the feature.

        Returns
        -------
        self : Booster
            Returns self.
        )r  _FEATURE_IMPORTANCE_TYPE_MAPPERrB   r   LGBM_BoosterSaveModelr  r@   rA   rE   rs   r  r  )rk   r-  r  r  r]  importance_type_ints         r5   
save_modelzBooster.save_model  s    :   //M=oN&&_-]+01s8}%	
 	!!8!8(Cr4   end_iterationc           	          t        t        j                  | j                  t	        j
                  |      t	        j
                  |                   | S )a  Shuffle models.

        Parameters
        ----------
        start_iteration : int, optional (default=0)
            The first iteration that will be shuffled.
        end_iteration : int, optional (default=-1)
            The last iteration that will be shuffled.
            If <= 0, means the last available iteration.

        Returns
        -------
        self : Booster
            Booster with shuffled models.
        )rB   r   LGBM_BoosterShuffleModelsr  r@   rA   )rk   r  rc  s      r5   shuffle_modelszBooster.shuffle_models  s@    ( 	**_-]+	
 r4   c           	      j   t        t        j                  | j                               | j	                          t        j                         | _        t        j                  d      }t        t        j                  t        |      t        j                  |      t        j                  | j                                     t        j                  d      }t        t        j                  | j                  t        j                  |                   |j                  | _        t        |      | _        | S )zLoad Booster from a string.

        Parameters
        ----------
        model_str : str
            Model will be loaded from this string.

        Returns
        -------
        self : Booster
            Loaded Booster object.
        r   r  )rB   r   r  r  r  r@   r   rA   r  rE   rF   r  rG   r  r  r  )rk   r  r  r  s       r5   r  zBooster.model_from_string!  s     	4((67(#\\!_00y!/0T\\*	
 Q**]+	
 )..":Y"Or4   c                    || j                   }t        |   }d}t        j                  d      }t        j                  |      }t        j
                  t        j                  |            }t        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |      t        j                  |      |             |j                  }	|	|kD  rt        j                  |	      }t        j
                  t        j                  |            }t        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |	      t        j                  |      |             |j                  j                  d      }
|
t        | j                         z  }
|
S )aN  Save Booster to string.

        Parameters
        ----------
        num_iteration : int or None, optional (default=None)
            Index of the iteration that should be saved.
            If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
            If <= 0, all iterations are saved.
        start_iteration : int, optional (default=0)
            Start index of the iteration that should be saved.
        importance_type : str, optional (default="split")
            What type of feature importance should be saved.
            If "split", result contains numbers of times the feature is used in a model.
            If "gain", result contains total gains of splits which use the feature.

        Returns
        -------
        str_repr : str
            String representation of Booster.
        r*  r   r   )r  r_  r@   r   r2  r   r3  rB   r   LGBM_BoosterSaveModelToStringr  rA   rF   rG   r   r  r  )rk   r  r  r]  ra  r7  r8  r9  r:  r;  r   s              r5   r  zBooster.model_to_stringF  s   4   //M=oN
nnQ'33J?"OOF,<,<],KL.._-]+01z*[)!
	
 !&&

""77
CM &0@0@0O P22LLLL1LL/LL!45NN:.LL-%
 !!((1'(?(?@@
r4   r1  c                    || j                   }t        |   }d}t        j                  d      }t        j                  |      }t        j
                  t        j                  |            }	t        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |      t        j                  |      |	             |j                  }
|
|kD  rt        j                  |
      }t        j
                  t        j                  |            }	t        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |
      t        j                  |      |	             t        j                  |j                  j!                  d      |      }t        j                  t        j"                  | j$                  t&                    |d<   |S )a  Dump Booster to JSON format.

        Parameters
        ----------
        num_iteration : int or None, optional (default=None)
            Index of the iteration that should be dumped.
            If None, if the best iteration exists, it is dumped; otherwise, all iterations are dumped.
            If <= 0, all iterations are dumped.
        start_iteration : int, optional (default=0)
            Start index of the iteration that should be dumped.
        importance_type : str, optional (default="split")
            What type of feature importance should be dumped.
            If "split", result contains numbers of times the feature is used in a model.
            If "gain", result contains total gains of splits which use the feature.
        object_hook : callable or None, optional (default=None)
            If not None, ``object_hook`` is a function called while parsing the json
            string returned by the C API. It may be used to alter the json, to store
            specific values while building the json structure. It avoids
            walking through the structure again. It saves a significant amount
            of time if the number of trees is huge.
            Signature is ``def object_hook(node: dict) -> dict``.
            None is equivalent to ``lambda node: node``.
            See documentation of ``json.loads()`` for further details.

        Returns
        -------
        json_repr : dict
            JSON format of Booster.
        r*  r   r   r0  r  r  )r  r_  r@   r   r2  r   r3  rB   r   LGBM_BoosterDumpModelr  rA   rF   rG   r5  r6  r   r  r  r  )rk   r  r  r]  r1  ra  r7  r8  r9  r:  r;  r   s               r5   r"  zBooster.dump_model  s   H   //M=oN
nnQ'33J?"OOF,<,<],KL&&_-]+01z*[)!
	
 !&&

""77
CM &0@0@0O P**LLLL1LL/LL!45NN:.LL-%
 jj,,33G<+V$(JJJJ''0%
 ! 
r4   r  r  r  r  r  c	           
          t         j                  | t        |	            }
||dk  r| j                  }nd}|
j	                  ||||||||      S )a	  Make a prediction.

        Parameters
        ----------
        data : str, pathlib.Path, numpy array, pandas DataFrame, scipy.sparse, pyarrow Table or polars DataFrame
            Data source for prediction.
            If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM).

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        start_iteration : int, optional (default=0)
            Start index of the iteration to predict.
            If <= 0, starts from the first iteration.
        num_iteration : int or None, optional (default=None)
            Total number of iterations used in the prediction.
            If None, if the best iteration exists and start_iteration <= 0, the best iteration is used;
            otherwise, all iterations from ``start_iteration`` are used (no limits).
            If <= 0, all iterations from ``start_iteration`` are used (no limits).
        raw_score : bool, optional (default=False)
            Whether to predict raw scores.
        pred_leaf : bool, optional (default=False)
            Whether to predict leaf index.
        pred_contrib : bool, optional (default=False)
            Whether to predict feature contributions.

            .. note::

                If you want to get more explanations for your model's predictions using SHAP values,
                like SHAP interaction values,
                you can install the shap package (https://github.com/slundberg/shap).
                Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra
                column, where the last column is the expected value.

        data_has_header : bool, optional (default=False)
            Whether the data has header.
            Used only if data is str.
        validate_features : bool, optional (default=False)
            If True, ensure that the features used to predict match the ones used to train.
            Used only if data is pandas DataFrame.
        **kwargs
            Other parameters for the prediction.

        Returns
        -------
        result : numpy array, scipy.sparse or list of scipy.sparse
            Prediction result.
            Can be sparse or a list of sparse objects (each element represents predictions for one class) for feature contributions (when ``pred_contrib=True``).
        r  r  r   r  )r[   r  r  r  r  r  r  r  )r  r  r   r  r  )rk   r[   r  r  r  r  r  r  r  r  r  s              r5   r  zBooster.predict  su    @ $00#F+ 1 
	  !# $ 3 3 "  +'%+/ ! 	
 		
r4   rS  
decay_raterw  rT  rV  rU  r  r  r  rx  c                    | j                   rt        d      |
i }
t        j                  | t	        |            }|j                  |dd|      }|j                  \  }}t        j                  d      }t        t        j                  | j                  t        j                  |                   t        d| j                  d	      }t!        |j"                        |d<   |j%                  |
       t        d
|d	      }|j'                  d
      }|r|	dk(  r|}	n||	k7  rd}t        |      t)        ||||||||	||
      }||d<   t+        ||      }t        t        j,                  |j                  |j                               |j/                  d      }t1        |      \  }}}t        t        j2                  |j                  |t        j4                  |      t        j4                  |                   | j6                  |_        |S )a  Refit the existing Booster by new data.

        Parameters
        ----------
        data : str, pathlib.Path, numpy array, pandas DataFrame, scipy.sparse, Sequence, list of Sequence, list of numpy array, pyarrow Table or polars DataFrame
            Data source for refit.
            If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM).

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        label : list, numpy 1-D array, pandas Series / one-column DataFrame, pyarrow ChunkedArray, polars Series or None
            Label for refit.

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        decay_rate : float, optional (default=0.9)
            Decay rate of refit,
            will use ``leaf_output = decay_rate * old_leaf_output + (1.0 - decay_rate) * new_leaf_output`` to refit trees.
        reference : Dataset or None, optional (default=None)
            Reference for ``data``.

            .. versionadded:: 4.0.0

        weight : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Weight for each ``data`` instance. Weights should be non-negative.

            .. versionadded:: 4.0.0

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        group : list, numpy 1-D array, pandas Series, pyarrow ChunkedArray, polars Series or None, optional (default=None)
            Group/query size for ``data``.
            Only used in the learning-to-rank task.
            sum(group) = n_samples.
            For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
            where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.

            .. versionadded:: 4.0.0

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), pyarrow ChunkedArray, pyarrow Table (for multi-class task), polars Series, polars DataFrame (for multi-class task) or None, optional (default=None)
            Init score for ``data``.

            .. versionadded:: 4.0.0

            .. versionadded:: 4.2.0
                Support for ``pyarrow`` inputs

            .. versionadded:: 4.7.0
                Support for ``polars`` inputs

        feature_name : list of str, or 'auto', optional (default="auto")
            Feature names for ``data``.
            If 'auto' and data is pandas DataFrame, data columns names are used.

            .. versionadded:: 4.0.0

        categorical_feature : list of str or int, or 'auto', optional (default="auto")
            Categorical features for ``data``.
            If list of int, interpreted as indices.
            If list of str, interpreted as feature names (need to specify ``feature_name`` as well).
            If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.
            All values in categorical features will be cast to int32 and thus should be less than int32 max value (2147483647).
            Large values could be memory consuming. Consider using consecutive integers starting from zero.
            All negative values in categorical features will be treated as missing values.
            The output cannot be monotonically constrained with respect to a categorical feature.
            Floating point numbers in categorical features will be rounded towards 0.

            .. versionadded:: 4.0.0

        dataset_params : dict or None, optional (default=None)
            Other parameters for Dataset ``data``.

            .. versionadded:: 4.0.0

        free_raw_data : bool, optional (default=True)
            If True, raw data is freed after constructing inner Dataset for ``data``.

            .. versionadded:: 4.0.0

        validate_features : bool, optional (default=False)
            If True, ensure that the features used to refit the model match the original ones.
            Used only if data is pandas DataFrame.

            .. versionadded:: 4.0.0

        **kwargs
            Other parameters for refit.
            These parameters will be passed to ``predict`` method.

        Returns
        -------
        result : Booster
            Refitted Booster.
        z,Cannot refit due to null objective function.Nrm  r  T)r[   r  r  r  r   r  r  r  r  ar  'categorical_feature' value passed to Booster.refit() is different from  'categorical_feature' value found in Booster.params. Preferring the value passed via keyword argument. Using refit() to change which columns are treated as categorical is not supported. If you have a valid use case for this, please open an issue at https://github.com/lightgbm-org/LightGBM/issues.)
r[   rS  rw  rT  rV  rU  r  r  r>   rx  refit_decay_rate)r  r$   r  r  r   r  r   r@   rA   rB   r   LGBM_BoosterGetLinearr  rF   rR  r>   rq  rG   r@  rO  r"   r!   r  r  rm  LGBM_BoosterRefitrD   r  )rk   r[   rS  rn  rw  rT  rV  rU  r  r  r  rx  r  r  r  
leaf_predsr  r  out_is_linear
new_paramscat_features_from_params	error_msgr  new_boosterre  r  s                             r5   refitzBooster.refit)  s   z '' NOO!N#00hW]N^0_	!*!2!2/	 "3 "

  %%
dQ&&]+	
 ));;


 %))<)<$=
=!.)
 )1


 $.>>2G#H  $"f,&>#)-@@F  $I..!% 3'
	 *4
%&j)4""##!!	
  ''+
%j1!Q""##t$t$		
  $}}r4   tree_idleaf_idc           
         t        j                  d      }t        t        j                  | j
                  t        j                  |      t        j                  |      t        j                  |                   |j                  S )a#  Get the output of a leaf.

        Parameters
        ----------
        tree_id : int
            The index of the tree.
        leaf_id : int
            The index of the leaf in the tree.

        Returns
        -------
        result : float
            The output of the leaf.
        r   )	r@   r   rB   r   LGBM_BoosterGetLeafValuer  rA   rF   rG   )rk   rz  r{  r   s       r5   get_leaf_outputzBooster.get_leaf_output  s_     ooa ))W%W%S!		
 yyr4   rG   c           
          t        t        j                  | j                  t	        j
                  |      t	        j
                  |      t	        j                  |                   | S )a  Set the output of a leaf.

        .. versionadded:: 4.0.0

        Parameters
        ----------
        tree_id : int
            The index of the tree.
        leaf_id : int
            The index of the leaf in the tree.
        value : float
            Value to set as the output of the leaf.

        Returns
        -------
        self : Booster
            Booster with the leaf output set.
        )rB   r   LGBM_BoosterSetLeafValuer  r@   rA   r   )rk   rz  r{  rG   s       r5   set_leaf_outputzBooster.set_leaf_output  sL    0 	))W%W%&		
 r4   c                     t        j                  d      }t        t        j                  | j
                  t        j                  |                   |j                  S )zGet number of features.

        Returns
        -------
        num_feature : int
            The number of features.
        r   )r@   rA   rB   r   LGBM_BoosterGetNumFeaturer  rF   rG   )rk   out_num_features     r5   rP  zBooster.num_feature7  sH     !,,q/**_-	
 $$$r4   c                    | j                         }t        j                  d      }d}t        j                  d      }t	        |      D cg c]  }t        j
                  |       }}t        j                  |z  t        t        j                  |       }t        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |      |             ||j                  k7  rt        d      |j                  }||k  rt	        |      D cg c]  }t        j
                  |       }}t        j                  |z  t        t        j                  |       }t        t        j                  | j                  t        j                  |      t        j                  |      t        j                  |      t        j                  |      |             t	        |      D 	cg c]   }	||	   j                  j!                  d      " c}	S c c}w c c}w c c}	w )zGet names of features.

        Returns
        -------
        result : list of str
            List with names of features.
        r   r\  r]  r   )rP  r@   rA   r^  r  r2  r   r  r3  rB   r   LGBM_BoosterGetFeatureNamesr  rF   rG   r   r   r`  s
             r5   r  zBooster.feature_nameH  s    &&(ll1o&)#&,ooa&8#\abm\noWX&556QRoo$oo;c&BRBRTb>cd,,[)[) ;<89"		
 ++++UVV$?$E$E!&)BB^cdo^pqYZf99:STqNq"(//K"?#fFVFVXfBg!h00LLLL-LL-OO$=>LL!<=&	 BG{ASTAq!''..w7TT; p" r Us   
H?I%I		iterationc                     || j                   }t        |   }t        j                  | j	                         t        j
                        }t        t        j                  | j                  t        j                  |      t        j                  |      |j                  j                  t        j                  t        j                                           |t        k(  r|j!                  t        j"                        S |S )a  Get feature importances.

        Parameters
        ----------
        importance_type : str, optional (default="split")
            How the importance is calculated.
            If "split", result contains numbers of times the feature is used in a model.
            If "gain", result contains total gains of splits which use the feature.
        iteration : int or None, optional (default=None)
            Limit number of iterations in the feature importance calculation.
            If None, if the best iteration exists, it is used; otherwise, all trees are used.
            If <= 0, all trees are used (no limits).

        Returns
        -------
        result : numpy array
            Array with feature importances.
        r   )r  r_  rR   r  rP  rT   rB   r   LGBM_BoosterFeatureImportancer  r@   rA   ra  r   r   _C_API_FEATURE_IMPORTANCE_SPLITr   ri  )rk   r]  r  ra  results        r5   feature_importancezBooster.feature_importancet  s    . ++I=oN$**,BJJ?..Y'01%%fnnV__&EF		
 "AA==**Mr4   rw  binsxgboost_stylec                    dt         t        t        f   ddffd| j                         }|j	                  d      |d   }g |D ]  } |d           |t        |t              r:|r8t        t        j                              }t        |t        ||      n|d      }t        j                  |	      \  }}	|r@t        j                  |	dd |f      }
|
|
dddf   d
kD     }
t        rt        |
ddg      S |
S ||	fS )a,  Get split value histogram for the specified feature.

        Parameters
        ----------
        feature : int or str
            The feature name or index the histogram is calculated for.
            If int, interpreted as index.
            If str, interpreted as name.

            .. warning::

                Categorical features are not supported.

        bins : int, str or None, optional (default=None)
            The maximum number of bins.
            If None, or int and > number of unique split values and ``xgboost_style=True``,
            the number of bins equals number of unique split values.
            If str, it should be one from the list of the supported values by ``numpy.histogram()`` function.
        xgboost_style : bool, optional (default=False)
            Whether the returned result should be in the same form as it is in XGBoost.
            If False, the returned value is tuple of 2 numpy arrays as it is in ``numpy.histogram()`` function.
            If True, the returned value is matrix, in which the first column is the right edges of non-empty bins
            and the second one is the histogram values.

        Returns
        -------
        result_tuple : tuple of 2 numpy arrays
            If ``xgboost_style=False``, the values of the histogram of used splitting values for the specified feature
            and the bin edges.
        result_array_like : numpy array or pandas DataFrame (if pandas is installed)
            If ``xgboost_style=True``, the histogram of used splitting values for the specified feature.
        rootr7   Nc                     d| v rnt        t              r	| d      }n| d   }|k(  r2t        | d   t              rt        d      j                  | d           | d           | d          yy)zRecursively add thresholds.r  Nr  r	  z@Cannot compute split value histogram for the categorical featurer  r  )r   rs   r$   r   )r  r  r  rw  r  r   s     r5   r  z.Booster.get_split_value_histogram.<locals>.add  s    $ ,GS1I$1$2G$HM$($9M G+!${"3S9+,nooMM${"34D&'D'( %r4   r  r  r  r   )r  r   
SplitValueCountr   )r   rs   r   r"  rD  r   r  r   rR   r"  r  r  	histogramcolumn_stackr   r   )rk   rw  r  r  model
tree_infosr  n_uniquehist	bin_edgesr   r  r  r   s    `         @@@r5   get_split_value_histogramz!Booster.get_split_value_histogram  s   N	)d38n 	) 	) 	) !		/2;'
 # 	-I	*+,	- <:dC0]299V,-Hd.>s8T*HaPD,,vD9i//9QR=$"78Cc!Q$i!m$C#C,1HII
?"r4   rV  r3  c                   || j                   k\  rt        d      | j                          g }| j                  dkD  rHt	        j
                  | j                  t        j                        }t        j                  d      }t        t        j                  | j                  t        j                  |      t        j                  |      |j                  j                  t        j                  t        j                                            |j"                  | j                  k7  rt        d      t%        | j                        D ]=  }|j'                  t)        || j*                  |   ||   | j,                  |                ? t/        |      r|g}||dk(  r| j0                  }n| j2                  |dz
     }|D ]  }	|	 |	| j5                  |      |      }
t7        |
t8              r/|
D ])  }|j'                  t)        ||d   |d   |d                + ^|j'                  t)        ||
d   |
d   |
d                 |S )	z%Evaluate training or validation data.1Data_idx should be smaller than number of datasetr   r   zWrong length of eval results)r  r  r  r  r   r2  r   )r  r   r  _Booster__num_inner_evalrR   r  rT   r@   rA   rB   r   LGBM_BoosterGetEvalr  rF   ra  r   r   rG   r  r   r  _Booster__name_inner_eval"_Booster__higher_better_inner_evalrx   r  r  r8  r   r   )rk   rV  r3  rS  r   r  r8  rC  cur_dataeval_function	feval_ret
eval_tuples               r5   __inner_evalzBooster.__inner_eval  s    t)))PQQ  1$XXd332::FF ,,q/K((LLLL*LL-MM))&..*IJ	   D$9$99 !?@@4001 

%.$($:$:1$=%+AY!%!@!@!C	 E?GE1}>>??8a<8!&  ()$*>*>*>*QS[\	i.&/ 


&-6,6qM-7])3A	 JJ")2(1!)21%.q\	. 
r4   c          	         || j                   k\  rt        d      | j                  |   |dk(  r(| j                  j	                         | j
                  z  }n-| j                  |dz
     j	                         | j
                  z  }t        j                  |t        j                        | j                  |<   | j                  |   st        j                  d      }| j                  |   j                  j                  t        j                  t        j                              }t!        t#        j$                  | j&                  t        j(                  |      t        j*                  |      |             |j,                  t/        | j                  |         k7  rt        d|       d| j                  |<   | j                  |   }| j
                  dkD  r7|j0                  | j
                  z  }|j3                  || j
                  d      }|S )	z,Predict for training and validation dataset.r  r   r   r   z)Wrong length of predict results for data TrM   rQ   )r  r   r  r  r  r  r  rR   r  rT   r  r@   r   ra  r   r   rB   r   LGBM_BoosterGetPredictr  rA   rF   rG   r   r  r  )rk   r3  r  r8  r  r  r  s          r5   __inner_predictzBooster.__inner_predict(  s   t)))PQQ&&x081}..113d6F6FF//(Q,7@@BTEUEUU46HHWBJJ4WD''1++H5 ..+K228<CCKKFNN[a[j[jLklH++LLLL*LL-	   C(C(CH(M$NN #LXJ!WXX59D((2!88Ba{{d&6&66H^^Hd.>.>c^JFr4   c                    | j                   r,d| _         t        j                  d      }t        t	        j
                  | j                  t        j                  |                   |j                  | _	        | j                  dkD  rt        j                  d      }d}t        j                  d      }t        | j                        D cg c]  }t        j                  |       }}t        j                  | j                  z  t        t        j                  |       }t        t	        j                   | j                  t        j                  | j                        t        j                  |      t        j                  |      t        j                  |      |             | j                  |j                  k7  rt#        d      |j                  }||k  rt        | j                        D cg c]  }t        j                  |       }}t        j                  | j                  z  t        t        j                  |       }t        t	        j                   | j                  t        j                  | j                        t        j                  |      t        j                  |      t        j                  |      |             t        | j                        D 	cg c]   }	||	   j                  j%                  d      " c}	| _        | j&                  D 
cg c]  }
|
j)                  d       c}
| _        yyyc c}w c c}w c c}	w c c}
w )z%Get inner evaluation count and names.Fr   r\  z1Length of eval names doesn't equal with num_evalsr   )auczndcg@zmap@average_precisionN)r  r@   rA   rB   r   LGBM_BoosterGetEvalCountsr  rF   rG   r  r^  r  r2  r   r  r3  LGBM_BoosterGetEvalNamesr   r   r  r  r  )rk   out_num_evalr8  ra  rb  r  rc  rd  re  rC  r   s              r5   __get_eval_infozBooster.__get_eval_infoG  s   ''+0D(!<<?L..LLLL. %1$6$6D!$$q($ll1o.1+.4ooa.@+V[\`\q\qVr"QRF//0KL" " '-oo8M8M&MPSTZTdTdftPu%v"11T%:%:;[1(CD%@A*	 ((K,=,==$%XYY,G,M,M).1JJX]^b^s^sXt&ST334MN&N & +1//D<Q<Q*QV--~>*& 55 LL"LL)>)>?"LL5"OO,EF"LL)DE.	 \aaeavav[w)xVW.*;*A*A*H*H*Q)x&_c_u_u3W[DOO$QR3/S ) ( "&&  *y3s   
L;.M %MM
)NNNNro  )r7   r!   )r  r  r   NNr9   )Nr   rX  )r   r  )Nr   rX  N)r   NFFFFF)
g?NNNNr  r  NTF)rX  N)NF)Kr/   r0   r1   r2   r   r   rs   r   r"   r   r   r  r  r  r  r  r  r  r  r  r   r   r  r  r  r   r%  r'  r*  r-  _LGBM_CustomObjectiveFunctionrq  r@  rR   r   r9  rD  rm  rI  r!  r   rN  rR  _LGBM_CustomEvalFunctionr  rX  rZ  r\  rb  rf  r  r  r   r"  rr  rs  r  r  r  r  r  r  r  r  ry  r~  r  rP  r  r  r   r  rW  r8  r  r3   r4   r5   r!   r!   h  s    ,0'+15#'Hc3h(H G$H U39-.	H
 C=HT
',# , , ,d38n $$sCx. $T $?4S> ?8 "'"$S	3s8S01$ $ 	$
 $ 
$L
\FL \F| 	  g S Y @d38n  4 (,8<O6G$O6 45O6 
	O6b<. jj<. jj	<.
 
<.|
"3 ""$ $"3 "U "U * \`	6Q6Q 6Q 6=U8VVWX	6Q
 
j	6Qt \`![6=U8VVWX![ 
j	![J \`%
6=U8VVWX%
 
j	%
T (, &*T	"*  }* 	*
 * 
*\  !  
	:#3 #9 #N (, &	>}> > 	>
 
>D (, &LPM}M M 	M
 hS#X'7c3h'GHIM 
c3hMd  !'+" %"'R
#R
 R
  }	R

 R
 R
 R
 R
  R
 R
 
!R
p  '+-1+/487=EK37""'P!P P 	P
 G$P )*P (P 01P 5P CP !c3h0P P  P P 
Pds S U 4     	 
 
 D%S %"*Ud3i *U\  '#'&& C=& 
	&V +/#	H#sCxH# uS#X'H# 	H#
 
uRZZ+,bjj,F	GH#T@ @ 	@
 6=U8VVWX@ 
j	@D3 2:: >8r4   r!   )rl   rr   r9   r  )r2   libpathr   r  r@   r  r5  rp   collectionsr   r   r   enumr   	functoolsr   osr	   r
   os.pathr   pathlibr   tempfiler   typingr   r   r   r   r   r   r   r   r   r   r   r   narwhalsr  narwhals.dependenciesdependenciesr  narwhals.typingnwtnumpyrR   scipy.sparser  compatr   r   r   r   r   r   r    __all__r   rp  r  _ctypes_int_ptr_ctypes_int_array_ctypes_float_ptr_ctypes_float_arrayrs   r   rq  _LGBM_EvalFunctionResultType_LGBM_BoosterBestScoreTyper  r  r  r   
IntoSeriesr  r  IntoDataFramer  r  r  r  r  rr  rs  rt  r  r  r:   _MULTICLASS_OBJECTIVESr:  r$   r<   rI   r\   r^   rf   rt   r  r   r   rz   r%   r   r   r   r   bytesr   rD  r   r   restype	CFUNCTYPEcallbackLGBM_RegisterLogCallbackr   r  rB   r   r   r   r   r   r   r   r   r   r   r   r   	pythonapiPyCapsule_GetPointerr   	py_objectargtypesobjectr   r   r   r   r   r   rE   r   Arrayr   r  r
  r  r  FutureWarningr#   r(  rR  r  rb  rc  rj  rl  rV   rW   r  r  r  r  rO  r]  r  _C_API_FEATURE_IMPORTANCE_GAINr<  r_  r]  rg  rm  rr  r   r~  r  r  r  ABCr&   r  r"   r  r  r  r!   r3   r4   r5   <module>r     s|   $  
     #        ' x x x x  #    Z Z) ' 5  (  6   %S%%56 !#tCJ'7"78 (-d3icDU.U(V %!&tCy2C'C!D KIJJNN	 JJNN 
 KeJJNN  JJ	LL
  KIJJNN JJ	LL   JJ	LL		! 
 !&	LL		!!  KIJJNN	  ecOKIJJ	  c 	I 	2 2$ 2	# 	s 	s 	+rzz +eBJJO&< +&4 ) ) ~    8 8# 8$ 8 #(/// / 
	/28SE4K#8 XseTk=R "-3 -4 -0c 0d 0 -S -T - -*u * * 7;;#W-7%+__D"vfoo6H]+DM$t$$T]]3q82D224;;GDEE ud#	FC 	FD 	FS T AS AT A
- - -1bjj 19N 1SUS]S] 1Ic Id I
S3 S+H SQ Q(C QxC xD x



 !
 	

 ZZ
0WS WT W
Mc Md M
[C [D [
  ))>> !'  #)#3#3V__"E  UV U U

   ZZ	&5&7 5 5 56&7 6 6 65$5 5s 5rzz 55$5 5s 5rzz 533 36?? 3
*D *$s) * *
# # %UC-. 3 Xd38n5 #   	] 	: :z, ,d38n ,UX ,]abegjbj]k ,^ 
 8     .   >     ,   1"# !"  !"&"  8,*# 	bjj 	RZZ 	' '.?bjj.P(Q '*'rzz 'eOS"**,L&M '*x4 xD x
	
y 	
T 	
B
B'B ZZB"/
/0/ ?/ !d,	/
 2::tCy%S	49(<"=tDzIJ/h -1	 d,	c4i()	 		 -1#c4i()} d4j8?_sww ?_DU" U"p{ {|; !)ZZ	"**bjj
 !#!  !	W$	& 	W)*	,		 3/ 3/lW Wr4   