Coverage for tests/test_compatibility.py: 100%

194 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-02 00:41 +0000

1"""Tests that `LogitEncoder` is a drop-in for `category_encoders`' encoders. 

2 

3Also tests edge cases and the input checks of `logit_encode.utils`. 

4""" 

5 

6from __future__ import annotations 

7 

8import inspect 

9import pickle 

10import warnings 

11from collections.abc import Callable 

12from typing import Any 

13 

14import category_encoders as ce 

15import numpy as np 

16import pandas as pd 

17import pytest 

18from scipy import sparse 

19 

20from logit_encode import LogitEncoder, _logit_models 

21 

22 

23def make_data(n_rows: int = 400, seed: int = 0) -> tuple[pd.DataFrame, pd.Series]: 

24 """Makes data with every kind of column that encoders meet. 

25 

26 Args: 

27 n_rows: number of rows. 

28 seed: random seed. 

29 

30 Returns: 

31 The features (object, categorical, boolean, numeric, rare-category, 

32 and constant columns) and a binary outcome. 

33 

34 """ 

35 rng = np.random.default_rng(seed) 

36 X = pd.DataFrame({ 

37 'color': rng.choice(['red', 'blue', 'green', 'gold'], n_rows), 

38 'size': pd.Categorical(rng.choice(['S', 'M', 'L'], n_rows)), 

39 'flag': rng.choice([True, False], n_rows), 

40 'price': rng.normal(size = n_rows), 

41 'rare': rng.choice(['a'] * 50 + ['b', 'c', 'd'], n_rows), 

42 'constant': 'same'}) 

43 X.loc[::17, 'color'] = np.nan 

44 return X, pd.Series(rng.binomial(1, 0.4, n_rows)) 

45 

46 

47def outcome(make: Callable[[], Any], fit: tuple, data: Any) -> tuple: 

48 """Fits an encoder and summarizes its output, or the error it raised. 

49 

50 Args: 

51 make: makes the encoder. 

52 fit: arguments to `fit`. 

53 data: data to transform. 

54 

55 Returns: 

56 The output's type, columns (or shape), and feature names, or the 

57 error's type. 

58 

59 """ 

60 with warnings.catch_warnings(): 

61 warnings.simplefilter('ignore') 

62 try: 

63 encoder = make().fit(*fit) 

64 output = encoder.transform(data) 

65 except (ValueError, TypeError, KeyError) as error: 

66 return ('error', type(error).__name__) 

67 columns = list(output.columns) if hasattr(output, 'columns') else None 

68 return ( 

69 type(output).__name__, 

70 columns, 

71 np.shape(output), 

72 [str(name) for name in encoder.get_feature_names_out()]) 

73 

74 

75X, Y = make_data() 

76NEW = X.head(5).copy() 

77NEW.loc[0, 'color'] = 'purple' 

78SCENARIOS: dict[str, tuple[dict[str, Any], tuple, Any]] = { 

79 'default columns': ({}, (X, Y), X), 

80 'explicit columns': ({'cols': ['color', 'rare']}, (X, Y), X), 

81 'array output': ({'cols': ['color'], 'return_df': False}, (X, Y), X), 

82 'series input': ({}, (X['color'], Y), X['color']), 

83 'list input': ( 

84 {'cols': [0]}, (X[['color', 'price']].to_numpy().tolist(), Y), 

85 X[['color', 'price']].to_numpy().tolist()), 

86 'flat list input': ({'cols': [0]}, (X['color'].tolist(), Y), 

87 X['color'].tolist()), 

88 'array input': ({'cols': [0]}, (X[['color', 'price']].to_numpy(), Y), 

89 X[['color', 'price']].to_numpy()), 

90 'extra columns': ({'cols': ['color']}, (X[['color', 'price']], Y), 

91 X[['color', 'flag', 'price']]), 

92 'array after frame': ({'cols': ['color']}, (X[['color', 'price']], Y), 

93 X[['color', 'price']].to_numpy()), 

94 'missing column': ({'cols': ['color']}, (X[['color', 'price']], Y), 

95 X[['price']]), 

96 'missing cols column': ({'cols': ['nothing']}, (X, Y), X), 

97 'drop invariant': ({'drop_invariant': True}, (X, Y), X), 

98 'composite': ({'composite_cols': [('color', 'rare')]}, (X, Y), X), 

99 'composite kept': ({'composite_cols': [('color', 'rare')], 

100 'keep_components': True}, (X, Y), X), 

101 'min group size': ({'cols': ['rare'], 'min_group_size': 20}, (X, Y), X), 

102 'min group share': ({'cols': ['rare'], 'min_group_size': 0.05, 

103 'min_group_name': 'other'}, (X, Y), X)} 

