"docs/vscode:/vscode.git/clone" did not exist on "a52d9c3097404325790ef08777700563faa2f5c0"
Unverified Commit bb39bc99 authored by Weston King-Leatham's avatar Weston King-Leatham Committed by GitHub
Browse files

[python] Add type hints to python-package/lightgbm/plotting.py (#4367)



* Change to f-strings in test_plotting.py

* Implemented type hinting in python-package/lightgbm/plotting.py

* Apply suggestions from code review
Co-authored-by: default avatarJames Lamb <jaylamb20@gmail.com>

* Update python-package/lightgbm/plotting.py
Co-authored-by: default avatarJames Lamb <jaylamb20@gmail.com>

* Delete test_plotting.py

File was mistakenly added to pull request

* Revert "Delete test_plotting.py"

This reverts commit df095b612af3abafcc87df4f95e8b523a49ebde5.

* default argument

* Apply suggestions from code review
Co-authored-by: default avatarJames Lamb <jaylamb20@gmail.com>

* Removed errant bracket

* Update python-package/lightgbm/plotting.py

* Apply suggestions from code review
Co-authored-by: default avatarNikita Titov <nekit94-08@mail.ru>

* Fixing tuples from ints to floats

* Apply suggestions from code review
Co-authored-by: default avatarNikita Titov <nekit94-08@mail.ru>

* Update python-package/lightgbm/plotting.py
Co-authored-by: default avatarNikita Titov <nekit94-08@mail.ru>
Co-authored-by: default avatarJames Lamb <jaylamb20@gmail.com>
Co-authored-by: default avatarNikita Titov <nekit94-08@mail.ru>
parent 45ac271b
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"""Plotting library.""" """Plotting library."""
from copy import deepcopy from copy import deepcopy
from io import BytesIO from io import BytesIO
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np import numpy as np
...@@ -10,24 +11,36 @@ from .compat import GRAPHVIZ_INSTALLED, MATPLOTLIB_INSTALLED ...@@ -10,24 +11,36 @@ from .compat import GRAPHVIZ_INSTALLED, MATPLOTLIB_INSTALLED
from .sklearn import LGBMModel from .sklearn import LGBMModel
def _check_not_tuple_of_2_elements(obj, obj_name='obj'): def _check_not_tuple_of_2_elements(obj: Any, obj_name: str = 'obj') -> None:
"""Check object is not tuple or does not have 2 elements.""" """Check object is not tuple or does not have 2 elements."""
if not isinstance(obj, tuple) or len(obj) != 2: if not isinstance(obj, tuple) or len(obj) != 2:
raise TypeError(f"{obj_name} must be a tuple of 2 elements.") raise TypeError(f"{obj_name} must be a tuple of 2 elements.")
def _float2str(value, precision=None): def _float2str(value: float, precision: Optional[int] = None) -> str:
return (f"{value:.{precision}f}" return (f"{value:.{precision}f}"
if precision is not None and not isinstance(value, str) if precision is not None and not isinstance(value, str)
else str(value)) else str(value))
def plot_importance(booster, ax=None, height=0.2, def plot_importance(
xlim=None, ylim=None, title='Feature importance', booster: Union[Booster, LGBMModel],
xlabel='Feature importance', ylabel='Features', ax=None,
importance_type='split', max_num_features=None, height: float = 0.2,
ignore_zero=True, figsize=None, dpi=None, grid=True, xlim: Optional[Tuple[float, float]] = None,
precision=3, **kwargs): ylim: Optional[Tuple[float, float]] = None,
title: Optional[str] = 'Feature importance',
xlabel: Optional[str] = 'Feature importance',
ylabel: Optional[str] = 'Features',
importance_type: str = 'split',
max_num_features: Optional[int] = None,
ignore_zero: bool = True,
figsize: Optional[Tuple[float, float]] = None,
dpi: Optional[int] = None,
grid: bool = True,
precision: Optional[int] = 3,
**kwargs: Any
) -> Any:
"""Plot model's feature importances. """Plot model's feature importances.
Parameters Parameters
...@@ -138,11 +151,22 @@ def plot_importance(booster, ax=None, height=0.2, ...@@ -138,11 +151,22 @@ def plot_importance(booster, ax=None, height=0.2,
return ax return ax
def plot_split_value_histogram(booster, feature, bins=None, ax=None, width_coef=0.8, def plot_split_value_histogram(
xlim=None, ylim=None, booster: Union[Booster, LGBMModel],
title='Split value histogram for feature with @index/name@ @feature@', feature: Union[int, str],
xlabel='Feature split value', ylabel='Count', bins: Union[int, str, None] = None,
figsize=None, dpi=None, grid=True, **kwargs): ax=None,
width_coef: float = 0.8,
xlim: Optional[Tuple[float, float]] = None,
ylim: Optional[Tuple[float, float]] = None,
title: Optional[str] = 'Split value histogram for feature with @index/name@ @feature@',
xlabel: Optional[str] = 'Feature split value',
ylabel: Optional[str] = 'Count',
figsize: Optional[Tuple[float, float]] = None,
dpi: Optional[int] = None,
grid: bool = True,
**kwargs: Any
) -> Any:
"""Plot split value histogram for the specified feature of the model. """Plot split value histogram for the specified feature of the model.
Parameters Parameters
...@@ -244,11 +268,20 @@ def plot_split_value_histogram(booster, feature, bins=None, ax=None, width_coef= ...@@ -244,11 +268,20 @@ def plot_split_value_histogram(booster, feature, bins=None, ax=None, width_coef=
return ax return ax
def plot_metric(booster, metric=None, dataset_names=None, def plot_metric(
ax=None, xlim=None, ylim=None, booster: Union[Dict, LGBMModel],
title='Metric during training', metric: Optional[str] = None,
xlabel='Iterations', ylabel='auto', dataset_names: Optional[List[str]] = None,
figsize=None, dpi=None, grid=True): ax=None,
xlim: Optional[Tuple[float, float]] = None,
ylim: Optional[Tuple[float, float]] = None,
title: Optional[str] = 'Metric during training',
xlabel: Optional[str] = 'Iterations',
ylabel: Optional[str] = 'auto',
figsize: Optional[Tuple[float, float]] = None,
dpi: Optional[int] = None,
grid: bool = True
) -> Any:
"""Plot one metric during training. """Plot one metric during training.
Parameters Parameters
...@@ -369,8 +402,15 @@ def plot_metric(booster, metric=None, dataset_names=None, ...@@ -369,8 +402,15 @@ def plot_metric(booster, metric=None, dataset_names=None,
return ax return ax
def _to_graphviz(tree_info, show_info, feature_names, precision=3, def _to_graphviz(
orientation='horizontal', constraints=None, **kwargs): tree_info: Dict[str, Any],
show_info: List[str],
feature_names: Union[List[str], None],
precision: Optional[int] = 3,
orientation: str = 'horizontal',
constraints: Optional[List[int]] = None,
**kwargs: Any
) -> Any:
"""Convert specified tree to graphviz instance. """Convert specified tree to graphviz instance.
See: See:
...@@ -465,8 +505,14 @@ def _to_graphviz(tree_info, show_info, feature_names, precision=3, ...@@ -465,8 +505,14 @@ def _to_graphviz(tree_info, show_info, feature_names, precision=3,
return graph return graph
def create_tree_digraph(booster, tree_index=0, show_info=None, precision=3, def create_tree_digraph(
orientation='horizontal', **kwargs): booster: Union[Booster, LGBMModel],
tree_index: int = 0,
show_info: Optional[List[str]] = None,
precision: Optional[int] = 3,
orientation: str = 'horizontal',
**kwargs: Any
) -> Any:
"""Create a digraph representation of specified tree. """Create a digraph representation of specified tree.
Each node in the graph represents a node in the tree. Each node in the graph represents a node in the tree.
...@@ -542,8 +588,17 @@ def create_tree_digraph(booster, tree_index=0, show_info=None, precision=3, ...@@ -542,8 +588,17 @@ def create_tree_digraph(booster, tree_index=0, show_info=None, precision=3,
return graph return graph
def plot_tree(booster, ax=None, tree_index=0, figsize=None, dpi=None, def plot_tree(
show_info=None, precision=3, orientation='horizontal', **kwargs): booster: Union[Booster, LGBMModel],
ax=None,
tree_index: int = 0,
figsize: Optional[Tuple[float, float]] = None,
dpi: Optional[int] = None,
show_info: Optional[List[str]] = None,
precision: Optional[int] = 3,
orientation: str = 'horizontal',
**kwargs: Any
) -> Any:
"""Plot specified tree. """Plot specified tree.
Each node in the graph represents a node in the tree. Each node in the graph represents a node in the tree.
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment