[ci] [python-package] enforce 'pylint' checks (fixes #4308) (#6334)

This commit is contained in:
James Lamb 2024-02-23 23:07:03 -06:00 коммит произвёл GitHub
Родитель 776c5c3c49
Коммит 6f19edde52
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
4 изменённых файлов: 34 добавлений и 11 удалений

Просмотреть файл

@ -1215,7 +1215,7 @@ class _InnerPredictor:
)
if pred_leaf:
preds = preds.astype(np.int32)
is_sparse = isinstance(preds, scipy.sparse.spmatrix) or isinstance(preds, list)
is_sparse = isinstance(preds, (list, scipy.sparse.spmatrix))
if not is_sparse and preds.size != nrow:
if preds.size % nrow == 0:
preds = preds.reshape(nrow, -1)
@ -2681,7 +2681,10 @@ class Dataset:
'In multiclass classification init_score can also be a list of lists, numpy 2-D array or pandas DataFrame.'
)
else:
dtype = np.int32 if (field_name == 'group' or field_name == 'position') else np.float32
if field_name in {'group', 'position'}:
dtype = np.int32
else:
dtype = np.float32
data = _list_to_1d_numpy(data, dtype=dtype, name=field_name)
ptr_data: Union[_ctypes_float_ptr, _ctypes_int_ptr]
@ -3106,7 +3109,7 @@ class Dataset:
if self._need_slice and self.used_indices is not None and self.reference is not None:
self.data = self.reference.data
if self.data is not None:
if isinstance(self.data, np.ndarray) or isinstance(self.data, scipy.sparse.spmatrix):
if isinstance(self.data, (np.ndarray, scipy.sparse.spmatrix)):
self.data = self.data[self.used_indices, :]
elif isinstance(self.data, pd_DataFrame):
self.data = self.data.iloc[self.used_indices].copy()
@ -3284,7 +3287,7 @@ class Dataset:
self.data = None
elif isinstance(self.data, scipy.sparse.spmatrix):
sparse_format = self.data.getformat()
if isinstance(other.data, np.ndarray) or isinstance(other.data, scipy.sparse.spmatrix):
if isinstance(other.data, (np.ndarray, scipy.sparse.spmatrix)):
self.data = scipy.sparse.hstack((self.data, other.data), format=sparse_format)
elif isinstance(other.data, pd_DataFrame):
self.data = scipy.sparse.hstack((self.data, other.data.values), format=sparse_format)

Просмотреть файл

@ -393,8 +393,8 @@ def plot_metric(
for name in dataset_names_iter:
metrics_for_one = eval_results[name]
results = metrics_for_one[metric]
max_result = max(max(results), max_result)
min_result = min(min(results), min_result)
max_result = max(*results, max_result)
min_result = min(*results, min_result)
ax.plot(x_, results, label=name)
ax.legend(loc='best')
@ -804,7 +804,7 @@ def plot_tree(
The plot with single tree.
"""
if MATPLOTLIB_INSTALLED:
import matplotlib.image as image
import matplotlib.image
import matplotlib.pyplot as plt
else:
raise ImportError('You must install matplotlib and restart your session to plot tree.')
@ -821,7 +821,7 @@ def plot_tree(
s = BytesIO()
s.write(graph.pipe(format='png'))
s.seek(0)
img = image.imread(s)
img = matplotlib.image.imread(s)
ax.imshow(img)
ax.axis('off')

Просмотреть файл

@ -125,7 +125,21 @@ ignore = [
# (pydocstyle) Missing docstring in magic method
"D105",
# (pycodestyle) Line too long
"E501"
"E501",
# (pylint) Too many branches
"PLR0912",
# (pylint) Too many arguments in function definition
"PLR0913",
# (pylint) Too many statements
"PLR0915",
# (pylint) Consider merging multiple comparisons
"PLR1714",
# (pylint) Magic value used in comparison
"PLR2004",
# (pylint) for loop veriable overwritten by assignment target
"PLW2901",
# (pylint) use 'elif' instead of 'else' then 'if', to reduce indentation
"PLR5501"
]
select = [
# flake8-bugbear
@ -138,6 +152,8 @@ select = [
"E",
# pyflakes
"F",
# pylint
"PL",
# flake8-return: unnecessary assignment before return
"RET504",
# flake8-simplify: use dict.get() instead of an if-else block
@ -159,6 +175,10 @@ select = [
# flake8-print
"T"
]
"python-package/lightgbm/basic.py" = [
# (pylint) Using the global statement is discouraged
"PLW0603"
]
"tests/*" = [
# (flake8-bugbear) Found useless expression
"B018",

Просмотреть файл

@ -79,7 +79,7 @@ class DistributedMockup:
"""Start the training process on the `i`-th worker."""
config_path = TESTS_DIR / f"train{i}.conf"
cmd = [self.executable, f"config={config_path}"]
return subprocess.run(cmd)
return subprocess.run(cmd, check=True)
def _set_ports(self) -> None:
"""Randomly assign a port for training to each worker and save all ports to mlist.txt."""
@ -145,7 +145,7 @@ class DistributedMockup:
with open(config_path, "wt") as file:
_write_dict(self.predict_config, file)
cmd = [self.executable, f"config={config_path}"]
result = subprocess.run(cmd)
result = subprocess.run(cmd, check=True)
if result.returncode != 0:
raise RuntimeError("Error in prediction")
return np.loadtxt(str(TESTS_DIR / "predictions.txt"))