104for handle in ('value', 'return_nan', 'error', -1.5): 

105 SCENARIOS[f'handle_unknown={handle}'] = ( 

106 {'cols': ['color'], 'handle_unknown': handle}, (X, Y), NEW) 

107 SCENARIOS[f'handle_missing={handle}'] = ( 

108 {'cols': ['color'], 'handle_missing': handle}, (X, Y), NEW) 

109 

110 

111""" Drop-in Compatibility """ 

112 

113 

114@pytest.mark.parametrize('name', list(SCENARIOS)) 

115def test_same_output_as_category_encoders(name: str) -> None: 

116 """Outputs have the same type, columns, and names as TargetEncoder's.""" 

117 kwargs, fit, data = SCENARIOS[name] 

118 expected = outcome(lambda: ce.TargetEncoder(**kwargs), fit, data) 

119 actual = outcome(lambda: LogitEncoder(**kwargs), fit, data) 

120 assert actual == expected 

121 

122 

123def test_shared_parameters_in_the_same_order() -> None: 

124 """Parameters shared with TargetEncoder come in the same order.""" 

125 target = list(inspect.signature(ce.TargetEncoder).parameters) 

126 logit = list(inspect.signature(LogitEncoder).parameters) 

127 shared = [name for name in target if name in logit] 

128 assert [name for name in logit if name in shared] == shared 

129 specific = {'min_samples_leaf', 'smoothing', 'hierarchy'} 

130 assert set(target) - set(logit) == specific 

131 

132 

133def test_positional_parameters() -> None: 

134 """The shared parameters can be passed by position.""" 

135 encoder = LogitEncoder(1, ['color'], True, False, 'return_nan', 'error') 

136 assert encoder.get_params()['cols'] == ['color'] 

137 assert encoder.handle_missing == 'return_nan' 

138 assert encoder.handle_unknown == 'error' 

139 

140 

141def test_category_encoders_attributes() -> None: 

142 """Attributes and methods that category_encoders code uses exist.""" 

143 encoder = LogitEncoder(cols = ['color'], drop_invariant = True).fit(X, Y) 

144 assert encoder.mapping is encoder.mapping_ 

145 assert encoder.ordinal_encoder is encoder.ordinal_encoder_ 

146 assert encoder.invariant_cols is encoder.invariant_cols_ 

147 assert list(encoder.feature_names_out_) == list( 

148 encoder.get_feature_names_out()) 

149 assert list(encoder.get_feature_names_in()) == list(X.columns) 

150 with pytest.warns(FutureWarning, match = 'deprecated'): 

151 names = encoder.get_feature_names() 

152 assert list(names) == list(encoder.get_feature_names_out()) 

153 data = LogitEncoder(cols = ['color'], return_df = False).fit(X, Y) 

154 assert isinstance(data.transform(X, override_return_df = True), 

155 pd.DataFrame) 

156 

157 

158def test_lumping_matches_category_encoders() -> None: 

159 """`min_group_size` lumps the same categories as category_encoders.""" 

160 for size, name, combine in ((20, None, None), (0.05, 'other', 'force'), 

161 (20, 'x', False)): 

162 options = { 

163 'cols': ['rare'], 'min_group_size': size, 

164 'min_group_name': name, 'combine_min_nan_groups': combine} 

165 ours = LogitEncoder(**options).fit(X, Y) 

166 theirs = ce.TargetEncoder(**options).fit(X, Y) 

167 assert ours.min_group_lumping_ == theirs.min_group_lumping_ 

168 

169 

170def test_extra_columns_keep_their_place() -> None: 

171 """Extra transform columns pass through where they were in the input.""" 

172 encoder = LogitEncoder(cols = ['color']).fit(X[['color', 'price']], Y) 

173 output = encoder.transform(X[['color', 'flag', 'price']]) 

174 assert list(output.columns) == ['color', 'flag', 'price'] 

175 assert output['flag'].equals(X['flag']) 

176 with pytest.raises(ValueError, match = 'same order|feature names'): 

177 encoder.transform(X[['price', 'color', 'flag']]) 

178 

179 

180def test_default_columns_skip_booleans() -> None: 

181 """As in category_encoders, booleans are not encoded by default.""" 

182 encoder = LogitEncoder().fit(X, Y) 

183 assert encoder.cols_ == ['color', 'size', 'rare', 'constant'] 

