Esempio n. 1
0
  def testTrainRegressorNonInMemory(self):
    ops.reset_default_graph()
    expected_first, expected_second, expected_third = (
        self._get_expected_ensembles_for_regression())
    with self.test_session() as sess:
      # Train without train_in_memory mode.
      with sess.graph.as_default():
        train_op, ensemble_serialized = self._get_train_op_and_ensemble(
            boosted_trees._create_regression_head(label_dimension=1),
            run_config.RunConfig(),
            is_classification=False,
            train_in_memory=False)
      _, serialized = sess.run([train_op, ensemble_serialized])
      # Validate the trained ensemble.
      ensemble_proto = boosted_trees_pb2.TreeEnsemble()
      ensemble_proto.ParseFromString(serialized)
      self.assertProtoEquals(expected_first, ensemble_proto)

      # Run one more time and validate the trained ensemble.
      _, serialized = sess.run([train_op, ensemble_serialized])
      ensemble_proto = boosted_trees_pb2.TreeEnsemble()
      ensemble_proto.ParseFromString(serialized)
      self.assertProtoEquals(expected_second, ensemble_proto)

      # Third round training and validation.
      _, serialized = sess.run([train_op, ensemble_serialized])
      ensemble_proto = boosted_trees_pb2.TreeEnsemble()
      ensemble_proto.ParseFromString(serialized)
      self.assertProtoEquals(expected_third, ensemble_proto)
 def setUp(self):
   self._head = canned_boosted_trees._create_regression_head(label_dimension=1)
   self._feature_columns = {
       feature_column.bucketized_column(
           feature_column.numeric_column('f_%d' % i, dtype=dtypes.float32),
           BUCKET_BOUNDARIES) for i in range(NUM_FEATURES)
   }
    def testTrainRegressorNonInMemory(self):
        ops.reset_default_graph()
        expected_first, expected_second, expected_third = (
            self._get_expected_ensembles_for_regression())
        with self.test_session() as sess:
            # Train without train_in_memory mode.
            with sess.graph.as_default():
                train_op, ensemble_serialized = self._get_train_op_and_ensemble(
                    boosted_trees._create_regression_head(label_dimension=1),
                    run_config.RunConfig(),
                    is_classification=False,
                    train_in_memory=False)
            _, serialized = sess.run([train_op, ensemble_serialized])
            # Validate the trained ensemble.
            ensemble_proto = boosted_trees_pb2.TreeEnsemble()
            ensemble_proto.ParseFromString(serialized)
            self.assertProtoEquals(expected_first, ensemble_proto)

            # Run one more time and validate the trained ensemble.
            _, serialized = sess.run([train_op, ensemble_serialized])
            ensemble_proto = boosted_trees_pb2.TreeEnsemble()
            ensemble_proto.ParseFromString(serialized)
            self.assertProtoEquals(expected_second, ensemble_proto)

            # Third round training and validation.
            _, serialized = sess.run([train_op, ensemble_serialized])
            ensemble_proto = boosted_trees_pb2.TreeEnsemble()
            ensemble_proto.ParseFromString(serialized)
            self.assertProtoEquals(expected_third, ensemble_proto)
Esempio n. 4
0
 def setUp(self):
   self._head = canned_boosted_trees._create_regression_head(label_dimension=1)
   self._feature_columns = {
       feature_column.bucketized_column(
           feature_column.numeric_column('f_%d' % i, dtype=dtypes.float32),
           BUCKET_BOUNDARIES)
       for i in range(NUM_FEATURES)
   }
