Skip to content

Commit c310ef6

Browse files
[FIX] Passing checks (#298)
* Initial fix for all tests passing locally py=3.8 * fix bug in tests * fix bug in test for data * debugging error in dummy forward pass * debug try -2 * catch runtime error in ci * catch runtime error in ci * add better debug test setup * debug some more * run this test only * remove sum backward * remove inplace in inception block * undo silly change * Enable all tests * fix flake * fix bug in test setup * remove anamoly detection * minor changes to comments * Apply suggestions from code review Co-authored-by: nabenabe0928 <[email protected]> * Address comments from Shuhei * revert change leading to bug * fix flake * change comment position in feature validator * Add documentation for _is_datasets_consistent * address comments from arlind * case when all nans in test Co-authored-by: nabenabe0928 <[email protected]>
1 parent 34258e2 commit c310ef6

File tree

18 files changed

+119
-120
lines changed

18 files changed

+119
-120
lines changed

autoPyTorch/api/base_task.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1695,7 +1695,7 @@ def fit_ensemble(
16951695
Args:
16961696
optimize_metric (str): name of the metric that is used to
16971697
evaluate a pipeline. if not specified, value passed to search will be used
1698-
precision (int), (default=32): Numeric precision used when loading
1698+
precision (Optional[int]): Numeric precision used when loading
16991699
ensemble data. Can be either 16, 32 or 64.
17001700
ensemble_nbest (Optional[int]):
17011701
only consider the ensemble_nbest models to build the ensemble.
@@ -1738,6 +1738,7 @@ def fit_ensemble(
17381738
"Please call the `search()` method of {} prior to "
17391739
"fit_ensemble().".format(self.__class__.__name__))
17401740

1741+
precision = precision if precision is not None else self.precision
17411742
if precision not in [16, 32, 64]:
17421743
raise ValueError("precision must be one of 16, 32, 64 but got {}".format(precision))
17431744

@@ -1788,7 +1789,7 @@ def fit_ensemble(
17881789
manager = self._init_ensemble_builder(
17891790
time_left_for_ensembles=time_left_for_ensemble,
17901791
optimize_metric=self.opt_metric if optimize_metric is None else optimize_metric,
1791-
precision=self.precision if precision is None else precision,
1792+
precision=precision,
17921793
ensemble_size=ensemble_size,
17931794
ensemble_nbest=ensemble_nbest,
17941795
)

autoPyTorch/data/tabular_feature_validator.py

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import functools
2-
from typing import Dict, List, Optional, Tuple, cast
2+
from typing import Dict, List, Optional, Tuple, Union, cast
33

44
import numpy as np
55

@@ -124,6 +124,7 @@ def _comparator(cmp1: str, cmp2: str) -> int:
124124
if cmp1 not in choices or cmp2 not in choices:
125125
raise ValueError('The comparator for the column order only accepts {}, '
126126
'but got {} and {}'.format(choices, cmp1, cmp2))
127+
127128
idx1, idx2 = choices.index(cmp1), choices.index(cmp2)
128129
return idx1 - idx2
129130

@@ -271,13 +272,12 @@ def transform(
271272
# having a value for a categorical column.
272273
# We need to convert the column in test data to
273274
# object otherwise the test column is interpreted as float
274-
if len(self.categorical_columns) > 0:
275-
categorical_columns = self.column_transformer.transformers_[0][-1]
276-
for column in categorical_columns:
277-
if X[column].isna().all():
278-
X[column] = X[column].astype('object')
279-
280275
if self.column_transformer is not None:
276+
if len(self.categorical_columns) > 0:
277+
categorical_columns = self.column_transformer.transformers_[0][-1]
278+
for column in categorical_columns:
279+
if X[column].isna().all():
280+
X[column] = X[column].astype('object')
281281
X = self.column_transformer.transform(X)
282282

283283
# Sparse related transformations
@@ -362,16 +362,10 @@ def _check_data(
362362

363363
dtypes = [dtype.name for dtype in X.dtypes]
364364

365-
dtypes_diff = [s_dtype != dtype for s_dtype, dtype in zip(self.dtypes, dtypes)]
365+
diff_cols = X.columns[[s_dtype != dtype for s_dtype, dtype in zip(self.dtypes, dtypes)]]
366366
if len(self.dtypes) == 0:
367367
self.dtypes = dtypes
368-
elif (
369-
any(dtypes_diff) # the dtypes of some columns are different in train and test dataset
370-
and self.all_nan_columns is not None # Ignore all_nan_columns is None
371-
and len(set(X.columns[dtypes_diff]).difference(self.all_nan_columns)) != 0
372-
):
373-
# The dtypes can be different if and only if the column belongs
374-
# to all_nan_columns as these columns would be imputed.
368+
elif not self._is_datasets_consistent(diff_cols, X):
375369
raise ValueError("The dtype of the features must not be changed after fit(), but"
376370
" the dtypes of some columns are different between training ({}) and"
377371
" test ({}) datasets.".format(self.dtypes, dtypes))
@@ -539,6 +533,33 @@ def infer_objects(self, X: pd.DataFrame) -> pd.DataFrame:
539533

540534
return X
541535

536+
def _is_datasets_consistent(self, diff_cols: List[Union[int, str]], X: pd.DataFrame) -> bool:
537+
"""
538+
Check the consistency of dtypes between training and test datasets.
539+
The dtypes can be different if the column belongs to `self.all_nan_columns`
540+
(list of column names with all nans in training data) or if the column is
541+
all nan as these columns would be imputed.
542+
543+
Args:
544+
diff_cols (List[bool]):
545+
The column labels that have different dtypes.
546+
X (pd.DataFrame):
547+
A validation or test dataset to be compared with the training dataset
548+
Returns:
549+
_ (bool): Whether the training and test datasets are consistent.
550+
"""
551+
if self.all_nan_columns is None:
552+
if len(diff_cols) == 0:
553+
return True
554+
else:
555+
return all(X[diff_cols].isna().all())
556+
557+
# dtype is different ==> the column in at least either of train or test datasets must be all NaN
558+
# inconsistent <==> dtype is different and the col in both train and test is not all NaN
559+
inconsistent_cols = list(set(diff_cols) - self.all_nan_columns)
560+
561+
return len(inconsistent_cols) == 0 or all(X[inconsistent_cols].isna().all())
562+
542563

543564
def has_object_columns(
544565
feature_types: pd.Series,

autoPyTorch/pipeline/components/preprocessing/tabular_preprocessing/encoding/NoEncoder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def transform(self, X: Dict[str, Any]) -> Dict[str, Any]:
4040
Returns:
4141
(Dict[str, Any]): the updated 'X' dictionary
4242
"""
43-
X.update({'encoder': self.preprocessor})
43+
# X.update({'encoder': self.preprocessor})
4444
return X
4545

4646
@staticmethod

autoPyTorch/pipeline/components/preprocessing/tabular_preprocessing/scaling/NoScaler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def transform(self, X: Dict[str, Any]) -> Dict[str, Any]:
4343
Returns:
4444
np.ndarray: Transformed features
4545
"""
46-
X.update({'scaler': self.preprocessor})
46+
# X.update({'scaler': self.preprocessor})
4747
return X
4848

4949
@staticmethod

autoPyTorch/pipeline/components/setup/network_embedding/base_network_embedding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def fit(self, X: Dict[str, Any], y: Any = None) -> BaseEstimator:
2121

2222
self.embedding = self.build_embedding(
2323
num_input_features=num_input_features,
24-
num_numerical_features=num_numerical_columns)
24+
num_numerical_features=num_numerical_columns) # type: ignore[arg-type]
2525
return self
2626

2727
def transform(self, X: Dict[str, Any]) -> Dict[str, Any]:

autoPyTorch/pipeline/components/training/trainer/AdversarialTrainer.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,7 @@ def train_step(self, data: np.ndarray, targets: np.ndarray) -> Tuple[float, torc
109109
loss = loss_func(self.criterion, original_outputs, adversarial_outputs)
110110
loss.backward()
111111
self.optimizer.step()
112-
if self.scheduler:
113-
if 'ReduceLROnPlateau' in self.scheduler.__class__.__name__:
114-
self.scheduler.step(loss)
115-
else:
116-
self.scheduler.step()
112+
117113
# only passing the original outputs since we do not care about
118114
# the adversarial performance.
119115
return loss.item(), original_outputs

autoPyTorch/pipeline/components/training/trainer/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,7 @@ def fit(self, X: Dict[str, Any], y: Any = None, **kwargs: Any) -> autoPyTorchCom
283283
y=y,
284284
**kwargs
285285
)
286+
286287
# Add snapshots to base network to enable
287288
# predicting with snapshot ensemble
288289
self.choice: autoPyTorchComponent = cast(autoPyTorchComponent, self.choice)

examples/40_advanced/40_advanced/example_custom_configuration_space.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def get_search_space_updates():
5959
value_range=['shake-shake'],
6060
default_value='shake-shake')
6161
updates.append(node_name='network_backbone',
62-
hyperparameter='ResNetBackbone:shake_shake_method',
62+
hyperparameter='ResNetBackbone:shake_shake_update_func',
6363
value_range=['M3'],
6464
default_value='M3'
6565
)

test/test_data/test_feature_validator.py

Lines changed: 25 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,6 @@ def test_featurevalidator_supported_types(input_data_featuretest):
204204
assert sparse.issparse(transformed_X)
205205
else:
206206
assert isinstance(transformed_X, np.ndarray)
207-
assert np.shape(input_data_featuretest) == np.shape(transformed_X)
208207
assert np.issubdtype(transformed_X.dtype, np.number)
209208
assert validator._is_fitted
210209

@@ -237,11 +236,10 @@ def test_featurevalidator_categorical_nan(input_data_featuretest):
237236
validator.fit(input_data_featuretest)
238237
transformed_X = validator.transform(input_data_featuretest)
239238
assert any(pd.isna(input_data_featuretest))
240-
categories_ = validator.column_transformer.named_transformers_['categorical_pipeline'].\
241-
named_steps['ordinalencoder'].categories_
239+
categories_ = validator.column_transformer.\
240+
named_transformers_['categorical_pipeline'].named_steps['onehotencoder'].categories_
242241
assert any(('0' in categories) or (0 in categories) or ('missing_value' in categories) for categories in
243242
categories_)
244-
assert np.shape(input_data_featuretest) == np.shape(transformed_X)
245243
assert np.issubdtype(transformed_X.dtype, np.number)
246244
assert validator._is_fitted
247245
assert isinstance(transformed_X, np.ndarray)
@@ -294,7 +292,6 @@ def test_featurevalidator_fitontypeA_transformtypeB(input_data_featuretest):
294292
else:
295293
raise ValueError(type(input_data_featuretest))
296294
transformed_X = validator.transform(complementary_type)
297-
assert np.shape(input_data_featuretest) == np.shape(transformed_X)
298295
assert np.issubdtype(transformed_X.dtype, np.number)
299296
assert validator._is_fitted
300297

@@ -314,12 +311,6 @@ def test_featurevalidator_get_columns_to_encode():
314311
for col in df.columns:
315312
df[col] = df[col].astype(col)
316313

317-
<<<<<<< HEAD
318-
transformed_columns, feature_types = validator._get_columns_to_encode(df)
319-
320-
assert transformed_columns == ['category', 'bool']
321-
assert feature_types == ['numerical', 'numerical', 'categorical', 'categorical']
322-
=======
323314
validator.fit(df)
324315

325316
categorical_columns, numerical_columns, feat_type = validator._get_columns_info(df)
@@ -435,7 +426,6 @@ def test_feature_validator_remove_nan_catcolumns():
435426
)
436427
ans_test = np.array([[0, 0, 0, 0], [0, 0, 0, 0]], dtype=np.float64)
437428
feature_validator_remove_nan_catcolumns(df_train, df_test, ans_train, ans_test)
438-
>>>>>>> Bug fixes (#249)
439429

440430

441431
def test_features_unsupported_calls_are_raised():
@@ -445,36 +435,29 @@ def test_features_unsupported_calls_are_raised():
445435
expected
446436
"""
447437
validator = TabularFeatureValidator()
448-
with pytest.raises(ValueError, match=r"AutoPyTorch does not support time"):
438+
with pytest.raises(TypeError, match=r".*?Convert the time information to a numerical value"):
449439
validator.fit(
450440
pd.DataFrame({'datetime': [pd.Timestamp('20180310')]})
451441
)
442+
validator = TabularFeatureValidator()
452443
with pytest.raises(ValueError, match=r"AutoPyTorch only supports.*yet, the provided input"):
453444
validator.fit({'input1': 1, 'input2': 2})
454-
with pytest.raises(ValueError, match=r"has unsupported dtype string"):
445+
validator = TabularFeatureValidator()
446+
with pytest.raises(TypeError, match=r".*?but input column A has an invalid type `string`.*"):
455447
validator.fit(pd.DataFrame([{'A': 1, 'B': 2}], dtype='string'))
448+
validator = TabularFeatureValidator()
456449
with pytest.raises(ValueError, match=r"The feature dimensionality of the train and test"):
457450
validator.fit(X_train=np.array([[1, 2, 3], [4, 5, 6]]),
458451
X_test=np.array([[1, 2, 3, 4], [4, 5, 6, 7]]),
459452
)
453+
validator = TabularFeatureValidator()
460454
with pytest.raises(ValueError, match=r"Cannot call transform on a validator that is not fit"):
461455
validator.transform(np.array([[1, 2, 3], [4, 5, 6]]))
462456

463457

464458
@pytest.mark.parametrize(
465459
'input_data_featuretest',
466460
(
467-
'numpy_numericalonly_nonan',
468-
'numpy_numericalonly_nan',
469-
'pandas_numericalonly_nonan',
470-
'pandas_numericalonly_nan',
471-
'list_numericalonly_nonan',
472-
'list_numericalonly_nan',
473-
# Category in numpy is handled via feat_type
474-
'numpy_categoricalonly_nonan',
475-
'numpy_mixed_nonan',
476-
'numpy_categoricalonly_nan',
477-
'numpy_mixed_nan',
478461
'sparse_bsr_nonan',
479462
'sparse_bsr_nan',
480463
'sparse_coo_nonan',
@@ -512,7 +495,7 @@ def test_no_column_transformer_created(input_data_featuretest):
512495
)
513496
def test_column_transformer_created(input_data_featuretest):
514497
"""
515-
This test ensures an encoder is created if categorical data is provided
498+
This test ensures an column transformer is created if categorical data is provided
516499
"""
517500
validator = TabularFeatureValidator()
518501
validator.fit(input_data_featuretest)
@@ -521,7 +504,7 @@ def test_column_transformer_created(input_data_featuretest):
521504

522505
# Make sure that the encoded features are actually encoded. Categorical columns are at
523506
# the start after transformation. In our fixtures, this is also honored prior encode
524-
transformed_columns, feature_types = validator._get_columns_to_encode(input_data_featuretest)
507+
cat_columns, _, feature_types = validator._get_columns_info(input_data_featuretest)
525508

526509
# At least one categorical
527510
assert 'categorical' in validator.feat_type
@@ -530,20 +513,13 @@ def test_column_transformer_created(input_data_featuretest):
530513
if np.any([pd.api.types.is_numeric_dtype(input_data_featuretest[col]
531514
) for col in input_data_featuretest.columns]):
532515
assert 'numerical' in validator.feat_type
533-
for i, feat_type in enumerate(feature_types):
534-
if 'numerical' in feat_type:
535-
np.testing.assert_array_equal(
536-
transformed_X[:, i],
537-
input_data_featuretest[input_data_featuretest.columns[i]].to_numpy()
538-
)
539-
elif 'categorical' in feat_type:
540-
np.testing.assert_array_equal(
541-
transformed_X[:, i],
542-
# Expect always 0, 1... because we use a ordinal encoder
543-
np.array([0, 1])
544-
)
545-
else:
546-
raise ValueError(feat_type)
516+
# we expect this input to be the fixture 'pandas_mixed_nan'
517+
np.testing.assert_array_equal(transformed_X, np.array([[1., 0., -1.], [0., 1., 1.]]))
518+
else:
519+
np.testing.assert_array_equal(transformed_X, np.array([[1., 0., 1., 0.], [0., 1., 0., 1.]]))
520+
521+
if not all([feat_type in ['numerical', 'categorical'] for feat_type in feature_types]):
522+
raise ValueError("Expected only numerical and categorical feature types")
547523

548524

549525
def test_no_new_category_after_fit():
@@ -575,13 +551,12 @@ def test_unknown_encode_value():
575551
x['c'].cat.add_categories(['NA'], inplace=True)
576552
x.loc[0, 'c'] = 'NA' # unknown value
577553
x_t = validator.transform(x)
578-
# The first row should have a -1 as we added a new categorical there
579-
expected_row = [-1, -41, -3, -987.2]
554+
# The first row should have a 0, 0 as we added a
555+
# new categorical there and one hot encoder marks
556+
# it as all zeros for the transformed column
557+
expected_row = [0.0, 0.0, -0.5584294383572701, 0.5000000000000004, -1.5136598016833485]
580558
assert expected_row == x_t[0].tolist()
581559

582-
# Notice how there is only one column 'c' to encode
583-
assert validator.categories == [list(range(2)) for i in range(1)]
584-
585560

586561
# Actual checks for the features
587562
@pytest.mark.parametrize(
@@ -633,19 +608,20 @@ def test_feature_validator_new_data_after_fit(
633608
assert sparse.issparse(transformed_X)
634609
else:
635610
assert isinstance(transformed_X, np.ndarray)
636-
assert np.shape(X_test) == np.shape(transformed_X)
637611

638612
# And then check proper error messages
639613
if train_data_type == 'pandas':
640614
old_dtypes = copy.deepcopy(validator.dtypes)
641615
validator.dtypes = ['dummy' for dtype in X_train.dtypes]
642-
with pytest.raises(ValueError, match=r"Changing the dtype of the features after fit"):
616+
with pytest.raises(ValueError,
617+
match=r"The dtype of the features must not be changed after fit"):
643618
transformed_X = validator.transform(X_test)
644619
validator.dtypes = old_dtypes
645620
if test_data_type == 'pandas':
646621
columns = X_test.columns.tolist()
647622
X_test = X_test[reversed(columns)]
648-
with pytest.raises(ValueError, match=r"Changing the column order of the features"):
623+
with pytest.raises(ValueError,
624+
match=r"The column order of the features must not be changed after fit"):
649625
transformed_X = validator.transform(X_test)
650626

651627

test/test_data/test_validation.py

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import numpy as np
22

3-
import pandas as pd
4-
53
import pytest
64

75
from scipy import sparse
@@ -32,14 +30,6 @@ def test_data_validation_for_classification(openmlid, as_frame):
3230

3331
validator.fit(X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test)
3432
X_train_t, y_train_t = validator.transform(X_train, y_train)
35-
assert np.shape(X_train) == np.shape(X_train_t)
36-
37-
# Leave columns that are complete NaN
38-
# The sklearn pipeline will handle that
39-
if as_frame and np.any(pd.isnull(X_train).values.all(axis=0)):
40-
assert np.any(pd.isnull(X_train_t).values.all(axis=0))
41-
elif not as_frame and np.any(pd.isnull(X_train).all(axis=0)):
42-
assert np.any(pd.isnull(X_train_t).all(axis=0))
4333

4434
# make sure everything was encoded to number
4535
assert np.issubdtype(X_train_t.dtype, np.number)
@@ -74,14 +64,6 @@ def test_data_validation_for_regression(openmlid, as_frame):
7464
validator.fit(X_train=X_train, y_train=y_train)
7565

7666
X_train_t, y_train_t = validator.transform(X_train, y_train)
77-
assert np.shape(X_train) == np.shape(X_train_t)
78-
79-
# Leave columns that are complete NaN
80-
# The sklearn pipeline will handle that
81-
if as_frame and np.any(pd.isnull(X_train).values.all(axis=0)):
82-
assert np.any(pd.isnull(X_train_t).values.all(axis=0))
83-
elif not as_frame and np.any(pd.isnull(X_train).all(axis=0)):
84-
assert np.any(pd.isnull(X_train_t).all(axis=0))
8567

8668
# make sure everything was encoded to number
8769
assert np.issubdtype(X_train_t.dtype, np.number)
@@ -103,8 +85,6 @@ def test_sparse_data_validation_for_regression():
10385
validator.fit(X_train=X_sp, y_train=y)
10486

10587
X_t, y_t = validator.transform(X, y)
106-
assert np.shape(X) == np.shape(X_t)
107-
10888
# make sure everything was encoded to number
10989
assert np.issubdtype(X_t.dtype, np.number)
11090
assert np.issubdtype(y_t.dtype, np.number)

0 commit comments

Comments
 (0)