184 

185 

186def test_passthrough_columns_keep_their_dtype() -> None: 

187 """Columns that are not encoded keep their dtype, such as 'category'.""" 

188 output = LogitEncoder(cols = ['color']).fit(X, Y).transform(X) 

189 assert isinstance(output['size'].dtype, pd.CategoricalDtype) 

190 assert output['flag'].dtype == bool 

191 

192 

193def test_pickle_round_trip() -> None: 

194 """A fitted encoder survives pickling.""" 

195 encoder = LogitEncoder(cols = ['color'], return_uncertainty = True) 

196 encoder.fit(X, Y) 

197 copy = pickle.loads(pickle.dumps(encoder)) # noqa: S301 

198 pd.testing.assert_frame_equal(copy.transform(X), encoder.transform(X)) 

199 

200 

201def test_composite_ambiguity_raises() -> None: 

202 """A '|' in the data that makes combinations collide raises an error.""" 

203 data = pd.DataFrame({'a': ['x|y', 'x', 'p'] * 20, 'b': ['z', 'y|z', 'q'] * 20}) 

204 with pytest.raises(ValueError, match = 'ambiguous'): 

205 LogitEncoder(composite_cols = [('a', 'b')]).fit(data, [0, 1, 1] * 20) 

206 

207 

208""" Edge Cases """ 

209 

210 

211def test_classes_whose_names_end_like_suffixes() -> None: 

212 """Class names that end in 'se' are not taken for standard errors.""" 

213 rng = np.random.default_rng(3) 

214 data = pd.DataFrame({'color': rng.choice(['a', 'b', 'c'], 300)}) 

215 outcome_values = pd.Series(rng.choice(['case', 'false', 'house'], 300)) 

216 encoder = LogitEncoder(return_uncertainty = True, cv = None) 

217 output = encoder.fit(data, outcome_values).transform(data) 

218 modeled = list(encoder.modeled_classes_) 

219 expected = [ 

220 *(f'color_{name}' for name in modeled), 

221 *(f'color_{name}_se' for name in modeled), 

222 'color_count'] 

223 assert list(output.columns) == expected 

224 assert (output.filter(like = '_se') > 0).all().all() 

225 

226 

227def test_duplicate_output_columns_raise() -> None: 

228 """An output name that would appear twice raises an error.""" 

229 data = pd.DataFrame({'a': ['x', 'y'] * 30, 'a_maybe': [1.0, 2.0] * 30}) 

230 labels = ['no', 'maybe', 'yes', 'no'] * 15 

231 with pytest.raises(ValueError, match = 'duplicate columns'): 

232 LogitEncoder(cols = ['a']).fit(data, labels) 

233 # A class named 'count' collides with the count column. 

234 counted = ['count', 'other', 'third', 'other'] * 15 

235 with pytest.raises(ValueError, match = 'duplicate columns'): 

236 LogitEncoder(cols = ['a'], return_uncertainty = True).fit( 

237 data, counted) 

238 

239 

240@pytest.mark.parametrize(('data', 'error', 'message'), [ 

241 (sparse.csr_matrix(np.ones((4, 2))), TypeError, 'sparse'), 

242 (np.ones(4), ValueError, 'Expected 2D'), 

243 (np.ones((2, 2, 2)), ValueError, 'Expected 2D'), 

244 (np.ones((0, 2)), ValueError, '0 sample'), 

245 (np.ones((4, 0)), ValueError, '0 feature'), 

246 (np.ones((4, 2)) + 1j, ValueError, 'Complex'), 

247 (pd.DataFrame([[1, 2]] * 4, columns = ['a', 'a']), ValueError, 

248 'duplicate columns')]) 

249def test_invalid_inputs(data: Any, error: type, message: str) -> None: 

250 """Invalid inputs raise clear errors.""" 

251 with pytest.raises(error, match = message): 

252 LogitEncoder(cols = 'all').fit(data, [0, 1, 0, 1][:np.shape(data)[0]]) 

253 

254 

255@pytest.mark.parametrize(('target', 'message'), [ 

256 (pd.DataFrame({'a': [0, 1] * 10, 'b': [1, 0] * 10}), 'one-dimensional'), 

257 (np.ones((20, 2)), 'one-dimensional'), 

258 ([0, 1] * 5, 'inconsistent numbers'), 

259 (np.linspace(0, 1, 20), 'continuous'), 

260 ([0.0, np.nan] * 10, 'missing values')]) 

261def test_invalid_outcomes(target: Any, message: str) -> None: 