Esempio n. 5
0
def boosted_trees_regressor_train_in_memory(
    train_input_fn,
    feature_columns,
    model_dir=None,
    label_dimension=canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT,
    weight_column=None,
    n_trees=100,
    max_depth=6,
    learning_rate=0.1,
    l1_regularization=0.,
    l2_regularization=0.,
    tree_complexity=0.,
    config=None,
    train_hooks=None):
  """Trains a boosted tree regressor with in memory dataset.

  Example:

  ```python
  bucketized_feature_1 = bucketized_column(
    numeric_column('feature_1'), BUCKET_BOUNDARIES_1)
  bucketized_feature_2 = bucketized_column(
    numeric_column('feature_2'), BUCKET_BOUNDARIES_2)

  def input_fn_train():
    dataset = create-dataset-from-training-data
    # Don't use repeat or cache, since it is assumed to be one epoch
    # This is either tf.data.Dataset, or a tuple of feature dict and label.
    return dataset

  regressor = boosted_trees_regressor_train_in_memory(
      train_input_fn,
      feature_columns=[bucketized_feature_1, bucketized_feature_2],
      n_trees=100,
      ... <some other params>
  )

  def input_fn_eval():
    ...
    return dataset

  metrics = regressor.evaluate(input_fn=input_fn_eval, steps=10)
  ```

  Args:
    train_input_fn: the input function returns a dataset containing a single
      epoch of *unbatched* features and labels.
    feature_columns: An iterable containing all the feature columns used by
      the model. All items in the set should be instances of classes derived
      from `FeatureColumn`.
    model_dir: Directory to save model parameters, graph and etc. This can
      also be used to load checkpoints from the directory into a estimator
      to continue training a previously saved model.
    label_dimension: Number of regression targets per example.
      Multi-dimensional support is not yet implemented.
    weight_column: A string or a `_NumericColumn` created by
      `tf.feature_column.numeric_column` defining feature column representing
      weights. It is used to downweight or boost examples during training. It
      will be multiplied by the loss of the example. If it is a string, it is
      used as a key to fetch weight tensor from the `features`. If it is a
      `_NumericColumn`, raw tensor is fetched by key `weight_column.key`,
      then weight_column.normalizer_fn is applied on it to get weight tensor.
    n_trees: number trees to be created.
    max_depth: maximum depth of the tree to grow.
    learning_rate: shrinkage parameter to be used when a tree added to the
      model.
    l1_regularization: regularization multiplier applied to the absolute
      weights of the tree leafs.
    l2_regularization: regularization multiplier applied to the square weights
      of the tree leafs.
    tree_complexity: regularization factor to penalize trees with more leaves.
    config: `RunConfig` object to configure the runtime settings.
    train_hooks: a list of Hook instances to be passed to estimator.train().

  Returns:
    a `BoostedTreesClassifier` instance created with the given arguments and
      trained with the data loaded up on memory from the input_fn.

  Raises:
    ValueError: when wrong arguments are given or unsupported functionalities
       are requested.
  """
  # pylint: disable=protected-access
  # TODO(nponomareva): Extend it to multi-dimension cases.
  if label_dimension == canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT:
    label_dimension = 1
  head = canned_boosted_trees._create_regression_head(label_dimension,
                                                      weight_column)

  # HParams for the model.
  tree_hparams = canned_boosted_trees._TreeHParams(
      n_trees, max_depth, learning_rate, l1_regularization, l2_regularization,
      tree_complexity)

  def _model_fn(features, labels, mode, config):
    return canned_boosted_trees._bt_model_fn(
        features,
        labels,
        mode,
        head,
        feature_columns,
        tree_hparams,
        n_batches_per_layer=1,
        config=config,
        train_in_memory=True)

  in_memory_regressor = estimator.Estimator(
      model_fn=_model_fn, model_dir=model_dir, config=config)

  in_memory_regressor.train(input_fn=train_input_fn, hooks=train_hooks)

  return in_memory_regressor
