Exemplo n.º 1
0
def test_nested_model(teardown):
    x_data = iris.data
    y_t_data = iris.target

    # Sub-model
    x = Input()
    y_t = Input()
    h = PCA(n_components=2)(x)
    y = LogisticRegression()(h, y_t)
    submodel = Model(x, y, y_t)

    # Model
    x = Input()
    y_t = Input()
    y = submodel(x, y_t)
    model = Model(x, y, y_t)

    with raises_with_cause(RuntimeError, NotFittedError):
        submodel.predict(x_data)

    model.fit(x_data, y_t_data)
    y_pred = model.predict(x_data)
    y_pred_sub = submodel.predict(x_data)

    assert_array_equal(y_pred, y_pred_sub)
Exemplo n.º 2
0
    def test_with_unnecessary_inputs(self, teardown):
        x1 = Input()
        x2 = Input()
        y_t = Input()
        h = PCA()(x1)
        y = LogisticRegression()(h, y_t)

        with pytest.raises(ValueError):
            Model([x1, x2], y, y_t)

        with pytest.raises(ValueError):
            Model([x1, h], y, y_t)  # x1 is an unnecessary input upstream of h
Exemplo n.º 3
0
def make_naive_stacked_model(n_components, random_state, x_data, y_t_data):
    # An unnecessarily complex Model

    # Sub-model 1
    x1 = Input(name="x1")
    y1_t = Input(name="y1_t")
    h1 = PCA(n_components=n_components, random_state=random_state, name="pca_sub1")(x1)
    y1 = LogisticRegression(
        multi_class="multinomial",
        solver="lbfgs",
        random_state=random_state,
        name="logreg_sub1",
    )(h1, y1_t)
    submodel1 = Model(x1, y1, y1_t, name="submodel1")

    # Sub-model 2 (a nested stacked model)
    x2 = Input(name="x2")
    y2_t = Input(name="y2_t")
    y2_1 = RandomForestClassifier(random_state=random_state, name="rforest_sub2")(
        x2, y2_t
    )
    y2_2 = ExtraTreesClassifier(random_state=random_state, name="extrees_sub2")(
        x2, y2_t
    )
    features = Stack(axis=1, name="stack_sub2")([y2_1, y2_2])
    y2 = LogisticRegression(
        multi_class="multinomial",
        solver="lbfgs",
        random_state=random_state,
        name="logreg_sub2",
    )(features, y2_t)
    submodel2 = Model(x2, y2, y2_t, name="submodel2")

    # Stack of submodels
    x = Input(name="x")
    y_t = Input(name="y_t")
    y1 = submodel1(x, y_t)
    y2 = submodel2(x, y_t)
    features = Stack(axis=1, name="stack")([y1, y2])
    y = LogisticRegression(
        multi_class="multinomial",
        solver="lbfgs",
        random_state=random_state,
        name="logreg_stacked",
    )(features, y_t)
    stacked_model_baikal = Model(x, y, y_t, name="stacked")

    stacked_model_baikal.fit(x_data, y_t_data)

    return stacked_model_baikal
Exemplo n.º 4
0
    def test_with_wrong_type(self, teardown):
        x = Input()
        y_t = Input()
        y = LogisticRegression()(x, y_t)

        wrong = np.zeros((10,))
        with pytest.raises(ValueError):
            Model(wrong, y, y_t)

        with pytest.raises(ValueError):
            Model(x, wrong, y_t)

        with pytest.raises(ValueError):
            Model(x, y, wrong)
Exemplo n.º 5
0
def test_fit_predict_ensemble(teardown):
    mask = iris.target != 2  # Reduce to binary problem to avoid ConvergenceWarning
    x_data = iris.data
    y_t_data = iris.target
    random_state = 123

    # baikal way
    x = Input()
    y_t = Input()
    y1 = LogisticRegression(random_state=random_state)(x, y_t)
    y2 = RandomForestClassifier(random_state=random_state)(x, y_t)
    features = Stack(axis=1)([y1, y2])
    y = LogisticRegression(random_state=random_state)(features, y_t)

    model = Model(x, y, y_t)
    model.fit(x_data, y_t_data)
    y_pred_baikal = model.predict(x_data)

    # traditional way
    logreg = sklearn.linear_model.LogisticRegression(random_state=random_state)
    logreg.fit(x_data, y_t_data)
    logreg_pred = logreg.predict(x_data)

    random_forest = sklearn.ensemble.RandomForestClassifier(random_state=random_state)
    random_forest.fit(x_data, y_t_data)
    random_forest_pred = random_forest.predict(x_data)

    features = np.stack([logreg_pred, random_forest_pred], axis=1)
    ensemble = sklearn.linear_model.LogisticRegression(random_state=random_state)
    ensemble.fit(features, y_t_data)
    y_pred_traditional = ensemble.predict(features)

    assert_array_equal(y_pred_baikal, y_pred_traditional)
