Module keras.api.keras.wrappers.scikit_learn

Public API for tf.keras.wrappers.scikit_learn namespace.

Expand source code
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.keras.wrappers.scikit_learn namespace.
"""

from __future__ import print_function as _print_function

import sys as _sys

from keras.wrappers.scikit_learn import KerasClassifier
from keras.wrappers.scikit_learn import KerasRegressor

del _print_function

from tensorflow.python.util import module_wrapper as _module_wrapper

if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):
  _sys.modules[__name__] = _module_wrapper.TFModuleWrapper(
      _sys.modules[__name__], "keras.wrappers.scikit_learn", public_apis=None, deprecation=True,
      has_lite=False)

Classes

class KerasClassifier (build_fn=None, **sk_params)

Implementation of the scikit-learn classifier API for Keras.

Expand source code
class KerasClassifier(BaseWrapper):
  """Implementation of the scikit-learn classifier API for Keras.
  """

  def fit(self, x, y, **kwargs):
    """Constructs a new model with `build_fn` & fit the model to `(x, y)`.

    Args:
        x : array-like, shape `(n_samples, n_features)`
            Training samples where `n_samples` is the number of samples
            and `n_features` is the number of features.
        y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
            True labels for `x`.
        **kwargs: dictionary arguments
            Legal arguments are the arguments of `Sequential.fit`

    Returns:
        history : object
            details about the training history at each epoch.

    Raises:
        ValueError: In case of invalid shape for `y` argument.
    """
    y = np.array(y)
    if len(y.shape) == 2 and y.shape[1] > 1:
      self.classes_ = np.arange(y.shape[1])
    elif (len(y.shape) == 2 and y.shape[1] == 1) or len(y.shape) == 1:
      self.classes_ = np.unique(y)
      y = np.searchsorted(self.classes_, y)
    else:
      raise ValueError('Invalid shape for y: ' + str(y.shape))
    self.n_classes_ = len(self.classes_)
    return super(KerasClassifier, self).fit(x, y, **kwargs)

  def predict(self, x, **kwargs):
    """Returns the class predictions for the given test data.

    Args:
        x: array-like, shape `(n_samples, n_features)`
            Test samples where `n_samples` is the number of samples
            and `n_features` is the number of features.
        **kwargs: dictionary arguments
            Legal arguments are the arguments
            of `Sequential.predict`.

    Returns:
        preds: array-like, shape `(n_samples,)`
            Class predictions.
    """
    proba = self.model.predict(x, **kwargs)
    if proba.shape[-1] > 1:
      classes = proba.argmax(axis=-1)
    else:
      classes = (proba > 0.5).astype('int32')
    return self.classes_[classes]

  def predict_proba(self, x, **kwargs):
    """Returns class probability estimates for the given test data.

    Args:
        x: array-like, shape `(n_samples, n_features)`
            Test samples where `n_samples` is the number of samples
            and `n_features` is the number of features.
        **kwargs: dictionary arguments
            Legal arguments are the arguments
            of `Sequential.predict`.

    Returns:
        proba: array-like, shape `(n_samples, n_outputs)`
            Class probability estimates.
            In the case of binary classification,
            to match the scikit-learn API,
            will return an array of shape `(n_samples, 2)`
            (instead of `(n_sample, 1)` as in Keras).
    """
    probs = self.model.predict(x, **kwargs)

    # check if binary classification
    if probs.shape[1] == 1:
      # first column is probability of class 0 and second is of class 1
      probs = np.hstack([1 - probs, probs])
    return probs

  def score(self, x, y, **kwargs):
    """Returns the mean accuracy on the given test data and labels.

    Args:
        x: array-like, shape `(n_samples, n_features)`
            Test samples where `n_samples` is the number of samples
            and `n_features` is the number of features.
        y: array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
            True labels for `x`.
        **kwargs: dictionary arguments
            Legal arguments are the arguments of `Sequential.evaluate`.

    Returns:
        score: float
            Mean accuracy of predictions on `x` wrt. `y`.

    Raises:
        ValueError: If the underlying model isn't configured to
            compute accuracy. You should pass `metrics=["accuracy"]` to
            the `.compile()` method of the model.
    """
    y = np.searchsorted(self.classes_, y)
    kwargs = self.filter_sk_params(Sequential.evaluate, kwargs)

    loss_name = self.model.loss
    if hasattr(loss_name, '__name__'):
      loss_name = loss_name.__name__
    if loss_name == 'categorical_crossentropy' and len(y.shape) != 2:
      y = to_categorical(y)

    outputs = self.model.evaluate(x, y, **kwargs)
    if not isinstance(outputs, list):
      outputs = [outputs]
    for name, output in zip(self.model.metrics_names, outputs):
      if name in ['accuracy', 'acc']:
        return output
    raise ValueError('The model is not configured to compute accuracy. '
                     'You should pass `metrics=["accuracy"]` to '
                     'the `model.compile()` method.')

Ancestors

Methods

def fit(self, x, y, **kwargs)

Constructs a new model with build_fn & fit the model to (x, y).

Args

x : array-like, shape (n_samples, n_features)
Training samples where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape (n_samples,) or (n_samples, n_outputs)
True labels for x.
**kwargs
dictionary arguments Legal arguments are the arguments of Sequential.fit

Returns

history
object details about the training history at each epoch.

Raises

ValueError
In case of invalid shape for y argument.
Expand source code
def fit(self, x, y, **kwargs):
  """Constructs a new model with `build_fn` & fit the model to `(x, y)`.

  Args:
      x : array-like, shape `(n_samples, n_features)`
          Training samples where `n_samples` is the number of samples
          and `n_features` is the number of features.
      y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
          True labels for `x`.
      **kwargs: dictionary arguments
          Legal arguments are the arguments of `Sequential.fit`

  Returns:
      history : object
          details about the training history at each epoch.

  Raises:
      ValueError: In case of invalid shape for `y` argument.
  """
  y = np.array(y)
  if len(y.shape) == 2 and y.shape[1] > 1:
    self.classes_ = np.arange(y.shape[1])
  elif (len(y.shape) == 2 and y.shape[1] == 1) or len(y.shape) == 1:
    self.classes_ = np.unique(y)
    y = np.searchsorted(self.classes_, y)
  else:
    raise ValueError('Invalid shape for y: ' + str(y.shape))
  self.n_classes_ = len(self.classes_)
  return super(KerasClassifier, self).fit(x, y, **kwargs)
def predict(self, x, **kwargs)

Returns the class predictions for the given test data.

Args

x
array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
**kwargs
dictionary arguments Legal arguments are the arguments of Sequential.predict.

Returns

preds
array-like, shape (n_samples,) Class predictions.
Expand source code
def predict(self, x, **kwargs):
  """Returns the class predictions for the given test data.

  Args:
      x: array-like, shape `(n_samples, n_features)`
          Test samples where `n_samples` is the number of samples
          and `n_features` is the number of features.
      **kwargs: dictionary arguments
          Legal arguments are the arguments
          of `Sequential.predict`.

  Returns:
      preds: array-like, shape `(n_samples,)`
          Class predictions.
  """
  proba = self.model.predict(x, **kwargs)
  if proba.shape[-1] > 1:
    classes = proba.argmax(axis=-1)
  else:
    classes = (proba > 0.5).astype('int32')
  return self.classes_[classes]
def predict_proba(self, x, **kwargs)

Returns class probability estimates for the given test data.

Args

x
array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
**kwargs
dictionary arguments Legal arguments are the arguments of Sequential.predict.

Returns

proba
array-like, shape (n_samples, n_outputs) Class probability estimates. In the case of binary classification, to match the scikit-learn API, will return an array of shape (n_samples, 2) (instead of (n_sample, 1) as in Keras).
Expand source code
def predict_proba(self, x, **kwargs):
  """Returns class probability estimates for the given test data.

  Args:
      x: array-like, shape `(n_samples, n_features)`
          Test samples where `n_samples` is the number of samples
          and `n_features` is the number of features.
      **kwargs: dictionary arguments
          Legal arguments are the arguments
          of `Sequential.predict`.

  Returns:
      proba: array-like, shape `(n_samples, n_outputs)`
          Class probability estimates.
          In the case of binary classification,
          to match the scikit-learn API,
          will return an array of shape `(n_samples, 2)`
          (instead of `(n_sample, 1)` as in Keras).
  """
  probs = self.model.predict(x, **kwargs)

  # check if binary classification
  if probs.shape[1] == 1:
    # first column is probability of class 0 and second is of class 1
    probs = np.hstack([1 - probs, probs])
  return probs
def score(self, x, y, **kwargs)

Returns the mean accuracy on the given test data and labels.

Args

x
array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
y
array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
**kwargs
dictionary arguments Legal arguments are the arguments of Sequential.evaluate.

Returns

score
float Mean accuracy of predictions on x wrt. y.

Raises

ValueError
If the underlying model isn't configured to compute accuracy. You should pass metrics=["accuracy"] to the .compile() method of the model.
Expand source code
def score(self, x, y, **kwargs):
  """Returns the mean accuracy on the given test data and labels.

  Args:
      x: array-like, shape `(n_samples, n_features)`
          Test samples where `n_samples` is the number of samples
          and `n_features` is the number of features.
      y: array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
          True labels for `x`.
      **kwargs: dictionary arguments
          Legal arguments are the arguments of `Sequential.evaluate`.

  Returns:
      score: float
          Mean accuracy of predictions on `x` wrt. `y`.

  Raises:
      ValueError: If the underlying model isn't configured to
          compute accuracy. You should pass `metrics=["accuracy"]` to
          the `.compile()` method of the model.
  """
  y = np.searchsorted(self.classes_, y)
  kwargs = self.filter_sk_params(Sequential.evaluate, kwargs)

  loss_name = self.model.loss
  if hasattr(loss_name, '__name__'):
    loss_name = loss_name.__name__
  if loss_name == 'categorical_crossentropy' and len(y.shape) != 2:
    y = to_categorical(y)

  outputs = self.model.evaluate(x, y, **kwargs)
  if not isinstance(outputs, list):
    outputs = [outputs]
  for name, output in zip(self.model.metrics_names, outputs):
    if name in ['accuracy', 'acc']:
      return output
  raise ValueError('The model is not configured to compute accuracy. '
                   'You should pass `metrics=["accuracy"]` to '
                   'the `model.compile()` method.')

Inherited members

class KerasRegressor (build_fn=None, **sk_params)

Implementation of the scikit-learn regressor API for Keras.

Expand source code
class KerasRegressor(BaseWrapper):
  """Implementation of the scikit-learn regressor API for Keras.
  """

  def predict(self, x, **kwargs):
    """Returns predictions for the given test data.

    Args:
        x: array-like, shape `(n_samples, n_features)`
            Test samples where `n_samples` is the number of samples
            and `n_features` is the number of features.
        **kwargs: dictionary arguments
            Legal arguments are the arguments of `Sequential.predict`.

    Returns:
        preds: array-like, shape `(n_samples,)`
            Predictions.
    """
    kwargs = self.filter_sk_params(Sequential.predict, kwargs)
    return np.squeeze(self.model.predict(x, **kwargs))

  def score(self, x, y, **kwargs):
    """Returns the mean loss on the given test data and labels.

    Args:
        x: array-like, shape `(n_samples, n_features)`
            Test samples where `n_samples` is the number of samples
            and `n_features` is the number of features.
        y: array-like, shape `(n_samples,)`
            True labels for `x`.
        **kwargs: dictionary arguments
            Legal arguments are the arguments of `Sequential.evaluate`.

    Returns:
        score: float
            Mean accuracy of predictions on `x` wrt. `y`.
    """
    kwargs = self.filter_sk_params(Sequential.evaluate, kwargs)
    loss = self.model.evaluate(x, y, **kwargs)
    if isinstance(loss, list):
      return -loss[0]
    return -loss

Ancestors

Methods

def predict(self, x, **kwargs)

Returns predictions for the given test data.

Args

x
array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
**kwargs
dictionary arguments Legal arguments are the arguments of Sequential.predict.

Returns

preds
array-like, shape (n_samples,) Predictions.
Expand source code
def predict(self, x, **kwargs):
  """Returns predictions for the given test data.

  Args:
      x: array-like, shape `(n_samples, n_features)`
          Test samples where `n_samples` is the number of samples
          and `n_features` is the number of features.
      **kwargs: dictionary arguments
          Legal arguments are the arguments of `Sequential.predict`.

  Returns:
      preds: array-like, shape `(n_samples,)`
          Predictions.
  """
  kwargs = self.filter_sk_params(Sequential.predict, kwargs)
  return np.squeeze(self.model.predict(x, **kwargs))
def score(self, x, y, **kwargs)

Returns the mean loss on the given test data and labels.

Args

x
array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
y
array-like, shape (n_samples,) True labels for x.
**kwargs
dictionary arguments Legal arguments are the arguments of Sequential.evaluate.

Returns

score
float Mean accuracy of predictions on x wrt. y.
Expand source code
def score(self, x, y, **kwargs):
  """Returns the mean loss on the given test data and labels.

  Args:
      x: array-like, shape `(n_samples, n_features)`
          Test samples where `n_samples` is the number of samples
          and `n_features` is the number of features.
      y: array-like, shape `(n_samples,)`
          True labels for `x`.
      **kwargs: dictionary arguments
          Legal arguments are the arguments of `Sequential.evaluate`.

  Returns:
      score: float
          Mean accuracy of predictions on `x` wrt. `y`.
  """
  kwargs = self.filter_sk_params(Sequential.evaluate, kwargs)
  loss = self.model.evaluate(x, y, **kwargs)
  if isinstance(loss, list):
    return -loss[0]
  return -loss

Inherited members