Esempio n. 6
0
def boosted_trees_regressor_train_in_memory(
    train_input_fn,
    feature_columns,
    model_dir=None,
    label_dimension=canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT,
    weight_column=None,
    n_trees=100,
    max_depth=6,
    learning_rate=0.1,
    l1_regularization=0.,
    l2_regularization=0.,
    tree_complexity=0.,
    min_node_weight=0.,
    config=None,
    train_hooks=None,
    center_bias=False,
    pruning_mode='none'):
  """Trains a boosted tree regressor with in memory dataset.

  Example:

  ```python
  bucketized_feature_1 = bucketized_column(
    numeric_column('feature_1'), BUCKET_BOUNDARIES_1)
  bucketized_feature_2 = bucketized_column(
    numeric_column('feature_2'), BUCKET_BOUNDARIES_2)

  def train_input_fn():
    dataset = create-dataset-from-training-data
    # This is tf.data.Dataset of a tuple of feature dict and label.
    #   e.g. Dataset.zip((Dataset.from_tensors({'f1': f1_array, ...}),
    #                     Dataset.from_tensors(label_array)))
    # The returned Dataset shouldn't be batched.
    # If Dataset repeats, only the first repetition would be used for training.
    return dataset

  regressor = boosted_trees_regressor_train_in_memory(
      train_input_fn,
      feature_columns=[bucketized_feature_1, bucketized_feature_2],
      n_trees=100,
      ... <some other params>
  )

  def input_fn_eval():
    ...
    return dataset

  metrics = regressor.evaluate(input_fn=input_fn_eval, steps=10)
  ```

  Args:
    train_input_fn: the input function returns a dataset containing a single
      epoch of *unbatched* features and labels.
    feature_columns: An iterable containing all the feature columns used by
      the model. All items in the set should be instances of classes derived
      from `FeatureColumn`.
    model_dir: Directory to save model parameters, graph and etc. This can
      also be used to load checkpoints from the directory into an estimator
      to continue training a previously saved model.
    label_dimension: Number of regression targets per example.
      Multi-dimensional support is not yet implemented.
    weight_column: A string or a `_NumericColumn` created by
      `tf.feature_column.numeric_column` defining feature column representing
      weights. It is used to downweight or boost examples during training. It
      will be multiplied by the loss of the example. If it is a string, it is
      used as a key to fetch weight tensor from the `features`. If it is a
      `_NumericColumn`, raw tensor is fetched by key `weight_column.key`,
      then weight_column.normalizer_fn is applied on it to get weight tensor.
    n_trees: number trees to be created.
    max_depth: maximum depth of the tree to grow.
    learning_rate: shrinkage parameter to be used when a tree added to the
      model.
    l1_regularization: regularization multiplier applied to the absolute
      weights of the tree leafs.
    l2_regularization: regularization multiplier applied to the square weights
      of the tree leafs.
    tree_complexity: regularization factor to penalize trees with more leaves.
    min_node_weight: minimum hessian a node must have for a split to be
        considered. The value will be compared with sum(leaf_hessian)/
        (batch_size * n_batches_per_layer).
    config: `RunConfig` object to configure the runtime settings.
    train_hooks: a list of Hook instances to be passed to estimator.train().
    center_bias: Whether bias centering needs to occur. Bias centering refers
        to the first node in the very first tree returning the prediction that
        is aligned with the original labels distribution. For example, for
        regression problems, the first node will return the mean of the labels.
        For binary classification problems, it will return a logit for a prior
        probability of label 1.
    pruning_mode: one of 'none', 'pre', 'post' to indicate no pruning, pre-
        pruning (do not split a node if not enough gain is observed) and post
        pruning (build the tree up to a max depth and then prune branches with
        negative gain). For pre and post pruning, you MUST provide
        tree_complexity >0.

  Returns:
    a `BoostedTreesClassifier` instance created with the given arguments and
      trained with the data loaded up on memory from the input_fn.

  Raises:
    ValueError: when wrong arguments are given or unsupported functionalities
       are requested.
  """
  # pylint: disable=protected-access
  # TODO(nponomareva): Extend it to multi-dimension cases.
  if label_dimension == canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT:
    label_dimension = 1
  head = canned_boosted_trees._create_regression_head(label_dimension,
                                                      weight_column)

  # HParams for the model.
  tree_hparams = canned_boosted_trees._TreeHParams(
      n_trees, max_depth, learning_rate, l1_regularization, l2_regularization,
      tree_complexity, min_node_weight, center_bias, pruning_mode)

  def _model_fn(features, labels, mode, config):
    return canned_boosted_trees._bt_model_fn(
        features,
        labels,
        mode,
        head,
        feature_columns,
        tree_hparams,
        n_batches_per_layer=1,
        config=config,
        train_in_memory=True)

  in_memory_regressor = estimator.Estimator(
      model_fn=_model_fn, model_dir=model_dir, config=config)

  in_memory_regressor.train(
      input_fn=_validate_input_fn_and_repeat_dataset(train_input_fn),
      hooks=train_hooks)

  return in_memory_regressor
    def testContribEstimatorThatDFCIsInPredictions(self):
        # pylint:disable=protected-access
        head = canned_boosted_trees._create_regression_head(label_dimension=1)
        train_input_fn = _make_train_input_fn(is_classification=False)
        predict_input_fn = numpy_io.numpy_input_fn(x=FEATURES_DICT,
                                                   y=None,
                                                   batch_size=1,
                                                   num_epochs=1,
                                                   shuffle=False)

        est = boosted_trees._BoostedTreesEstimator(
            feature_columns=self._feature_columns,
            n_batches_per_layer=1,
            head=head,
            n_trees=1,
            max_depth=5,
            center_bias=True)
        # pylint:enable=protected-access

        num_steps = 100
        # Train for a few steps. Validate debug outputs in prediction dicts.
        est.train(train_input_fn, steps=num_steps)
        debug_predictions = est.experimental_predict_with_explanations(
            predict_input_fn)
        biases, dfcs = zip(*[(pred['bias'], pred['dfc'])
                             for pred in debug_predictions])
        self.assertAllClose([1.8] * 5, biases)
        self.assertAllClose(({
            0: -0.070499420166015625,
            1: -0.095000028610229492,
            2: 0.0
        }, {
            0: -0.53763031959533691,
            1: 0.063333392143249512,
            2: 0.0
        }, {
            0: -0.51756942272186279,
            1: -0.095000028610229492,
            2: 0.0
        }, {
            0: 0.1563495397567749,
            1: 0.063333392143249512,
            2: 0.0
        }, {
            0: 0.96934974193572998,
            1: 0.063333392143249512,
            2: 0.0
        }), dfcs)

        # Assert sum(dfcs) + bias == predictions.
        expected_predictions = [[1.6345005], [1.32570302], [1.1874305],
                                [2.01968288], [2.83268309]]
        predictions = [[sum(dfc.values()) + bias]
                       for (dfc, bias) in zip(dfcs, biases)]
        self.assertAllClose(expected_predictions, predictions)

        # Test when user doesn't include bias or dfc in predict_keys.
        debug_predictions = est.experimental_predict_with_explanations(
            predict_input_fn, predict_keys=['predictions'])
        for prediction_dict in debug_predictions:
            self.assertTrue('bias' in prediction_dict)
            self.assertTrue('dfc' in prediction_dict)
            self.assertTrue('predictions' in prediction_dict)
            self.assertEqual(len(prediction_dict), 3)