Exemplo n.º 6
0
 def build_model(step):
     x1 = Input()
     x2 = Input()
     y_t1 = Input()
     y_t2 = Input()
     y_p = step([x1, x2], [y_t1, y_t2])
     return Model([x1, x2], y_p, [y_t1, y_t2])
Exemplo n.º 7
0
def test_get_params(teardown):
    dummy1 = DummyEstimator(name="dummy1")
    dummy2 = DummyEstimator(x=456, y="def", name="dummy2")
    concat = Concatenate(name="concat")  # a step without get_params/set_params

    # a meaningless pipeline that contains shared steps
    x1 = Input()
    x2 = Input()
    h = dummy1(x1)
    c = concat([x1, h])
    y1 = dummy2(c)
    y2 = dummy2(x2, compute_func=lambda X: X * 2, trainable=False)
    model = Model([x1, x2], [y1, y2])

    expected = {
        "dummy1": dummy1,
        "dummy2": dummy2,
        "concat": concat,
        "dummy1__x": 123,
        "dummy1__y": "abc",
        "dummy2__x": 456,
        "dummy2__y": "def",
    }

    params = model.get_params()
    assert params == expected
Exemplo n.º 8
0
def test_fit_predict_pipeline(teardown):
    x_data = iris.data
    y_t_data = iris.target
    random_state = 123
    n_components = 2

    # baikal way
    x = Input()
    y_t = Input()
    x_pca = PCA(n_components=n_components, random_state=random_state, name="pca")(x)
    y = LogisticRegression(
        multi_class="multinomial",
        solver="lbfgs",
        random_state=random_state,
        name="logreg",
    )(x_pca, y_t)

    model = Model(x, y, y_t)
    y_pred_baikal = model.fit(x_data, y_t_data).predict(x_data)

    # traditional way
    pca = PCA(n_components=n_components, random_state=random_state)
    logreg = LogisticRegression(
        multi_class="multinomial", solver="lbfgs", random_state=random_state
    )
    x_data_transformed = pca.fit_transform(x_data)
    y_pred_traditional = logreg.fit(x_data_transformed, y_t_data).predict(
        x_data_transformed
    )

    assert_array_equal(y_pred_baikal, y_pred_traditional)
Exemplo n.º 9
0
    def test_with_missing_inputs(self, teardown):
        x1 = Input()
        x2 = Input()
        c = Concatenate()([x1, x2])

        with pytest.raises(ValueError):
            Model(x1, c)
Exemplo n.º 10
0
    def test_with_improperly_defined_step(self, teardown):
        x = Input()
        y = DummyImproperlyDefined()(x)
        model = Model(x, y)

        with pytest.raises(RuntimeError):
            model.predict(iris.data)
Exemplo n.º 11
0
def test_fit_predict_naive_stack(teardown):
    x_data = iris.data
    y_t_data = iris.target
    random_state = 123

    # baikal way
    x = Input()
    y_t = Input()
    y1 = LogisticRegression(random_state=random_state, solver="liblinear")(x, y_t)
    y2 = RandomForestClassifier(random_state=random_state)(x, y_t)
    features = Stack(axis=1)([y1, y2])
    y = LogisticRegression(random_state=random_state, solver="liblinear")(features, y_t)

    model = Model(x, y, y_t)
    model.fit(x_data, y_t_data)
    y_pred_baikal = model.predict(x_data)

    # traditional way
    logreg = LogisticRegression(random_state=random_state, solver="liblinear")
    logreg.fit(x_data, y_t_data)
    logreg_pred = logreg.predict(x_data)

    random_forest = RandomForestClassifier(random_state=random_state)
    random_forest.fit(x_data, y_t_data)
    random_forest_pred = random_forest.predict(x_data)

    features = np.stack([logreg_pred, random_forest_pred], axis=1)
    stacked = LogisticRegression(random_state=random_state, solver="liblinear")
    stacked.fit(features, y_t_data)
    y_pred_traditional = stacked.predict(features)

    assert_array_equal(y_pred_baikal, y_pred_traditional)
