Benchmark of PolynomialFeatures + partialfit of SGDClassifier (standalone)

This benchmark looks into a new implementation of PolynomialFeatures proposed in PR13290. It tests the following configurations:

This script is standalone and does not require pymlbenchmark as opposed to Benchmark of PolynomialFeatures + partialfit of SGDClassifier which reuse functions implemented in pymlbenchmark.

from time import perf_counter as time
import numpy
import numpy as np
from numpy.random import rand
import matplotlib.pyplot as plt
import pandas
import sklearn
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import SGDClassifier
try:
    from sklearn.utils._testing import ignore_warnings
except ImportError:
    from sklearn.utils.testing import ignore_warnings
from mlinsights.mlmodel import ExtendedFeatures

Implementations to benchmark

def fcts_model(X, y):

    model1 = SGDClassifier()
    model2 = make_pipeline(PolynomialFeatures(), SGDClassifier())
    model3 = make_pipeline(ExtendedFeatures(kind='poly'), SGDClassifier())
    model4 = make_pipeline(ExtendedFeatures(kind='poly-slow'), SGDClassifier())

    model1.fit(PolynomialFeatures().fit_transform(X), y)
    model2.fit(X, y)
    model3.fit(X, y)
    model4.fit(X, y)

    def partial_fit_model1(X, y, model=model1):
        return model.partial_fit(X, y)

    def partial_fit_model2(X, y, model=model2):
        X2 = model.steps[0][1].transform(X)
        return model.steps[1][1].partial_fit(X2, y)

    def partial_fit_model3(X, y, model=model3):
        X2 = model.steps[0][1].transform(X)
        return model.steps[1][1].partial_fit(X2, y)

    def partial_fit_model4(X, y, model=model4):
        X2 = model.steps[0][1].transform(X)
        return model.steps[1][1].partial_fit(X2, y)

    return (partial_fit_model1, partial_fit_model2,
            partial_fit_model3, partial_fit_model4)

Benchmarks

def build_x_y(ntrain, nfeat):
    X_train = np.empty((ntrain, nfeat))
    X_train[:, :] = rand(ntrain, nfeat)[:, :]
    X_trainsum = X_train.sum(axis=1)
    eps = rand(ntrain) - 0.5
    X_trainsum_ = X_trainsum + eps
    y_train = (X_trainsum_ >= X_trainsum).ravel().astype(int)
    return X_train, y_train


@ignore_warnings(category=(FutureWarning, DeprecationWarning))
def bench(n_obs, n_features, repeat=1000, verbose=False):
    res = []
    for n in n_obs:
        for nfeat in n_features:

            X_train, y_train = build_x_y(1000, nfeat)

            obs = dict(n_obs=n, nfeat=nfeat)

            fct1, fct2, fct3, fct4 = fcts_model(X_train, y_train)

            # creates different inputs to avoid caching in any ways
            Xs = []
            Xpolys = []
            for r in range(repeat):
                X, y = build_x_y(n, nfeat)
                Xs.append((X, y))
                Xpolys.append((PolynomialFeatures().fit_transform(X), y))

            # measure fct1
            r = len(Xs)
            st = time()
            for X, y in Xpolys:
                fct1(X, y)
            end = time()
            obs["time_sgd"] = (end - st) / r
            res.append(obs)

            # measures fct2
            st = time()
            for X, y in Xs:
                fct2(X, y)
            end = time()
            obs["time_pipe_skl"] = (end - st) / r
            res.append(obs)

            # measures fct3
            st = time()
            for X, y in Xs:
                fct3(X, y)
            end = time()
            obs["time_pipe_fast"] = (end - st) / r
            res.append(obs)

            # measures fct4
            st = time()
            for X, y in Xs:
                fct4(X, y)
            end = time()
            obs["time_pipe_slow"] = (end - st) / r
            res.append(obs)

            if verbose and (len(res) % 1 == 0 or n >= 10000):
                print("bench", len(res), ":", obs)

    return res

Plots

