ML (Sklearn Bridge)
from_sklearn_linear() (Helper)¶
Demonstrates the from_sklearn_linear function. This is a client-side (cleartext) helper function. It is not an FHE circuit and cannot be compiled with fhe.Compiler.
from_sklearn_linear converts a fitted sklearn linear model (LogisticRegression or LinearRegression) into an FHE-compatible model by quantizing the float weights into integers.
from concrete_fhe_toolkit.ml.sklearn_bridge import from_sklearn_linear
from concrete_fhe_toolkit.ml.classes import FHELinearRegression, FHELogisticRegression
import numpy as np
# Create a mock sklearn-like LinearRegression model
class MockLinearRegression:
pass
mock_model = MockLinearRegression()
mock_model.coef_ = np.array([1.5, -2.0])
mock_model.intercept_ = 3.0
# Convert to FHE model with scale=10
fhe_model = from_sklearn_linear(mock_model, scale=10)
assert isinstance(fhe_model, FHELinearRegression), f'Expected FHELinearRegression, got {type(fhe_model).__name__}'
assert fhe_model.weights == [15, -20], f'Weights mismatch: {fhe_model.weights}'
assert fhe_model.bias == 30, f'Bias mismatch: {fhe_model.bias}'
print(f'Converted linear model: weights={fhe_model.weights}, bias={fhe_model.bias}')
# Test with a mock LogisticRegression (has classes_ attribute)
class MockLogisticRegression:
pass
mock_clf = MockLogisticRegression()
mock_clf.coef_ = np.array([[0.5, -1.0]])
mock_clf.intercept_ = np.array([2.0])
mock_clf.classes_ = np.array([0, 1])
fhe_clf = from_sklearn_linear(mock_clf, scale=100)
assert isinstance(fhe_clf, FHELogisticRegression), f'Expected FHELogisticRegression, got {type(fhe_clf).__name__}'
assert fhe_clf.weights == [50, -100], f'Weights mismatch: {fhe_clf.weights}'
print(f'Converted classifier: weights={fhe_clf.weights}, bias={fhe_clf.bias}')
print('from_sklearn_linear tests passed!')
from_sklearn_tree() (Helper)¶
Demonstrates the from_sklearn_tree function. This is a client-side (cleartext) helper function. It is not an FHE circuit and cannot be compiled with fhe.Compiler.
from_sklearn_tree converts a fitted sklearn DecisionTreeClassifier or DecisionTreeRegressor into an FHEDecisionTree. This requires a fitted model (with a tree_ attribute). Below we show the expected usage pattern.
from concrete_fhe_toolkit.ml.sklearn_bridge import from_sklearn_tree
from concrete_fhe_toolkit.ml.classes import FHEDecisionTree
# from_sklearn_tree requires a fitted sklearn tree model with a tree_ attribute.
# We demonstrate expected error handling for unfitted models.
try:
class UnfittedModel:
pass
from_sklearn_tree(UnfittedModel())
assert False, 'Should have raised ValueError'
except ValueError as e:
assert 'fitted sklearn decision tree' in str(e)
print(f'Correctly caught unfitted model: {e}')
# If sklearn is available, perform a real conversion
try:
from sklearn.tree import DecisionTreeClassifier
import numpy as np
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 1, 0, 1])
sk_tree = DecisionTreeClassifier(max_depth=2).fit(X, y)
fhe_tree = from_sklearn_tree(sk_tree, scale=1)
assert isinstance(fhe_tree, FHEDecisionTree)
assert isinstance(fhe_tree.tree, dict)
print(f'Real conversion successful: tree={fhe_tree.tree}')
except ImportError:
print('scikit-learn not installed, skipping real conversion test')
print('from_sklearn_tree tests passed!')
from_sklearn_forest() (Helper)¶
Demonstrates the from_sklearn_forest function. This is a client-side (cleartext) helper function. It is not an FHE circuit and cannot be compiled with fhe.Compiler.
from_sklearn_forest converts a fitted sklearn RandomForestClassifier into an FHERandomForest by converting each estimator tree individually.
from concrete_fhe_toolkit.ml.sklearn_bridge import from_sklearn_forest
from concrete_fhe_toolkit.ml.classes import FHERandomForest
# Test error handling for unfitted model
try:
class UnfittedForest:
pass
from_sklearn_forest(UnfittedForest())
assert False, 'Should have raised ValueError'
except ValueError as e:
assert 'fitted sklearn forest' in str(e)
print(f'Correctly caught unfitted model: {e}')
# If sklearn is available, perform a real conversion
try:
from sklearn.ensemble import RandomForestClassifier
import numpy as np
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 1, 0, 1])
sk_rf = RandomForestClassifier(n_estimators=3, max_depth=2, random_state=42).fit(X, y)
fhe_rf = from_sklearn_forest(sk_rf, scale=1)
assert isinstance(fhe_rf, FHERandomForest)
assert len(fhe_rf.trees) == 3
print(f'Real conversion successful: {len(fhe_rf.trees)} trees converted')
except ImportError:
print('scikit-learn not installed, skipping real conversion test')
print('from_sklearn_forest tests passed!')