262 """Invalid outcomes raise clear errors.""" 

263 data = pd.DataFrame({'a': ['x', 'y'] * 10}) 

264 with pytest.raises(ValueError, match = message): 

265 LogitEncoder().fit(data, target) 

266 

267 

268def test_one_column_outcomes() -> None: 

269 """A one-column DataFrame or array is accepted as the outcome.""" 

270 data = pd.DataFrame({'a': ['x', 'y', 'z', 'x'] * 10}) 

271 target = np.array([0, 1, 1, 0] * 10) 

272 expected = LogitEncoder(cv = None).fit(data, target).transform(data) 

273 for shaped in (target.reshape(-1, 1), pd.DataFrame({'y': target})): 

274 actual = LogitEncoder(cv = None).fit(data, shaped).transform(data) 

275 pd.testing.assert_frame_equal(actual, expected) 

276 

277 

278@pytest.mark.parametrize(('params', 'message'), [ 

279 ({'C': '1'}, 'C must be'), 

280 ({'C': True}, 'C must be'), 

281 ({'l1_ratio': True}, 'l1_ratio must be'), 

282 ({'l1_ratio': None}, 'l1_ratio must be'), 

283 ({'cv': True}, 'cv must be'), 

284 ({'max_iter': 2.5}, 'max_iter must be'), 

285 ({'min_group_size': -1}, 'min_group_size must be'), 

286 ({'min_group_name': 'x'}, 'only works'), 

287 ({'min_group_size': 5, 'combine_min_nan_groups': 'maybe'}, 

288 'combine_min_nan_groups'), 

289 ({'min_group_size': 5, 'combine_min_nan_groups': 'force', 

290 'handle_missing': 'return_nan'}, 'Cannot have'), 

291 ({'handle_missing': ['value']}, 'handle_missing must be')]) 

292def test_invalid_parameter_values(params: dict, message: str) -> None: 

293 """Invalid parameter values raise ValueErrors when fitting.""" 

294 with pytest.raises(ValueError, match = message): 

295 LogitEncoder(**params).fit(X, Y) 

296 

297 

298@pytest.mark.parametrize('parameter', ['interactions', 'composite_cols']) 

299def test_combinations_must_be_lists(parameter: str) -> None: 

300 """`interactions` and `composite_cols` must be lists of tuples.""" 

301 with pytest.raises(TypeError, match = 'list of tuples'): 

302 LogitEncoder(**{parameter: 'color'}).fit(X, Y) 

303 

304 

305def test_unhashable_categories_raise() -> None: 

306 """A category that cannot be hashed raises a TypeError.""" 

307 data = pd.DataFrame({'a': [{'x': 1}, 'y'] * 10}) 

308 with pytest.raises(TypeError, match = 'hashable'): 

309 LogitEncoder().fit(data, [0, 1] * 10) 

310 

311 

312def test_constant_and_all_missing_columns() -> None: 

313 """Columns with one category, or only missing values, still encode.""" 

314 data = pd.DataFrame({ 

315 'constant': ['same'] * 40, 

316 'missing': [np.nan] * 40, 

317 'color': ['a', 'b'] * 20}).astype(object) 

318 target = [0, 1, 1, 0] * 10 

319 for C in (1.0, None): 

320 output = LogitEncoder(cols = 'all', C = C, cv = None).fit( 

321 data, target).transform(data) 

322 assert np.isfinite(output.to_numpy(dtype = float)).all() 

323 

324 

325def test_callable_and_numeric_missing_and_unknown_values() -> None: 

326 """Callables and numbers set the values of unknown categories.""" 

327 encoder = LogitEncoder( 

328 cols = ['color'], 

329 cv = None, 

330 handle_unknown = lambda value, mapping: 9.0).fit(X, Y) 

331 assert encoder.transform(NEW)['color'].iloc[0] == 9.0 

332 with pytest.raises(ValueError, match = 'collides'): 

333 LogitEncoder( 

334 cols = ['color'], 

335 encoding = 'coefficient', 

336 cv = None, 

337 handle_unknown = 0.0).fit(X, Y) 

338 

339 

340def test_transform_outcome_with_new_class_raises() -> None: 

341 """An outcome passed to `transform` must use the fitted classes.""" 

342 encoder = LogitEncoder(cols = ['color']).fit(X, Y) 

343 with pytest.raises(ValueError, match = 'fitted classes'): 

344 encoder.transform(X, Y.replace({1: 2})) 

345 

346 

347def test_cross_fitting_falls_back_with_too_few_rows() -> None: 