Exemplo n.º 12
0
def test_fit_params(teardown):
    x_data = iris.data
    y_t_data = iris.target
    random_state = 123
    n_components = 2

    sample_weight = y_t_data + 1  # Just weigh the classes differently
    fit_params = {"logreg__sample_weight": sample_weight}

    # baikal way
    x = Input()
    y_t = Input()
    x_pca = PCA(n_components=n_components, random_state=random_state, name="pca")(x)
    y = LogisticRegression(
        multi_class="multinomial",
        solver="lbfgs",
        random_state=random_state,
        name="logreg",
    )(x_pca, y_t)

    model = Model(x, y, y_t)
    model.fit(x_data, y_t_data, **fit_params)

    # traditional way
    pca = PCA(n_components=n_components, random_state=random_state)
    logreg = LogisticRegression(
        multi_class="multinomial", solver="lbfgs", random_state=random_state
    )
    pipe = Pipeline([("pca", pca), ("logreg", logreg)])
    pipe.fit(x_data, y_t_data, **fit_params)

    # Use assert_allclose instead of all equal due to small numerical differences
    # between fit_transform(...) and fit(...).transform(...)
    assert_allclose(model.get_step("logreg").coef_, pipe.named_steps["logreg"].coef_)
Exemplo n.º 13
0
def build_fn():
    x = Input()
    y_t = Input()
    h = PCA(random_state=random_state, name="pca")(x)
    y_p = LogisticRegression(random_state=random_state, name="classifier")(h, y_t)
    model = Model(x, y_p, y_t)
    return model
Exemplo n.º 14
0
    def test_with_steps_with_duplicated_names(self, teardown):
        x = Input()
        h = PCA(name="duplicated-name")(x)
        y = LogisticRegression(name="duplicated-name")(h)

        with pytest.raises(RuntimeError):
            Model(x, y)
Exemplo n.º 15
0
 def test_fit_with_shared_step(self, teardown):
     x = Input()
     scaler = StandardScaler()
     z = scaler(x, compute_func="transform", trainable=True)
     y = scaler(z, compute_func="inverse_transform", trainable=False)
     model = Model(x, y)
     model.fit(np.array([1, 3, 1, 3]).reshape(-1, 1))
     assert (scaler.mean_, scaler.var_) == (2.0, 1.0)
Exemplo n.º 16
0
    def test_simple(self, teardown):
        x1 = Input()
        x2 = Input()
        y_t = Input()

        x1_transformed = PCA()(x1)
        y_t_encoded = LabelEncoder()(y_t)
        z = Concatenate()([x1_transformed, x2])
        y = LogisticRegression()(z, y_t_encoded)
        # TODO: support shareable steps to reuse LabelEncoder with compute_func="inverse_transform"

        # full model
        Model([x1, x2], y, y_t)

        # submodels
        Model(x1, x1_transformed)
        Model(z, y, y_t_encoded)
Exemplo n.º 17
0
 def test_with_undefined_target(self, teardown):
     x = Input()
     y = LogisticRegression()(x, trainable=True)
     model = Model(inputs=x, outputs=y)
     with raises_with_cause(RuntimeError, TypeError):
         # LogisticRegression.fit will be called with not enough arguments
         # hence the TypeError
         model.fit(iris.data)
Exemplo n.º 18
0
 def test_predict_with_shared_step(self, teardown):
     x1 = Input()
     x2 = Input()
     doubler = Lambda(lambda x: x * 2)
     y1 = doubler(x1)
     y2 = doubler(x2)
     model = Model([x1, x2], [y1, y2])
     assert model.predict([2, 3]) == [4, 6]
Exemplo n.º 19
0
def test_try_and_raise_with_cause(teardown):
    x = Input()
    y = DummyStepWithFaultyPredict(name="faultystep")(x)
    model = Model(x, y)
    with raises_with_cause(RuntimeError, KeyError):
        model.predict(123)

    x = Input()
    y = DummyStepWithFaultyFit(name="faultystep")(x)
    model = Model(x, y)
    with raises_with_cause(RuntimeError, ValueError):
        model.fit(123)

    x = Input()
    y = DummyStepWithFaultyFitPredict(name="faultystep")(x)
    model = Model(x, y)
    with raises_with_cause(RuntimeError, ValueError):
        model.fit(123)
Exemplo n.º 20
0
 def build_fn():
     x = Input()
     y_t = Input()
     h = PCA(random_state=random_state, name="pca")(x)
     y = LogisticRegression(random_state=random_state,
                            solver="liblinear",
                            name="logreg")(h, y_t)
     model = Model(x, y, y_t)
     return model