def plot_results(df, verbose=False):
    nrows = max(len(set(df.nfeat)), 2)
    ncols = max(1, 2)
    fig, ax = plt.subplots(nrows, ncols,
                           figsize=(nrows * 4, ncols * 4))
    colors = "gbry"
    row = 0
    for nfeat in sorted(set(df.nfeat)):
        pos = 0
        for _ in range(1):
            a = ax[row, pos]
            if row == ax.shape[0] - 1:
                a.set_xlabel("N observations", fontsize='x-small')
            if pos == 0:
                a.set_ylabel("Time (s) nfeat={}".format(nfeat),
                             fontsize='x-small')

            subset = df[df.nfeat == nfeat]
            if subset.shape[0] == 0:
                continue
            subset = subset.sort_values("n_obs")
            if verbose:
                print(subset)

            label = "SGD"
            subset.plot(x="n_obs", y="time_sgd", label=label, ax=a,
                        logx=True, logy=True, c=colors[0], style='--')
            label = "SGD-SKL"
            subset.plot(x="n_obs", y="time_pipe_skl", label=label, ax=a,
                        logx=True, logy=True, c=colors[1], style='--')
            label = "SGD-FAST"
            subset.plot(x="n_obs", y="time_pipe_fast", label=label, ax=a,
                        logx=True, logy=True, c=colors[2])
            label = "SGD-SLOW"
            subset.plot(x="n_obs", y="time_pipe_slow", label=label, ax=a,
                        logx=True, logy=True, c=colors[3])

            a.legend(loc=0, fontsize='x-small')
            if row == 0:
                a.set_title("--", fontsize='x-small')
            pos += 1
        row += 1

    plt.suptitle("Benchmark for Polynomial with SGDClassifier", fontsize=16)

Final function for the benchmark

def run_bench(repeat=100, verbose=False):
    n_obs = [10, 100, 1000]
    n_features = [5, 10, 50]

    with sklearn.config_context(assume_finite=True):
        start = time()
        results = bench(n_obs, n_features, repeat=repeat, verbose=verbose)
        end = time()

    results_df = pandas.DataFrame(results)
    print("Total time = %0.3f sec\n" % (end - start))

    # plot the results
    plot_results(results_df, verbose=verbose)
    return results_df

Run the benchmark

print("numpy:", numpy.__version__)
print("scikit-learn:", sklearn.__version__)
df = run_bench(verbose=True)
print(df)

plt.show()
Benchmark for Polynomial with SGDClassifier, --
numpy: 1.23.3
scikit-learn: 1.1.1
bench 4 : {'n_obs': 10, 'nfeat': 5, 'time_sgd': 0.0008497024097596295, 'time_pipe_skl': 0.001282125809811987, 'time_pipe_fast': 0.001079227679874748, 'time_pipe_slow': 0.002118633950012736}
bench 8 : {'n_obs': 10, 'nfeat': 10, 'time_sgd': 0.0008550194598501549, 'time_pipe_skl': 0.0014594218900310808, 'time_pipe_fast': 0.0012494045399944298, 'time_pipe_slow': 0.004546432250062935}
bench 12 : {'n_obs': 10, 'nfeat': 50, 'time_sgd': 0.0010264409202500246, 'time_pipe_skl': 0.003028022260114085, 'time_pipe_fast': 0.0028423740598373117, 'time_pipe_slow': 0.07259456361003686}
bench 16 : {'n_obs': 100, 'nfeat': 5, 'time_sgd': 0.0009067429398419335, 'time_pipe_skl': 0.0014109204802662135, 'time_pipe_fast': 0.0012179115600883961, 'time_pipe_slow': 0.0022448893601540476}
bench 20 : {'n_obs': 100, 'nfeat': 10, 'time_sgd': 0.0009762415298609995, 'time_pipe_skl': 0.0017381886497605593, 'time_pipe_fast': 0.0015325305398437195, 'time_pipe_slow': 0.004878453559940681}
bench 24 : {'n_obs': 100, 'nfeat': 50, 'time_sgd': 0.0022738387700519526, 'time_pipe_skl': 0.005627139610005542, 'time_pipe_fast': 0.005384678380214609, 'time_pipe_slow': 0.08106288868992123}
bench 28 : {'n_obs': 1000, 'nfeat': 5, 'time_sgd': 0.0016971248600748368, 'time_pipe_skl': 0.0025622724200366066, 'time_pipe_fast': 0.002320328690111637, 'time_pipe_slow': 0.003338259599986486}
bench 32 : {'n_obs': 1000, 'nfeat': 10, 'time_sgd': 0.0023074036298203282, 'time_pipe_skl': 0.004175041140115354, 'time_pipe_fast': 0.0039023695301148107, 'time_pipe_slow': 0.0073684672202216465}
bench 36 : {'n_obs': 1000, 'nfeat': 50, 'time_sgd': 0.012888124820019584, 'time_pipe_skl': 0.039682799159782005, 'time_pipe_fast': 0.0431872425597976, 'time_pipe_slow': 0.12080329265998443}
Total time = 58.756 sec

    n_obs  nfeat  time_sgd  time_pipe_skl  time_pipe_fast  time_pipe_slow