Esempio n. 8
0
def boosted_trees_regressor_train_in_memory(
        train_input_fn,
        feature_columns,
        model_dir=None,
        label_dimension=canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT,
        weight_column=None,
        n_trees=100,
        max_depth=6,
        learning_rate=0.1,
        l1_regularization=0.,
        l2_regularization=0.,
        tree_complexity=0.,
        min_node_weight=0.,
        config=None,
        train_hooks=None,
        center_bias=False,
        pruning_mode='none'):
    """Trains a boosted tree regressor with in memory dataset.

  Example:

  ```python
  bucketized_feature_1 = bucketized_column(
    numeric_column('feature_1'), BUCKET_BOUNDARIES_1)
  bucketized_feature_2 = bucketized_column(
    numeric_column('feature_2'), BUCKET_BOUNDARIES_2)

  def train_input_fn():
    dataset = create-dataset-from-training-data
    # This is tf.data.Dataset of a tuple of feature dict and label.
    #   e.g. Dataset.zip((Dataset.from_tensors({'f1': f1_array, ...}),
    #                     Dataset.from_tensors(label_array)))
    # The returned Dataset shouldn't be batched.
    # If Dataset repeats, only the first repetition would be used for training.
    return dataset

  regressor = boosted_trees_regressor_train_in_memory(
      train_input_fn,
      feature_columns=[bucketized_feature_1, bucketized_feature_2],
      n_trees=100,
      ... <some other params>
  )

  def input_fn_eval():
    ...
    return dataset

  metrics = regressor.evaluate(input_fn=input_fn_eval, steps=10)
  ```

  Args:
    train_input_fn: the input function returns a dataset containing a single
      epoch of *unbatched* features and labels.
    feature_columns: An iterable containing all the feature columns used by
      the model. All items in the set should be instances of classes derived
      from `FeatureColumn`.
    model_dir: Directory to save model parameters, graph and etc. This can
      also be used to load checkpoints from the directory into a estimator
      to continue training a previously saved model.
    label_dimension: Number of regression targets per example.
      Multi-dimensional support is not yet implemented.
    weight_column: A string or a `_NumericColumn` created by
      `tf.feature_column.numeric_column` defining feature column representing
      weights. It is used to downweight or boost examples during training. It
      will be multiplied by the loss of the example. If it is a string, it is
      used as a key to fetch weight tensor from the `features`. If it is a
      `_NumericColumn`, raw tensor is fetched by key `weight_column.key`,
      then weight_column.normalizer_fn is applied on it to get weight tensor.
    n_trees: number trees to be created.
    max_depth: maximum depth of the tree to grow.
    learning_rate: shrinkage parameter to be used when a tree added to the
      model.
    l1_regularization: regularization multiplier applied to the absolute
      weights of the tree leafs.
    l2_regularization: regularization multiplier applied to the square weights
      of the tree leafs.
    tree_complexity: regularization factor to penalize trees with more leaves.
    min_node_weight: minimum hessian a node must have for a split to be
        considered. The value will be compared with sum(leaf_hessian)/
        (batch_size * n_batches_per_layer).
    config: `RunConfig` object to configure the runtime settings.
    train_hooks: a list of Hook instances to be passed to estimator.train().
    center_bias: Whether bias centering needs to occur. Bias centering refers
        to the first node in the very first tree returning the prediction that
        is aligned with the original labels distribution. For example, for
        regression problems, the first node will return the mean of the labels.
        For binary classification problems, it will return a logit for a prior
        probability of label 1.
    pruning_mode: one of 'none', 'pre', 'post' to indicate no pruning, pre-
        pruning (do not split a node if not enough gain is observed) and post
        pruning (build the tree up to a max depth and then prune branches with
        negative gain). For pre and post pruning, you MUST provide
        tree_complexity >0.

  Returns:
    a `BoostedTreesClassifier` instance created with the given arguments and
      trained with the data loaded up on memory from the input_fn.

  Raises:
    ValueError: when wrong arguments are given or unsupported functionalities
       are requested.
  """
    # pylint: disable=protected-access
    # TODO(nponomareva): Extend it to multi-dimension cases.
    if label_dimension == canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT:
        label_dimension = 1
    head = canned_boosted_trees._create_regression_head(
        label_dimension, weight_column)

    # HParams for the model.
    tree_hparams = canned_boosted_trees._TreeHParams(
        n_trees, max_depth, learning_rate, l1_regularization,
        l2_regularization, tree_complexity, min_node_weight, center_bias,
        pruning_mode)

    def _model_fn(features, labels, mode, config):
        return canned_boosted_trees._bt_model_fn(features,
                                                 labels,
                                                 mode,
                                                 head,
                                                 feature_columns,
                                                 tree_hparams,
                                                 n_batches_per_layer=1,
                                                 config=config,
                                                 train_in_memory=True)

    in_memory_regressor = estimator.Estimator(model_fn=_model_fn,
                                              model_dir=model_dir,
                                              config=config)

    in_memory_regressor.train(
        input_fn=_validate_input_fn_and_repeat_dataset(train_input_fn),
        hooks=train_hooks)

    return in_memory_regressor
  def testContribEstimatorThatDFCIsInPredictions(self):
    # pylint:disable=protected-access
    head = canned_boosted_trees._create_regression_head(label_dimension=1)
    train_input_fn = _make_train_input_fn(is_classification=False)
    predict_input_fn = numpy_io.numpy_input_fn(
        x=FEATURES_DICT, y=None, batch_size=1, num_epochs=1, shuffle=False)

    est = boosted_trees._BoostedTreesEstimator(
        feature_columns=self._feature_columns,
        n_batches_per_layer=1,
        head=head,
        n_trees=1,
        max_depth=5,
        center_bias=True)
    # pylint:enable=protected-access

    num_steps = 100
    # Train for a few steps. Validate debug outputs in prediction dicts.
    est.train(train_input_fn, steps=num_steps)
    debug_predictions = est.experimental_predict_with_explanations(
        predict_input_fn)
    biases, dfcs = zip(*[(pred['bias'], pred['dfc'])
                         for pred in debug_predictions])
    self.assertAllClose([1.8] * 5, biases)
    self.assertAllClose(({
        0: -0.070499420166015625,
        1: -0.095000028610229492,
        2: 0.0
    }, {
        0: -0.53763031959533691,
        1: 0.063333392143249512,
        2: 0.0
    }, {
        0: -0.51756942272186279,
        1: -0.095000028610229492,
        2: 0.0
    }, {
        0: 0.1563495397567749,
        1: 0.063333392143249512,
        2: 0.0
    }, {
        0: 0.96934974193572998,
        1: 0.063333392143249512,
        2: 0.0
    }), dfcs)

    # Assert sum(dfcs) + bias == predictions.
    expected_predictions = [[1.6345005], [1.32570302], [1.1874305],
                            [2.01968288], [2.83268309]]
    predictions = [
        [sum(dfc.values()) + bias] for (dfc, bias) in zip(dfcs, biases)
    ]
    self.assertAllClose(expected_predictions, predictions)

    # Test when user doesn't include bias or dfc in predict_keys.
    debug_predictions = est.experimental_predict_with_explanations(
        predict_input_fn, predict_keys=['predictions'])
    for prediction_dict in debug_predictions:
      self.assertTrue('bias' in prediction_dict)
      self.assertTrue('dfc' in prediction_dict)
      self.assertTrue('predictions' in prediction_dict)
      self.assertEqual(len(prediction_dict), 3)
