Keras 3 API 文档 / 工具类 / Scikit-Learn API 包装器

Scikit-Learn API 包装器

[源代码]

SKLearnClassifier

keras.wrappers.SKLearnClassifier(
    model, warm_start=False, model_kwargs=None, fit_kwargs=None
)

scikit-learn 兼容的 Keras 模型分类器包装器。

请注意,模型初始化和训练中存在随机性来源。请参阅 Keras 模型的可复现性,了解如何控制随机性。

参数

  • model: ModelModel 的一个实例,或返回此类对象的调用对象。请注意,如果输入是 Model,它将在拟合前使用 keras.models.clone_model 克隆,除非 warm_start=TrueModel 实例需要已编译。如果为调用对象,则它必须至少接受 Xy 作为关键字参数。如果用户通过 model_kwargs 传递其他参数,则必须接受。
  • warm_start: bool,默认为 False。是否重用上一次拟合的模型权重。如果为 True,则不会克隆给定的模型,并且会重用上一次拟合的权重。
  • model_kwargs: dict,默认为 None。传递给 model 的关键字参数,如果 model 是可调用对象的话。
  • fit_kwargs: dict,默认为 None。传递给 model.fit 的关键字参数。这些参数也可以直接传递给 scikit-learn 包装器的 fit 方法。直接传递给 fit 方法的值优先于这些参数。

属性

  • model_ : Model 拟合后的模型。
  • history_ : dict 拟合历史记录,由 model.fit 返回。
  • classes_ : array-like, shape=(n_classes,) 类标签。

示例

这里我们使用一个函数,该函数动态创建基本的 MLP 模型,并选择输入和输出形状。我们将使用它来创建我们的 scikit-learn 模型。

from keras.layers import Dense, Input
from keras.models import Model

def dynamic_model(X, y, loss, layers=[10]):
    # Creates a basic MLP model dynamically choosing the input and
    # output shapes.
    n_features_in = X.shape[1]
    inp = Input(shape=(n_features_in,))

    hidden = inp
    for layer_size in layers:
        hidden = Dense(layer_size, activation="relu")(hidden)

    n_outputs = y.shape[1] if len(y.shape) > 1 else 1
    out = Dense(n_outputs, activation="softmax")(hidden)
    model = Model(inp, out)
    model.compile(loss=loss, optimizer="rmsprop")

    return model

然后,您可以使用此函数创建 scikit-learn 兼容的模型,并用一些数据对其进行拟合。

from sklearn.datasets import make_classification
from keras.wrappers import SKLearnClassifier

X, y = make_classification(n_samples=1000, n_features=10)
est = SKLearnClassifier(
    model=dynamic_model,
    model_kwargs={
        "loss": "categorical_crossentropy",
        "layers": [20, 20, 20],
    },
)

est.fit(X, y, epochs=5)

[源代码]

SKLearnRegressor

keras.wrappers.SKLearnRegressor(
    model, warm_start=False, model_kwargs=None, fit_kwargs=None
)

scikit-learn 兼容的 Keras 模型回归器包装器。

请注意,模型初始化和训练中存在随机性来源。请参阅 Keras 模型的可复现性,了解如何控制随机性。

参数

  • model: ModelModel 的一个实例,或返回此类对象的调用对象。请注意,如果输入是 Model,它将在拟合前使用 keras.models.clone_model 克隆,除非 warm_start=TrueModel 实例需要已编译。如果为调用对象,则它必须至少接受 Xy 作为关键字参数。如果用户通过 model_kwargs 传递其他参数,则必须接受。
  • warm_start: bool,默认为 False。是否重用上一次拟合的模型权重。如果为 True,则不会克隆给定的模型,并且会重用上一次拟合的权重。
  • model_kwargs: dict,默认为 None。传递给 model 的关键字参数,如果 model 是可调用对象的话。
  • fit_kwargs: dict,默认为 None。传递给 model.fit 的关键字参数。这些参数也可以直接传递给 scikit-learn 包装器的 fit 方法。直接传递给 fit 方法的值优先于这些参数。

属性

  • model_ : Model 拟合后的模型。

示例

这里我们使用一个函数,该函数动态创建基本的 MLP 模型,并选择输入和输出形状。我们将使用它来创建我们的 scikit-learn 模型。

from keras.layers import Dense, Input
from keras.models import Model

def dynamic_model(X, y, loss, layers=[10]):
    # Creates a basic MLP model dynamically choosing the input and
    # output shapes.
    n_features_in = X.shape[1]
    inp = Input(shape=(n_features_in,))

    hidden = inp
    for layer_size in layers:
        hidden = Dense(layer_size, activation="relu")(hidden)

    n_outputs = y.shape[1] if len(y.shape) > 1 else 1
    out = Dense(n_outputs)(hidden)
    model = Model(inp, out)
    model.compile(loss=loss, optimizer="rmsprop")

    return model

然后,您可以使用此函数创建 scikit-learn 兼容的模型,并用一些数据对其进行拟合。

from sklearn.datasets import make_regression
from keras.wrappers import SKLearnRegressor

X, y = make_regression(n_samples=1000, n_features=10)
est = SKLearnRegressor(
    model=dynamic_model,
    model_kwargs={
        "loss": "mse",
        "layers": [20, 20, 20],
    },
)

est.fit(X, y, epochs=5)

[源代码]

SKLearnTransformer

keras.wrappers.SKLearnTransformer(
    model, warm_start=False, model_kwargs=None, fit_kwargs=None
)

scikit-learn 兼容的 Keras 模型转换器包装器。

请注意,这是一个 scikit-learn 兼容的转换器,而不是深度学习意义上的转换器。

另外请注意,模型初始化和训练中存在随机性来源。请参阅 Keras 模型的可复现性,了解如何控制随机性。

参数

  • model: ModelModel 的一个实例,或返回此类对象的调用对象。请注意,如果输入是 Model,它将在拟合前使用 keras.models.clone_model 克隆,除非 warm_start=TrueModel 实例需要已编译。如果为调用对象,则它必须至少接受 Xy 作为关键字参数。如果用户通过 model_kwargs 传递其他参数,则必须接受。
  • warm_start: bool,默认为 False。是否重用上一次拟合的模型权重。如果为 True,则不会克隆给定的模型,并且会重用上一次拟合的权重。
  • model_kwargs: dict,默认为 None。传递给 model 的关键字参数,如果 model 是可调用对象的话。
  • fit_kwargs: dict,默认为 None。传递给 model.fit 的关键字参数。这些参数也可以直接传递给 scikit-learn 包装器的 fit 方法。直接传递给 fit 方法的值优先于这些参数。

属性

  • model_ : Model 拟合后的模型。
  • history_ : dict 拟合历史记录,由 model.fit 返回。

示例

scikit-learn 转换器的一个常见用例是包含一个能为您提供数据嵌入的步骤。这里我们假设 my_package.my_model 是一个 Keras 模型,它接受输入并生成数据的嵌入,而 my_package.my_data 是您的数据集加载器。

from my_package import my_model, my_data
from keras.wrappers import SKLearnTransformer
from sklearn.frozen import FrozenEstimator # requires scikit-learn>=1.6
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import HistGradientBoostingClassifier

X, y = my_data()

trs = FrozenEstimator(SKLearnTransformer(model=my_model))
pipe = make_pipeline(trs, HistGradientBoostingClassifier())
pipe.fit(X, y)

请注意,在上面的示例中,FrozenEstimator 可防止管道中的转换器步骤进行任何进一步的训练,如果您不想更改当前嵌入模型,这是一种可能的情况。