348 """With too few rows of a class for two folds, values are not crossed.""" 

349 encoder = LogitEncoder(cols = ['color'], random_state = 0).fit(X, Y) 

350 small = X.head(3) 

351 pd.testing.assert_frame_equal( 

352 encoder.transform(small, pd.Series([0, 0, 1], index = small.index)), 

353 encoder.transform(small)) 

354 

355 

356def test_statsmodels_unpenalized_reports_iterations() -> None: 

357 """The unpenalized statsmodels fit reports its iterations.""" 

358 encoder = LogitEncoder( 

359 cols = ['color'], backend = 'statsmodels', C = None, cv = None) 

360 assert encoder.fit(X, Y).n_iter_ >= 1 

361 

362 

363def test_feature_names_with_input_features() -> None: 

364 """`input_features` renames the output, including expanded columns.""" 

365 data = pd.DataFrame({'a': ['x', 'y', 'z'] * 20, 'b': [1.0, 2.0, 3.0] * 20}) 

366 target = ['no', 'maybe', 'yes'] * 20 

367 encoder = LogitEncoder(cols = [0], return_uncertainty = True).fit( 

368 data.to_numpy(), target) 

369 names = encoder.get_feature_names_out(['first', 'second']) 

370 modeled = list(encoder.modeled_classes_) 

371 assert list(names) == [ 

372 *(f'first_{name}' for name in modeled), 

373 *(f'first_{name}_se' for name in modeled), 

374 'first_count', 'second'] 

375 

376 

377""" Model Module """ 

378 

379 

380def test_model_module_rejects_bad_options() -> None: 

381 """The model functions reject unknown options.""" 

382 data = _logit_models.aggregate( 

383 np.array([[1], [2], [1], [2]]), np.array([0, 1, 1, 0])) 

384 with pytest.raises(ValueError, match = 'reference must be'): 

385 _logit_models.build_design(data, 'last') # type: ignore[arg-type] 

386 design = _logit_models.build_design(data, 'first') 

387 with pytest.raises(ValueError, match = 'backend must be'): 

388 _logit_models.fit_logit( 

389 matrix = design.matrix, target = data.target, 

390 weights = data.weights, backend = 'r', # type: ignore[arg-type] 

391 C = 1.0, l1_ratio = 0.0, max_iter = 10) 

392 with pytest.raises(ValueError, match = 'encoding must be'): 

393 _logit_models.compute_encodings( 

394 design = design, data = data, fits = [], 

395 encoding = 'odds', ridge = 1.0, # type: ignore[arg-type] 

396 uncertainty = False) 

397 with pytest.raises(ValueError, match = 'model must be'): 

398 _logit_models.fit_encodings( 

399 codes = np.array([[1], [2]]), target = np.array([0, 1]), 

400 reference_class = 0, n_classes = 2, encoding = 'log_odds', 

401 model = 'mixed', backend = 'sklearn', # type: ignore[arg-type] 

402 C = 1.0, l1_ratio = 0.0, reference = 'first', max_iter = 10, 

403 uncertainty = False) 

404 

405 

406def test_model_module_without_columns() -> None: 

407 """With no columns, the model is intercept-only.""" 

408 encodings = _logit_models.fit_encodings( 

409 codes = np.zeros((4, 0), dtype = np.int64), 

410 target = np.array([0, 1, 1, 0]), 

411 reference_class = 0, n_classes = 2, encoding = 'log_odds', 

412 model = 'joint', backend = 'sklearn', C = 1.0, l1_ratio = 0.0, 

413 reference = 'first', max_iter = 10, uncertainty = True) 

414 assert encodings.columns == [] 

415 assert encodings.n_iter == 1 

416 

417 

418def test_missing_interaction_with_error_handling() -> None: 

419 """A missing interaction raises with `handle_missing = 'error'`.""" 

420 data = pd.DataFrame({'a': ['x', 'y'] * 20, 'b': ['p', 'q', 'r', 's'] * 10}) 

421 encoder = LogitEncoder( 

422 cols = ['a'], 

423 interactions = [('a', 'b')], 

424 handle_missing = 'error').fit(data, [0, 1, 1, 0] * 10) 

425 with pytest.raises(ValueError, match = 'cannot contain null'): 

426 encoder.transform(data.assign(b = np.nan)) 

427 

428 

429def test_single_column_name_for_cols() -> None: 

430 """`cols` may name one column without a list, as in category_encoders.""" 

431 encoder = LogitEncoder(cols = 'color').fit(X, Y) 

432 assert encoder.cols_ == ['color']