`L indZddlmZddlmZddlmZddlZddl m Z ddl m Z m Z mZmZdd lmZmZd d lmZmZmZmZd d lmZmZd ZGddZeZeeege eddddgddggdehdgdgdgdgdgdge eddddgde eddddgd dddddddddddddd dZGdd ZGd!d"eZ Gd#d$eZ!eid%dd&e"de d'gd(e eddddgd)ddgd*gdd+ehdgd,dgd-dgd.dgd/dgd0dgd1dgd2dgd3dgd4e eddddgd5e"gd d>dddddddddddddd6d7d8Z#d9Z$eeegddgddge eddddge ed dddge eddddgdgd:dddd;dddd<d=Z%y)?z: This module defines export functions for decision trees. )Iterable)StringIO)IntegralN) is_classifier) HasMethodsInterval StrOptionsvalidate_params) check_arraycheck_is_fitted)DecisionTreeClassifierDecisionTreeRegressor _criterion_tree)Treebuchheimc g}d\}}||z}||z }tjddd|z jtD]}|dz }|dt |dzdz z z}||df||dfd||fd||f|d|f|d|f||dfg} | t|\} } } td | |zztd | |zztd | |zzg} |j | |S) a Generate n colors with equally spaced hues. Parameters ---------- n : int The number of colors required. Returns ------- color_list : list, length n List of n tuples of form (R, G, B) being the components of each color. )g?g?igv@gN@rrr)nparangeastypeintabsappend) n color_listsvcmhh_barxrgbrgbs Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/tree/_export.py _color_brewr,sJ DAq AA AA YYr3 * 1 1# 6D S%!)q)) *1I 1I 1I 1I 1I 1I 1I c%j/1aC1q5M"c#Q-&8Cq1u allnonerootr: no_validation) decision_tree max_depth feature_names class_nameslabelfilledimpuritynode_ids proportionrounded precisionaxfontsizeT)prefer_skip_nested_validationr;F) r@rArBrCrDrErFrGrHrIrJrKc jt|t||||||||| | |  } | j|| S)a[ Plot a decision tree. The sample counts that are shown are weighted with any sample_weights that might be present. The visualization is fit automatically to the size of the axis. Use the ``figsize`` or ``dpi`` arguments of ``plt.figure`` to control the size of the rendering. Read more in the :ref:`User Guide `. .. versionadded:: 0.21 Parameters ---------- decision_tree : decision tree regressor or classifier The decision tree to be plotted. max_depth : int, default=None The maximum depth of the representation. If None, the tree is fully generated. feature_names : array-like of str, default=None Names of each of the features. If None, generic names will be used ("x[0]", "x[1]", ...). class_names : array-like of str or True, default=None Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If ``True``, shows a symbolic representation of the class name. label : {'all', 'root', 'none'}, default='all' Whether to show informative labels for impurity, etc. Options include 'all' to show at every node, 'root' to show only at the top root node, or 'none' to not show at any node. filled : bool, default=False When set to ``True``, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output. impurity : bool, default=True When set to ``True``, show the impurity at each node. node_ids : bool, default=False When set to ``True``, show the ID number on each node. proportion : bool, default=False When set to ``True``, change the display of 'values' and/or 'samples' to be proportions and percentages respectively. rounded : bool, default=False When set to ``True``, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman. precision : int, default=3 Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node. ax : matplotlib axis, default=None Axes to plot to. If None, use current axis. Any previous content is cleared. fontsize : int, default=None Size of text font. If None, determined automatically to fit figure. Returns ------- annotations : list of artists List containing the artists for the annotation boxes making up the tree. Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn import tree >>> clf = tree.DecisionTreeClassifier(random_state=0) >>> iris = load_iris() >>> clf = clf.fit(iris.data, iris.target) >>> tree.plot_tree(clf) [...] r@rArBrCrDrErFrGrHrIrK)rJ)r _MPLTreeExporterexport)r?r@rArBrCrDrErFrGrHrIrJrKexporters r+ plot_treerSGsMnM"# H ??=R? 00r-cBeZdZ ddZdZdZdZdZy)_BaseTreeExporterNc ||_||_||_||_||_||_||_||_| |_| |_ | |_ yNrO) r2r@rArBrCrDrErFrGrHrIrKs r+__init__z_BaseTreeExporter.__init__sS#*&      $ "  r-c |jdat|jdtj|}t |d}t |dk(rd}nk|d|dz d|dz z }nVt|jdd}||jddz |jdd|jddz z }|Dcgc]#}t t||zd|z dzzd%}}d t|zScc}w) Nboundsr'T)reversergrrz #%2x%2x%2x) colorslistrargmaxsortedlenrroundtuple)r2valuecolor sorted_valuesalphar"s r+ get_colorz_BaseTreeExporter.get_colors ;;x (U+BIIe,<=>E"5$7M=!Q&&q)M!,<<]STEUAUVU+A./ET[[2155 H%a(4;;x+@+CCEHMM!U519E S'88!<=MMeEl**Ns (DcDd|jvr t|jd|jd<|jdk7rNt j |j  t j|j  f|jd<n|jddk(rvtt j|jdk7rKt j|jt j |jf|jd<|jdk(rX|j|dddf}|jddk(r@t|tr0|jd!|j}n|j | }|j|S)Nr'rrrZ)r\r, n_classes n_outputsrmaxrEminr`uniquerc isinstanceritemrg)r2treenode_idnode_vals r+get_fill_colorz _BaseTreeExporter.get_fill_colors>  #!,T^^A->!?DKK ~~"+-&&*?)?"&&BWAW(X H%"a'C $**0E,F!,K)+ );RVVDJJ=O(P H% >>Q zz'*1a40Hq!Q&x2KK)5$==? g..H~~h''r-c  |jdk(r|j|dddf}n|j|}|jdk(xr|dk(xs|jdk(}|j}|d}|jr!|r|dz }||dt |z|dzz }|j |tjk7r|j.|j|j|}|j|}nd|d|j||d }||d |d d t|j||j|dz }|jrt!|t"j$rd }n4t!|t"j&s|d k(rd }nt!|t sd}|r|d|zz }|t t|j||j|dzz }|r|dz }|j(rMd|j*|zt-|j*dz } |t t| ddz|dzz }n!|t |j*||dzz }|j(s$|j.ddk7r||j0|z}|r|dz }|j.ddk(r!t3j4||j} n|j(r!t3j4||j} nst3j6t3j8t3j:|ddr|j=t>} n t3j4||j} t | j=djAdd} | jAddjAdd} |j.ddk(r1|jdk(r"| jAddjAdd} | jAd|d} || |dzz }|jB|j.ddk7r|jdk(rp|r|dz }|jBdur4|jBt3jD|} |j| } n"d|dt3jD||d } || z }|jG|dr|dtI|d }||d zS)!Nrrr=r;znode r&r rM friedman_mse squared_errorrEz%s = z samples = gY@%zvalue = S32zb''z' ', []z zclass = Ty)%rjrcrC charactersrFstr children_leftr TREE_LEAFrAfeature str_escapera thresholdrIrErnr FriedmanMSEMSErGn_node_samplesfloatriweighted_n_node_samplesraroundr;equalmodrrreplacerBr^endswithr`) r2rprq criterionrclabelsr node_stringrpercent value_text class_names r+ node_to_strz_BaseTreeExporter.node_to_strs >>Q JJw'1-EJJw'E**&77a<ODJJ%1  K ==)Z%;%;<* Iz~~6):V+  3/& w22 E$--0$..ABZPQ]R K  < 'K ??++G44uT=P=PQR=S7TT  3uWa01C7*Q-G GK 3t227;>!#4#9D88AAE  : %K >>!  !5$..9J __5$..9J VVBHHRVVE1-q1 2c*J5$..9J**512::4E ''t4<>!  !dnn&9#++C4<? !__Z8 , qMIIe$qM : %K    1 .%&;Z]);(;q+fr-rUc^eZdZeddddddddddddddffd ZdZd Zd Zd d Zd Z xZ S)_DOTTreeExporterNr;FTrM helveticac t|||||||| | | | ||_||_| |_||_| |_| r gd|_n gd|_dgi|_ddi|_ y)N r@rArBrCrDrErFrGrHrI)z#zzz≤z
><)#rr<=z\n"rleavesrZ) superrXleaves_parallelout_filespecial_charactersfontnamerotaterranksr\)r2rr@rArBrCrDrrErFrGrrHrrIr __class__s r+rXz_DOTTreeExporter.__init__s$ '#!   /  "4    UDODDO^ & r-c|jOt|j|jk7r-tdt|j|jfz|j t |t jr|j|ddn(|j|jd|j|jy)NzALength of feature_names, %d does not match number of features, %drrEr) rAr`n_features_in_ ValueErrorheadrnrrrecursetree_rtail)r2r?s r+rQz_DOTTreeExporter.exports    )4%%&-*F*FF W4--. 0L0LMN mUZZ 0 LLZL @ LL,,a=;R;RL S r-c |jr^t|jD]F}|jj ddj d|j|DzdzH|jj dy)Nz {rank=same ; z; c3 K|]}|ywrWr1).0r(s r+ z(_DOTTreeExporter.tail..s/La/Ls z} ; })rr_rrwritejoin)r2ranks r+rz_DOTTreeExporter.tailsn   tzz*  ###dii/L4::d;K/L&LLwV  C r-c|jjd|jjdg}|jr|jd|jr|jdt |dkDr-|jjddj |z|jjd|jz|jjd |jr|jjd |jjd |jz|jr|jjd yy) Nzdigraph Tree { znode [shape=boxrDrHrz, style="%s", color="black"r}z, fontname="%s"] ; z,graph [ranksep=equally, splines=polyline] ; zedge [fontname="%s"] ; z rankdir=LR ; ) rrrDrrHr`rrrr)r2rounded_filleds r+rz_DOTTreeExporter.heads ./ -. ;;  ! !( + <<  ! !) , ~  " MM  - .0II  - => G$    MM   O P 6FG ;; MM   0 1 r-c |tjk(rtdtjz|j|}|j|}|j ||j krA|tjk(r(|j djt|njt||j vr#t|g|j t|<n0|j t|jt||jjd||j|||fz|jr.|jjd|j||z|jjd||jjd||fz|dk(rtjdd g|j d z d zz}|jjd |d k(r"|jjd|dzn!|jjd|d z|jjd|tjk7r3|j#|||||d z|j#|||||d zyy|j djt||jjd|z|jr|jjd|jjd|z|!|jjd||fzyy)NzInvalid node_id %srz %d [label=%sz, fillcolor="%s"rz%d -> %dr-i?z [labeldistance=2.5, labelangle=rz%d, headlabel="True"]z%d, headlabel="False"]z ; )rparentdepthz%d [label="(...)"z, fillcolor="#C0C0C0"z %d -> %d ; )rrrrchildren_rightr@rrrrrrrDrsrarrayrr) r2rprqrrr left_child right_childangless r+rz_DOTTreeExporter.recurses eoo %1EOOCD D''0 ))'2  >> !Udnn%<U__, 8$++CL9U4::-*-g, 3u:& 3u:&--c'l; MM  '4+;+;D'9+U!VV {{ ##&)<){{ ##$;< MM  ' 1 2! ##Nfg5F$FG"r-c&|jddS)Nrz\")rrs r+rz_DOTTreeExporter.str_escapeCs~~c5))r-)Nr) r4r5r6SENTINELrXrQrrrr __classcell__rs@r+rrsT !-'^(!26CHJ*r-rcNeZdZ dfd ZddZddZddZxZS)rPc t |||||||||| |  | |_dgi|_ddi|_gd|_t |_|jrd|jd<t d|_ y) NrrrZ)rrrr r~r~raboxstylez<-) arrowstyle) rrXrKrr\rdict bbox_argsrH arrow_args) r2r@rArBrCrDrErFrGrHrIrKrs r+rXz_MPLTreeExporter.__init__Is '#!  ! ^ & = <<)0DNN: &$/r-ch|j|||}|j|tjk7rf|j||jkrK|j |j||||dz|j |j ||||dzg}n t||St||g|S)Nrrr)rrrrr@ _make_treerr)r2rqetrrnamechildrens r+rz_MPLTreeExporter._make_treeqsGyA  G $ 7 NN "et~~&=$$W-r9EAI %%g.IUQY  Hg& &D'-H--r-c>ddlm}ddlm}||j }|j |j |jd|j|j}t|}|jdz\}}|jj} |jj} | |z } | |z } |j||j||||j!D cgc]} t#| |s| }} |j$j&j)}|D]} | j+||j,|D cgc]$} | j/x}|j&}} t1|Dcgc]}|jc}}t1|Dcgc]}|jc}}|dj3t5| |z | |z z}|D]} | j7||Scc} wcc} wcc}wcc}w)Nr) Annotationr)matplotlib.pyplotpyplotmatplotlib.textrgcaclear set_axis_offrrrr max_extentsget_window_extentwidthheightr get_childrenrnfigurecanvas get_rendererupdate_bbox_position_sizerKget_bbox_patchrk get_fontsizerl set_fontsize)r2r?rJpltrmy_tree draw_treemax_xmax_yax_width ax_heightscale_xscale_yannannsrenderer bbox_patchextentsextent max_width max_heightsizes r+rQz_MPLTreeExporter.exports'. :B   //!]%8%8-:Q:QRW% !,,.2 u'')//((*11 U"e# Y 3 3RF!0PJsJ4OPP99##002 4C  ) )( 3 4 ==  "%"4"4"66JC,,.G @fV\\@AI'BfmmBCJ7'')C)#Wz%9-D '  & ' 5Q ABs6H H )HH1Hc Tddlm}tdd|zz d}|j|j|d<tddd|jj |j j d|} |jd | d d <|jd z|z ||jz d z |z f} |j||jkr|jr-|j||jj| d d<n|j| d d<|j )|j"|jj$| fi| n|j jd z|z ||j jz d z |z f} |j"|jj$| | fi| |j j Z| d| dzdz | d| dzdz f} |j j'|k(rd\} }nd\} }|j"| | fd|i||j(D]}|j+||||||dzy|j jd z|z ||j jz d z |z f} d| d d<|j"d| | fi| y)Nrd z axes fraction)zorderxycoordsrKcenter)havabbox arrowpropsz text.colorr edgecolorrrfcrr)zTrue right)z Falser7rrgreyz (...) r1)rrrrKrcopyrrcParamsr&rr@rDrsrprq get_facecolorrannotaterCr7rr)r2noderprJrrrr common_kwargskwargsxy xy_parenttext_pos label_textlabel_hachilds r+rz_MPLTreeExporter.recurses'e#$  == $(, M* % $$&++-    -0LL,F|[)vv|u$utvv~';u&D E >> !Udnn%<{{'+':':4ARAR'Svt$')'7'7'9vt${{" DIIOOR:6:[[]]S(E1T[[]]*S0E9  DIIOOYEfE;;%%-#11-2"11-2 H {{'')T1/B, H/B, HBKK HSS]S M UD"eU%!) L M $-&,5I$*F6N4 BKKB A& Ar-r)rrW)r4r5r6rXrrQrrrs@r+rPrPHs=&0P.&1f?Br-rPr?rrr@rArBrCrDrrErFrGrrHrrIrr)r@rArBrCrDrrErFrGrrHrrIrc|t|ddd}|t|tst|ddd}t|d}d} t|trt |dd}d}| d}t }t||||||||| | | | | || }|j||r-|jj|r|jSS |r|jyy#|r|jwwxYw) a Export a decision tree in DOT format. This function generates a GraphViz representation of the decision tree, which is then written into `out_file`. Once exported, graphical renderings can be generated using, for example:: $ dot -Tps tree.dot -o tree.ps (PostScript format) $ dot -Tpng tree.dot -o tree.png (PNG format) The sample counts that are shown are weighted with any sample_weights that might be present. Read more in the :ref:`User Guide `. Parameters ---------- decision_tree : object The decision tree estimator to be exported to GraphViz. out_file : object or str, default=None Handle or name of the output file. If ``None``, the result is returned as a string. .. versionchanged:: 0.20 Default of out_file changed from "tree.dot" to None. max_depth : int, default=None The maximum depth of the representation. If None, the tree is fully generated. feature_names : array-like of shape (n_features,), default=None An array containing the feature names. If None, generic names will be used ("x[0]", "x[1]", ...). class_names : array-like of shape (n_classes,) or bool, default=None Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If ``True``, shows a symbolic representation of the class name. label : {'all', 'root', 'none'}, default='all' Whether to show informative labels for impurity, etc. Options include 'all' to show at every node, 'root' to show only at the top root node, or 'none' to not show at any node. filled : bool, default=False When set to ``True``, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output. leaves_parallel : bool, default=False When set to ``True``, draw all leaf nodes at the bottom of the tree. impurity : bool, default=True When set to ``True``, show the impurity at each node. node_ids : bool, default=False When set to ``True``, show the ID number on each node. proportion : bool, default=False When set to ``True``, change the display of 'values' and/or 'samples' to be proportions and percentages respectively. rotate : bool, default=False When set to ``True``, orient tree left to right rather than top-down. rounded : bool, default=False When set to ``True``, draw node boxes with rounded corners. special_characters : bool, default=False When set to ``False``, ignore special characters for PostScript compatibility. precision : int, default=3 Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node. fontname : str, default='helvetica' Name of font used to render text. Returns ------- dot_data : str String representation of the input tree in GraphViz dot format. Only returned if ``out_file`` is None. .. versionadded:: 0.18 Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn import tree >>> clf = tree.DecisionTreeClassifier() >>> iris = load_iris() >>> clf = clf.fit(iris.data, iris.target) >>> tree.export_graphviz(clf) 'digraph Tree {... NFr ensure_2ddtypeensure_min_sampleswzutf-8)encodingT)rr@rArBrCrDrrErFrGrrHrrIr) r rnboolr ropenrrrQrgetvalueclose)r?rr@rArBrCrDrrErFrGrrHrrIrown_file return_stringrRs r+export_graphvizr0s$V # U$1 z+t'D! 5 M"HM! h $HcG.compute_depth_sk =/!\*|, 2:%2+ ma'  }q(-  &:r-r)rrrk)rprr5r6s @r+_compute_depthr7s5 F4D..0C0CVL v;r-)r?rArBr@spacingdecimals show_weightsr )rArBr@r8r9r:c ` |t|ddd}tdddtj tr^ jnOt t jk7r.t dt dt jdd d d |;t | jk7r#t d jt |fzttrd sd nd|3 jDcgc]}|tjk7r||ndc} n) jDcgc]}dj|c} dt_fd   f d  ddtjScc}wcc}w)a9 Build a text report showing the rules of a decision tree. Note that backwards compatibility may not be supported. Parameters ---------- decision_tree : object The decision tree estimator to be exported. It can be an instance of DecisionTreeClassifier or DecisionTreeRegressor. feature_names : array-like of shape (n_features,), default=None An array containing the feature names. If None generic names will be used ("feature_0", "feature_1", ...). class_names : array-like of shape (n_classes,), default=None Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. - if `None`, the class names are delegated to `decision_tree.classes_`; - otherwise, `class_names` will be used as class names instead of `decision_tree.classes_`. The length of `class_names` must match the length of `decision_tree.classes_`. .. versionadded:: 1.3 max_depth : int, default=10 Only the first max_depth levels of the tree are exported. Truncated branches will be marked with "...". spacing : int, default=3 Number of spaces between edges. The higher it is, the wider the result. decimals : int, default=2 Number of decimal digits to display. show_weights : bool, default=False If true the classification weights will be exported on each leaf. The classification weights are the number of samples each class. Returns ------- report : str Text summary of all the rules in the decision tree. Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn.tree import DecisionTreeClassifier >>> from sklearn.tree import export_text >>> iris = load_iris() >>> X = iris['data'] >>> y = iris['target'] >>> decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2) >>> decision_tree = decision_tree.fit(X, y) >>> r = export_text(decision_tree, feature_names=iris['feature_names']) >>> print(r) |--- petal width (cm) <= 0.80 | |--- class: 0 |--- petal width (cm) > 0.80 | |--- petal width (cm) <= 1.75 | | |--- class: 1 | |--- petal width (cm) > 1.75 | | |--- class: 2 NFrr$zaWhen `class_names` is an array, it should contain as many items as `decision_tree.classes_`. Got z while the tree was fitted with z classes.z {} {} <= {} z {} {} > {} z{} {} z.feature_names must contain %d elements, got %dz{}{} weights: {} z{}{}{} z{}{} value: {} z feature_{}r~cd}ttrRr>|Dcgc]}dj||z}}ddj|ddzdz}||dt |zz }n9|Dcgc]}dj|}}ddj|ddzdz}t xj j|d|z c_ycc}wcc}w)Nr~z {1:.{0}f}, rrrz class: )rnrformatrr export_textreport) rcrrindentvalr!r9r?r: value_fmts r+ _add_leafzexport_text.._add_leafTs m%; <#"((17N3NOBGGCL"--3' :J/ /C>CD=''!4DCD Sb))C/Ci..vr3??Es C *Cc ddzz|z}|d dzz}d}jdk(rj|d}nj|jd}tj|}j ddk7rjdk(r|}j |}|dzkrd}|}|}j|tjk7r߉|} j|} dj| } txjj|| | z c_ txj|z c_ j||dztxjj|| | z c_ txj|z c_ j||dzy ||||yt!|} | dk(r  ||||yd| z} txjj|| z c_ y) N|rw-rrr~z {1:.{0}f}ztruncated branch of depth %d)rjrcTrr^rirrrTREE_UNDEFINEDrr=r>r?rrr7)rrr@rcrrinfo_fmt info_fmt_leftinfo_fmt_rightrr subtree_depth trunc_reportrCrBr9feature_names_left_child_fmtr@print_tree_recurseright_child_fmtr8rtruncation_fmts r+rPz'export_text..print_tree_recursedsw'50 '"S7]2 ??a KK%a(EKK%''*EYYu% ??1  "u!';$Z0J"'"?"?"E IM !H$M%N}}T"e&:&::%d+!OOD1 '..xC ""o&<&r?)r?rArBr@r8r9r:irCrNrOrPrQrrRrBs` ````` @@@@@@@@r+r>r>sp # U$1 ! 5 M"   E]#  '00K  ]%;%;!< < $%& ../0 ;  &O$NN S%75;K;K%K <]!34 5  -!78( "I&  ]] !"U%9%9 9M! t C  ;@--HQ,--a0HK@ (R(RTq!   I Is !F&F+rW)&__doc__collections.abcriornumbersrnumpyrbaserutils._param_validationrr r r utils.validationr r r~rrrr_reingold_tilfordrrr,r/rrSrUrrPrr0r7r>r1r-r+r_s1% WW;NN-'T :02GHxD@$G&-6456+KK k;xD@$Gh4?F#'!*      t1%$t1nCCLo*(o*dnB(nBbS$ 7 34 hxD@$G ,-  6  *456  9+ I; YK YK yk 9+ I; yk hxD@$G SE!$#''.c       #c+*cL002GH&-$d+xD@$GXq$v>Eh4?F" #'  w wr-