Exemplo n.º 21
0
def test_lazy_model(teardown):
    x_data = np.array([[1, 2], [3, 4]])

    x = Input()
    model = Model(x, x)
    model.fit(x_data)  # nothing to fit
    x_pred = model.predict(x_data)

    assert_array_equal(x_pred, x_data)
Exemplo n.º 22
0
def test_plot_model(teardown, tmp_path):
    x1 = Input(name="x1")
    x2 = Input(name="x2")
    y1, y2 = DummyMIMO()([x1, x2])
    submodel = Model([x1, x2], [y1, y2], name="submodel")

    x = Input(name="x")
    h1, h2 = DummySIMO()(x)
    z1, z2 = submodel([h1, h2])

    u = Input(name="u")
    v = DummySISO()(u)

    w = DummyMISO()([z1, z2])
    model = Model([x, u], [w, v], name="main_model")

    filename = str(tmp_path / "test_plot_model.png")
    plot_model(model, filename, show=False, expand_nested=True)
Exemplo n.º 23
0
def test_single_input(step_class, teardown):
    x = Input()
    y = step_class()(x)
    model = Model(x, y)

    x_data = np.array([[1, 2], [3, 4]])
    if step_class is Stack:
        assert_array_equal(x_data.reshape((2, 2, 1)), model.predict(x_data))
    else:
        assert_array_equal(x_data, model.predict(x_data))
Exemplo n.º 24
0
    def test_predict_with_not_fitted_steps(self, teardown):
        x_data = iris.data

        x = Input(name="x")
        xt = PCA(n_components=2)(x)
        y = LogisticRegression(multi_class="multinomial", solver="lbfgs")(xt)

        model = Model(x, y)
        with raises_with_cause(RuntimeError, NotFittedError):
            model.predict(x_data)
Exemplo n.º 25
0
 def test_with_unnecessarily_defined_but_missing_target(self, teardown):
     x = Input()
     y_t = Input()
     pca = PCA()
     # The target passed to PCA is unnecessary (see notes in Step.__call__)
     y = pca(x, y_t, trainable=True)
     model = Model(inputs=x, outputs=y, targets=y_t)
     with pytest.raises(ValueError):
         # fails because of the model target specification and trainable=True
         model.fit(iris.data)
Exemplo n.º 26
0
def test_multiedge(teardown):
    x = Input()
    z1, z2 = DummySIMO()(x)
    y = DummyMISO()([z1, z2])
    model = Model(x, y)

    x_data = np.array([[1], [2]])
    y_out = model.predict(x_data)

    assert_array_equal(y_out, np.array([[2], [4]]))
Exemplo n.º 27
0
def test_fit_predict_with_shared_step(teardown):
    x = Input()
    scaler = StandardScaler()
    z = scaler(x, compute_func="transform", trainable=True)
    y = scaler(z, compute_func="inverse_transform", trainable=False)
    model = Model(x, y)

    X_data = np.array([1, 3, 1, 3]).reshape(-1, 1)
    model.fit(X_data)
    assert_array_equal(model.predict(X_data), X_data)
Exemplo n.º 28
0
 def test_with_non_fitted_non_trainable_step(self, teardown):
     x = Input()
     y_t = Input()
     z = PCA()(x, trainable=False)
     y = LogisticRegression()(z, y_t)
     model = Model(x, y, y_t)
     with raises_with_cause(RuntimeError, NotFittedError):
         # this will raise an error when calling compute
         # on PCA which was flagged as trainable=False but
         # hasn't been fitted
         model.fit(iris.data, iris.target)
Exemplo n.º 29
0
def test_split(x, indices_or_sections, teardown):
    x1 = Input()
    ys = Split(indices_or_sections, axis=0)(x1)
    model = Model(x1, ys)

    y_expected = np.split(x, indices_or_sections, axis=0)
    y_pred = model.predict(x)
    y_pred = listify(y_pred)

    for actual, expected in safezip2(y_pred, y_expected):
        assert_array_equal(actual, expected)
Exemplo n.º 30
0
def test_fit_and_predict_model_with_no_fittable_steps(teardown):
    X_data = np.array([[1, 2], [3, 4]])
    y_expected = np.array([[2, 4], [6, 8]])

    x = Input()
    y = DummySISO()(x)

    model = Model(x, y)
    model.fit(X_data)  # nothing to fit
    y_pred = model.predict(X_data)

    assert_array_equal(y_pred, y_expected)