0      10      5  0.000850       0.001282        0.001079        0.002119
1      10      5  0.000850       0.001282        0.001079        0.002119
2      10      5  0.000850       0.001282        0.001079        0.002119
3      10      5  0.000850       0.001282        0.001079        0.002119
12    100      5  0.000907       0.001411        0.001218        0.002245
13    100      5  0.000907       0.001411        0.001218        0.002245
14    100      5  0.000907       0.001411        0.001218        0.002245
15    100      5  0.000907       0.001411        0.001218        0.002245
24   1000      5  0.001697       0.002562        0.002320        0.003338
25   1000      5  0.001697       0.002562        0.002320        0.003338
26   1000      5  0.001697       0.002562        0.002320        0.003338
27   1000      5  0.001697       0.002562        0.002320        0.003338
    n_obs  nfeat  time_sgd  time_pipe_skl  time_pipe_fast  time_pipe_slow
4      10     10  0.000855       0.001459        0.001249        0.004546
5      10     10  0.000855       0.001459        0.001249        0.004546
6      10     10  0.000855       0.001459        0.001249        0.004546
7      10     10  0.000855       0.001459        0.001249        0.004546
16    100     10  0.000976       0.001738        0.001533        0.004878
17    100     10  0.000976       0.001738        0.001533        0.004878
18    100     10  0.000976       0.001738        0.001533        0.004878
19    100     10  0.000976       0.001738        0.001533        0.004878
28   1000     10  0.002307       0.004175        0.003902        0.007368
29   1000     10  0.002307       0.004175        0.003902        0.007368
30   1000     10  0.002307       0.004175        0.003902        0.007368
31   1000     10  0.002307       0.004175        0.003902        0.007368
    n_obs  nfeat  time_sgd  time_pipe_skl  time_pipe_fast  time_pipe_slow
8      10     50  0.001026       0.003028        0.002842        0.072595
9      10     50  0.001026       0.003028        0.002842        0.072595
10     10     50  0.001026       0.003028        0.002842        0.072595
11     10     50  0.001026       0.003028        0.002842        0.072595
20    100     50  0.002274       0.005627        0.005385        0.081063
21    100     50  0.002274       0.005627        0.005385        0.081063
22    100     50  0.002274       0.005627        0.005385        0.081063
23    100     50  0.002274       0.005627        0.005385        0.081063
32   1000     50  0.012888       0.039683        0.043187        0.120803
33   1000     50  0.012888       0.039683        0.043187        0.120803
34   1000     50  0.012888       0.039683        0.043187        0.120803
35   1000     50  0.012888       0.039683        0.043187        0.120803
    n_obs  nfeat  time_sgd  time_pipe_skl  time_pipe_fast  time_pipe_slow
0      10      5  0.000850       0.001282        0.001079        0.002119
1      10      5  0.000850       0.001282        0.001079        0.002119
2      10      5  0.000850       0.001282        0.001079        0.002119
3      10      5  0.000850       0.001282        0.001079        0.002119
4      10     10  0.000855       0.001459        0.001249        0.004546
5      10     10  0.000855       0.001459        0.001249        0.004546
6      10     10  0.000855       0.001459        0.001249        0.004546
7      10     10  0.000855       0.001459        0.001249        0.004546
8      10     50  0.001026       0.003028        0.002842        0.072595
9      10     50  0.001026       0.003028        0.002842        0.072595
10     10     50  0.001026       0.003028        0.002842        0.072595
11     10     50  0.001026       0.003028        0.002842        0.072595
12    100      5  0.000907       0.001411        0.001218        0.002245
13    100      5  0.000907       0.001411        0.001218        0.002245
14    100      5  0.000907       0.001411        0.001218        0.002245
15    100      5  0.000907       0.001411        0.001218        0.002245
16    100     10  0.000976       0.001738        0.001533        0.004878
17    100     10  0.000976       0.001738        0.001533        0.004878
18    100     10  0.000976       0.001738        0.001533        0.004878
19    100     10  0.000976       0.001738        0.001533        0.004878
20    100     50  0.002274       0.005627        0.005385        0.081063
21    100     50  0.002274       0.005627        0.005385        0.081063
22    100     50  0.002274       0.005627        0.005385        0.081063
23    100     50  0.002274       0.005627        0.005385        0.081063
24   1000      5  0.001697       0.002562        0.002320        0.003338
25   1000      5  0.001697       0.002562        0.002320        0.003338
26   1000      5  0.001697       0.002562        0.002320        0.003338
27   1000      5  0.001697       0.002562        0.002320        0.003338
28   1000     10  0.002307       0.004175        0.003902        0.007368
29   1000     10  0.002307       0.004175        0.003902        0.007368
30   1000     10  0.002307       0.004175        0.003902        0.007368
31   1000     10  0.002307       0.004175        0.003902        0.007368
32   1000     50  0.012888       0.039683        0.043187        0.120803
33   1000     50  0.012888       0.039683        0.043187        0.120803
34   1000     50  0.012888       0.039683        0.043187        0.120803
35   1000     50  0.012888       0.039683        0.043187        0.120803

Total running time of the script: ( 1 minutes 3.456 seconds)

Gallery generated by Sphinx-Gallery