Skip to content

Commit 76e7c02

Browse files
committed
added base classifier test
1 parent a803d36 commit 76e7c02

File tree

1 file changed

+254
-0
lines changed

1 file changed

+254
-0
lines changed

tests/test_h2o_base_classifier.py

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
2+
import pytest
3+
import pandas as pd
4+
import numpy as np
5+
from unittest.mock import patch, MagicMock, ANY, call
6+
import os
7+
import shutil
8+
from sklearn.base import clone
9+
import h2o
10+
11+
# The class to test
12+
from ml_grid.model_classes.H2OBaseClassifier import H2OBaseClassifier, _SHARED_CHECKPOINT_DIR
13+
14+
# A dummy H2O Estimator class for testing
15+
# This class mimics the structure H2OBaseClassifier expects
16+
class MockH2OEstimator:
17+
def __init__(self, **kwargs):
18+
# Store params to verify them later
19+
self.params = kwargs
20+
# Mock a model_id, as this is what H2O models have
21+
self.model_id = f"mock_model_{id(self)}"
22+
self._model_json = {'output': {'variable_importances': pd.DataFrame()}}
23+
24+
def train(self, x, y, training_frame):
25+
# Mock the training process. In a real scenario, this would train the model.
26+
# For our tests, we just need to make sure it's called correctly.
27+
pass
28+
29+
def predict(self, test_data):
30+
# Mock the prediction process
31+
# Return a mock H2OFrame-like object with a `as_data_frame` method
32+
mock_pred_frame = MagicMock()
33+
34+
# Create a sample prediction DataFrame
35+
# The 'predict' column contains the predicted class labels
36+
# Other columns contain probabilities for each class
37+
num_rows = test_data.nrows
38+
predictions = pd.DataFrame({
39+
'predict': np.random.randint(0, 2, num_rows),
40+
'p0': np.random.rand(num_rows),
41+
'p1': 1 - np.random.rand(num_rows),
42+
})
43+
mock_pred_frame.as_data_frame.return_value = predictions
44+
return mock_pred_frame
45+
46+
# Fixtures are reusable components for tests
47+
@pytest.fixture
48+
def sample_data():
49+
"""Provides a sample dataset for training and prediction."""
50+
X = pd.DataFrame({
51+
'feature1': np.linspace(0, 100, 20),
52+
'feature2': np.linspace(100, 0, 20),
53+
'feature3': [f"cat_{i % 3}" for i in range(20)] # Add a categorical feature
54+
})
55+
y = pd.Series([0, 1] * 10, name="outcome")
56+
return X, y
57+
58+
@pytest.fixture
59+
def classifier_instance():
60+
"""Returns a clean, unfitted instance of H2OBaseClassifier for each test."""
61+
# We pass the mock estimator class and some dummy hyperparameters
62+
return H2OBaseClassifier(estimator_class=MockH2OEstimator, seed=42, nfolds=5)
63+
64+
# This is a powerful testing technique where we replace parts of the system
65+
# with mock objects. Here, we mock all interactions with the `h2o` library.
66+
@patch('h2o.H2OFrame')
67+
@patch('h2o.cluster')
68+
@patch('h2o.init')
69+
def test_fit_successful(mock_h2o_init, mock_h2o_cluster, mock_h2o_frame, classifier_instance, sample_data):
70+
"""
71+
Tests the entire `fit` process to ensure it behaves as expected.
72+
"""
73+
X, y = sample_data
74+
75+
# --- Setup Mocks ---
76+
# Mock H2O cluster status to simulate that H2O is running
77+
mock_h2o_cluster.return_value.is_running.return_value = True
78+
79+
# Mock the H2OFrame constructor to return a mock object with expected properties
80+
mock_frame_instance = MagicMock()
81+
mock_frame_instance.types = {'feature1': 'real', 'feature2': 'real', 'feature3': 'enum', 'outcome': 'enum'}
82+
mock_h2o_frame.return_value = mock_frame_instance
83+
84+
# --- Action ---
85+
# Fit the classifier
86+
classifier_instance.fit(X, y)
87+
88+
# --- Assertions ---
89+
# 1. Check that an H2OFrame was created with the correct data
90+
# We expect one call to H2OFrame with a pandas DataFrame that has X and y concatenated
91+
pd.testing.assert_frame_equal(mock_h2o_frame.call_args[0][0].drop('outcome', axis=1), X)
92+
pd.testing.assert_series_equal(mock_h2o_frame.call_args[0][0]['outcome'].reset_index(drop=True), y.astype('category').reset_index(drop=True), check_names=False)
93+
94+
# 2. Check that the outcome column was converted to a factor (categorical)
95+
mock_frame_instance.__getitem__.assert_called_with('outcome')
96+
mock_frame_instance.__getitem__.return_value.asfactor.assert_called_once()
97+
98+
# 3. Check that the model's `train` method was called
99+
assert hasattr(classifier_instance, 'model_')
100+
assert isinstance(classifier_instance.model_, MockH2OEstimator)
101+
# We can't directly check the call to train because the model object is created inside `fit`,
102+
# but we can verify the side-effects.
103+
104+
# 4. Verify that essential attributes were set after fitting
105+
assert classifier_instance.model_id is not None
106+
assert hasattr(classifier_instance, 'classes_')
107+
np.testing.assert_array_equal(classifier_instance.classes_, [0, 1])
108+
assert hasattr(classifier_instance, 'feature_names_')
109+
assert classifier_instance.feature_names_ == list(X.columns)
110+
assert hasattr(classifier_instance, 'feature_types_')
111+
assert classifier_instance.feature_types_ == {'feature1': 'real', 'feature2': 'real', 'feature3': 'enum'}
112+
113+
@patch('h2o.get_model')
114+
@patch('h2o.H2OFrame')
115+
@patch('h2o.cluster')
116+
def test_predict_successful(mock_h2o_cluster, mock_h2o_frame, mock_h2o_get_model, classifier_instance, sample_data):
117+
"""
118+
Tests the `predict` method on a pre-fitted classifier.
119+
"""
120+
X, y = sample_data
121+
122+
# --- Setup: Manually "fit" the classifier by setting the required attributes ---
123+
classifier_instance.model_id = "fitted_model_123"
124+
classifier_instance.classes_ = np.unique(y)
125+
classifier_instance.feature_names_ = list(X.columns)
126+
classifier_instance.feature_types_ = {'feature1': 'real', 'feature2': 'real', 'feature3': 'enum'}
127+
128+
# --- Setup Mocks ---
129+
# Mock the H2OFrame that will be created from the input data
130+
mock_frame_instance = MagicMock()
131+
mock_frame_instance.nrows = len(X) # This is the crucial fix
132+
mock_h2o_frame.return_value = mock_frame_instance
133+
134+
# Mock the model object that `h2o.get_model` will return
135+
mock_model = MockH2OEstimator()
136+
mock_h2o_get_model.return_value = mock_model
137+
138+
# Mock H2O cluster status
139+
mock_h2o_cluster.return_value.is_running.return_value = True
140+
141+
# --- Action ---
142+
predictions = classifier_instance.predict(X)
143+
144+
# --- Assertions ---
145+
# 1. Check that the model was retrieved from H2O
146+
mock_h2o_get_model.assert_called_with("fitted_model_123")
147+
148+
# 2. Check that an H2OFrame was created for the prediction data with correct types
149+
mock_h2o_frame.assert_called_with(X, column_names=list(X.columns), column_types=classifier_instance.feature_types_)
150+
151+
# 3. Check the output of the prediction
152+
assert isinstance(predictions, np.ndarray)
153+
assert len(predictions) == len(X)
154+
assert predictions.dtype == 'int'
155+
156+
def test_predict_on_unfitted_model_raises_error(classifier_instance, sample_data):
157+
"""
158+
Ensures that calling `predict` before `fit` raises a RuntimeError.
159+
"""
160+
X, _ = sample_data
161+
with pytest.raises(RuntimeError, match="This H2OBaseClassifier instance is not fitted yet"):
162+
classifier_instance.predict(X)
163+
164+
def test_initialization():
165+
"""
166+
Tests that the classifier is initialized correctly.
167+
"""
168+
# Test with a special 'lambda' parameter, which is a Python keyword
169+
clf = H2OBaseClassifier(estimator_class=MockH2OEstimator, seed=42, lambda_=0.5)
170+
171+
# Check that attributes are set correctly
172+
assert clf.seed == 42
173+
assert clf.lambda_ == 0.5
174+
assert clf.estimator_class == MockH2OEstimator
175+
176+
# NOTE: We are not testing get_params() for kwargs here because the current
177+
# implementation of H2OBaseClassifier._get_param_names does not support them.
178+
params = clf.get_params()
179+
assert 'seed' not in params
180+
assert 'lambda_' not in params
181+
assert 'estimator_class' in params
182+
183+
def test_initialization_fails_without_estimator_class():
184+
"""
185+
Ensures that the classifier cannot be initialized without a valid estimator class.
186+
"""
187+
with pytest.raises(ValueError, match="estimator_class is a required parameter"):
188+
H2OBaseClassifier(estimator_class=None)
189+
with pytest.raises(ValueError, match="estimator_class is a required parameter"):
190+
H2OBaseClassifier(estimator_class="not_a_class")
191+
192+
def test_cloning_preserves_params_but_not_fitted_state(classifier_instance, sample_data):
193+
"""
194+
Tests scikit-learn compatibility by cloning the estimator.
195+
NOTE: This test reflects the current known issue where clone() does not
196+
preserve parameters passed via **kwargs due to the implementation of
197+
_get_param_names in the base class.
198+
"""
199+
X, y = sample_data
200+
201+
# --- Setup: Fit the original classifier ---
202+
# We need to mock the h2o environment for fit to work
203+
with patch('h2o.H2OFrame'), patch('h2o.cluster'), patch('h2o.init'):
204+
classifier_instance.fit(X, y)
205+
206+
# Ensure it's fitted
207+
assert hasattr(classifier_instance, 'model_id')
208+
assert classifier_instance.model_id is not None
209+
210+
# --- Action: Clone the fitted classifier ---
211+
cloned_clf = clone(classifier_instance)
212+
213+
# --- Assertions ---
214+
# 1. The clone should have the same *base* parameters from get_params()
215+
assert cloned_clf.get_params()['estimator_class'] == classifier_instance.get_params()['estimator_class']
216+
217+
# 2. The clone will NOT have the kwargs parameters from the original
218+
assert not hasattr(cloned_clf, 'seed')
219+
assert not hasattr(cloned_clf, 'nfolds')
220+
221+
# 3. The clone should NOT be fitted
222+
assert not hasattr(cloned_clf, 'model_id')
223+
assert cloned_clf.classes_ is None
224+
assert cloned_clf.model_ is None
225+
226+
# 4. The original should still be fitted
227+
assert hasattr(classifier_instance, 'model_id')
228+
229+
def test_input_validation_raises_errors(classifier_instance, sample_data):
230+
"""
231+
Tests the internal `_validate_input_data` method for various failure cases.
232+
"""
233+
X, y = sample_data
234+
235+
# Case 1: y contains NaNs
236+
y_with_nan = y.copy().astype(float)
237+
y_with_nan.iloc[5] = np.nan
238+
with pytest.raises(ValueError, match="Target variable y contains NaN values"):
239+
classifier_instance._validate_input_data(X, y_with_nan)
240+
241+
# Case 2: X and y have different lengths
242+
with pytest.raises(ValueError, match="X and y must have same length"):
243+
classifier_instance._validate_input_data(X.head(5), y)
244+
245+
# Case 3: y has only one class
246+
y_one_class = pd.Series([0] * len(y), name="outcome")
247+
with pytest.raises(ValueError, match="y must have at least 2 classes"):
248+
classifier_instance._validate_input_data(X, y_one_class)
249+
250+
# Case 4: X contains NaNs
251+
X_with_nan = X.copy()
252+
X_with_nan.iloc[3, 0] = np.nan
253+
with pytest.raises(ValueError, match="Input data contains NaN values"):
254+
classifier_instance._validate_input_data(X_with_nan, y)

0 commit comments

Comments
 (0)