Esempio n. 10
0
def boosted_trees_regressor_train_in_memory(
    train_input_fn,
    feature_columns,
    model_dir=None,
    label_dimension=canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT,
    weight_column=None,
    n_trees=100,
    max_depth=6,
    learning_rate=0.1,
    l1_regularization=0.,
    l2_regularization=0.,
    tree_complexity=0.,
    config=None,
    train_hooks=None):
  """Trains a boosted tree regressor with in memory dataset.

  Example:

  ```python
  bucketized_feature_1 = bucketized_column(
    numeric_column('feature_1'), BUCKET_BOUNDARIES_1)
  bucketized_feature_2 = bucketized_column(
    numeric_column('feature_2'), BUCKET_BOUNDARIES_2)

  def input_fn_train():
    dataset = create-dataset-from-training-data
    # Don't use repeat or cache, since it is assumed to be one epoch
    # This is either tf.data.Dataset, or a tuple of feature dict and label.
    return dataset

  regressor = boosted_trees_regressor_train_in_memory(
      train_input_fn,
      feature_columns=[bucketized_feature_1, bucketized_feature_2],
      n_trees=100,
      ... <some other params>
  )

  def input_fn_eval():
    ...
    return dataset

  metrics = regressor.evaluate(input_fn=input_fn_eval, steps=10)
  ```

  Args:
    train_input_fn: the input function returns a dataset containing a single
      epoch of *unbatched* features and labels.
    feature_columns: An iterable containing all the feature columns used by
      the model. All items in the set should be instances of classes derived
      from `FeatureColumn`.
    model_dir: Directory to save model parameters, graph and etc. This can
      also be used to load checkpoints from the directory into a estimator
      to continue training a previously saved model.
    label_dimension: Number of regression targets per example.
      Multi-dimensional support is not yet implemented.
    weight_column: A string or a `_NumericColumn` created by
      `tf.feature_column.numeric_column` defining feature column representing
      weights. It is used to downweight or boost examples during training. It
      will be multiplied by the loss of the example. If it is a string, it is
      used as a key to fetch weight tensor from the `features`. If it is a
      `_NumericColumn`, raw tensor is fetched by key `weight_column.key`,
      then weight_column.normalizer_fn is applied on it to get weight tensor.
    n_trees: number trees to be created.
    max_depth: maximum depth of the tree to grow.
    learning_rate: shrinkage parameter to be used when a tree added to the
      model.
    l1_regularization: regularization multiplier applied to the absolute
      weights of the tree leafs.
    l2_regularization: regularization multiplier applied to the square weights
      of the tree leafs.
    tree_complexity: regularization factor to penalize trees with more leaves.
    config: `RunConfig` object to configure the runtime settings.
    train_hooks: a list of Hook instances to be passed to estimator.train().

  Returns:
    a `BoostedTreesClassifier` instance created with the given arguments and
      trained with the data loaded up on memory from the input_fn.

  Raises:
    ValueError: when wrong arguments are given or unsupported functionalities
       are requested.
  """
  # pylint: disable=protected-access
  # TODO(nponomareva): Extend it to multi-dimension cases.
  if label_dimension == canned_boosted_trees._HOLD_FOR_MULTI_DIM_SUPPORT:
    label_dimension = 1
  head = canned_boosted_trees._create_regression_head(label_dimension,
                                                      weight_column)

  # HParams for the model.
  tree_hparams = canned_boosted_trees.TreeHParams(
      n_trees, max_depth, learning_rate, l1_regularization, l2_regularization,
      tree_complexity)

  def _model_fn(features, labels, mode, config):
    return canned_boosted_trees._bt_model_fn(
        features,
        labels,
        mode,
        head,
        feature_columns,
        tree_hparams,
        n_batches_per_layer=1,
        config=config,
        train_in_memory=True)

  in_memory_regressor = estimator.Estimator(
      model_fn=_model_fn, model_dir=model_dir, config=config)

  in_memory_regressor.train(input_fn=train_input_fn, hooks=train_hooks)

  return in_memory_regressor