# Buggy code
def __init__(
    self,
    path: str,
    name: str,
    problem_type: str,
    eval_metric: Union[str, metrics.Scorer] = None,
    num_classes=None,
    stopping_metric=None,
    model=None,
    hyperparameters=None,
    features=None,
    feature_types_metadata: FeatureTypesMetadata = None,
    debug=0,
    **kwargs,
):
    """Creates a new model.
    Args:
        path (str): directory where to store all outputs.
        name (str): name of subdirectory inside path where model will be saved.
        problem_type (str): type of problem this model will handle. Valid options: ['binary', 'multiclass', 'regression'].
        eval_metric (str or autogluon.utils.tabular.metrics.Scorer): objective function the model intends to optimize. If None, will be inferred based on problem_type.
        hyperparameters (dict): various hyperparameters that will be used by model (can be search spaces instead of fixed values).
        feature_types_metadata (autogluon.utils.tabular.features.feature_types_metadata.FeatureTypesMetadata): contains feature type information that can be used to identify special features such as text ngrams and datetime.
    """
    self.name = name
    self.path_root = path
    self.path_suffix = (
        self.name + os.path.sep
    )  # TODO: Make into function to avoid having to reassign on load?
    self.path = self.create_contexts(
        self.path_root + self.path_suffix
    )  # TODO: Make this path a function for consistency.
    self.num_classes = num_classes
    self.model = model
    self.problem_type = problem_type
    if eval_metric is not None:
        self.eval_metric = metrics.get_metric(
            eval_metric, self.problem_type, "eval_metric"
        )  # Note: we require higher values = better performance
    else:
        self.eval_metric = infer_eval_metric(problem_type=self.problem_type)
        logger.log(
            20,
            f"Model {self.name}'s eval_metric inferred to be '{self.eval_metric.name}' because problem_type='{self.problem_type}' and eval_metric was not specified during init.",
        )

    if stopping_metric is None:
        self.stopping_metric = self.eval_metric
    else:
        self.stopping_metric = stopping_metric

    if self.eval_metric.name in OBJECTIVES_TO_NORMALIZE:
        self.normalize_pred_probas = True
        logger.debug(
            self.name
            + " predicted probabilities will be transformed to never =0 since eval_metric="
            + self.eval_metric.name
        )
    else:
        self.normalize_pred_probas = False

    if isinstance(self.eval_metric, metrics._ProbaScorer):
        self.metric_needs_y_pred = False
    elif isinstance(self.eval_metric, metrics._ThresholdScorer):
        self.metric_needs_y_pred = False
    else:
        self.metric_needs_y_pred = True

    if isinstance(self.stopping_metric, metrics._ProbaScorer):
        self.stopping_metric_needs_y_pred = False
    elif isinstance(self.stopping_metric, metrics._ThresholdScorer):
        self.stopping_metric_needs_y_pred = False
    else:
        self.stopping_metric_needs_y_pred = True

    self.feature_types_metadata = feature_types_metadata  # TODO: Should this be passed to a model on creation? Should it live in a Dataset object and passed during fit? Currently it is being updated prior to fit by trainer
    self.features = features
    self.debug = debug

    self.fit_time = None  # Time taken to fit in seconds (Training data)
    self.predict_time = None  # Time taken to predict in seconds (Validation data)
    self.val_score = None  # Score with eval_metric (Validation data)

    self.params = {}
    self.params_aux = {}

    self._set_default_auxiliary_params()
    if hyperparameters is not None:
        hyperparameters = hyperparameters.copy()
        if AG_ARGS_FIT in hyperparameters:
            ag_args_fit = hyperparameters.pop(AG_ARGS_FIT)
            self.params_aux.update(ag_args_fit)
    self._set_default_params()
    self.nondefault_params = []
    if hyperparameters is not None:
        self.params.update(hyperparameters)
        self.nondefault_params = list(hyperparameters.keys())[
            :
        ]  # These are hyperparameters that user has specified.
    self.params_trained = dict()


# Traceback (ValueError)
File delimiter for ../input/house-prices-advanced-regression-techniques/test.csv inferred as ',' (comma). If this is incorrect, please manually load the data as a pandas DataFrame.
Loaded data from: ../input/house-prices-advanced-regression-techniques/test.csv | Columns = 80 / 80 | Rows = 1459 -> 1459
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-48-91455d7b9940> in <module>
1 test_data = task.Dataset(file_path=os.path.join(in_dir, job, 'test.csv'))
2
----> 3 preds = model.predict(test_data)

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/autogluon/task/tabular_prediction/predictor.py in predict(self, dataset, model, as_pandas, use_pred_cache, add_to_pred_cache)
130         """
131         dataset = self.__get_dataset(dataset)
--> 132         return self._learner.predict(X=dataset, model=model, as_pandas=as_pandas, use_pred_cache=use_pred_cache, add_to_pred_cache=add_to_pred_cache)
133
134     def predict_proba(self, dataset, model=None, as_pandas=False, as_multiclass=False):

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/autogluon/utils/tabular/ml/learner/abstract_learner.py in predict(self, X, model, as_pandas, use_pred_cache, add_to_pred_cache)
127
128         if len(X_cache_miss) > 0:
--> 129             y_pred_proba = self.predict_proba(X=X_cache_miss, model=model, inverse_transform=False)
130             problem_type = self.trainer_problem_type or self.problem_type
131             y_pred = get_pred_from_proba(y_pred_proba=y_pred_proba, problem_type=problem_type)

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/autogluon/utils/tabular/ml/learner/abstract_learner.py in predict_proba(self, X, model, as_pandas, as_multiclass, inverse_transform)
92     # TODO: Add pred_proba_cache functionality as in predict()
93     def predict_proba(self, X: DataFrame, model=None, as_pandas=False, as_multiclass=False, inverse_transform=True):
---> 94         X = self.transform_features(X)
95         y_pred_proba = self.load_trainer().predict_proba(X, model=model)
96         if inverse_transform:

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/autogluon/utils/tabular/ml/learner/abstract_learner.py in transform_features(self, X)
216     def transform_features(self, X):
217         for feature_generator in self.feature_generators:
--> 218             X = feature_generator.transform(X)
219         return X
220

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/autogluon/utils/tabular/utils/decorators.py in inner1(*args, **kwargs)
12         begin = time.time()
13
---> 14         output = func(*args, **kwargs)
15
16         # storing time after function execution

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/autogluon/utils/tabular/features/abstract_feature_generator.py in transform(self, X)
183             raise ValueError(f'Required columns are missing from the provided dataset. Missing columns: {missing_cols}')
184
--> 185         X = X.astype(self.features_init_types)
186         X.reset_index(drop=True, inplace=True)
187         X_features = self.generate_features(X)

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/generic.py in astype(self, dtype, copy, errors, **kwargs)
5863                     results.append(
5864                         col.astype(
-> 5865                             dtype=dtype[col_name], copy=copy, errors=errors, **kwargs
5866                         )
5867                     )

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/generic.py in astype(self, dtype, copy, errors, **kwargs)
5880             # else, only a single dtype is given
5881             new_data = self._data.astype(
-> 5882                 dtype=dtype, copy=copy, errors=errors, **kwargs
5883             )
5884             return self._constructor(new_data).__finalize__(self)

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/internals/managers.py in astype(self, dtype, **kwargs)
579
580     def astype(self, dtype, **kwargs):
--> 581         return self.apply("astype", dtype=dtype, **kwargs)
582
583     def convert(self, **kwargs):

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/internals/managers.py in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs)
436                     kwargs[k] = obj.reindex(b_items, axis=axis, copy=align_copy)
437
--> 438             applied = getattr(b, f)(**kwargs)
439             result_blocks = _extend_blocks(applied, result_blocks)
440

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/internals/blocks.py in astype(self, dtype, copy, errors, values, **kwargs)
557
558     def astype(self, dtype, copy=False, errors="raise", values=None, **kwargs):
--> 559         return self._astype(dtype, copy=copy, errors=errors, values=values, **kwargs)
560
561     def _astype(self, dtype, copy=False, errors="raise", values=None, **kwargs):

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/internals/blocks.py in _astype(self, dtype, copy, errors, values, **kwargs)
641                     # _astype_nansafe works fine with 1-d only
642                     vals1d = values.ravel()
--> 643                     values = astype_nansafe(vals1d, dtype, copy=True, **kwargs)
644
645                 # TODO(extension)

~/miniconda3/envs/autogluon/lib/python3.7/site-packages/pandas/core/dtypes/cast.py in astype_nansafe(arr, dtype, copy, skipna)
698         if not np.isfinite(arr).all():
699             raise ValueError(
--> 700                 "Cannot convert non-finite values (NA or inf) to " "integer"
701             )
702

ValueError: Cannot convert non-finite values (NA or inf) to integer

# Fixed code
def __init__(
    self,
    path: str,
    name: str,
    problem_type: str,
    eval_metric: Union[str, metrics.Scorer] = None,
    num_classes=None,
    stopping_metric=None,
    model=None,
    hyperparameters=None,
    features=None,
    feature_metadata: FeatureMetadata = None,
    debug=0,
    **kwargs,
):
    """Creates a new model.
    Args:
        path (str): directory where to store all outputs.
        name (str): name of subdirectory inside path where model will be saved.
        problem_type (str): type of problem this model will handle. Valid options: ['binary', 'multiclass', 'regression'].
        eval_metric (str or autogluon.utils.tabular.metrics.Scorer): objective function the model intends to optimize. If None, will be inferred based on problem_type.
        hyperparameters (dict): various hyperparameters that will be used by model (can be search spaces instead of fixed values).
        feature_metadata (autogluon.utils.tabular.features.feature_metadata.FeatureMetadata): contains feature type information that can be used to identify special features such as text ngrams and datetime as well as which features are numerical vs categorical
    """
    self.name = name
    self.path_root = path
    self.path_suffix = (
        self.name + os.path.sep
    )  # TODO: Make into function to avoid having to reassign on load?
    self.path = self.create_contexts(
        self.path_root + self.path_suffix
    )  # TODO: Make this path a function for consistency.
    self.num_classes = num_classes
    self.model = model
    self.problem_type = problem_type
    if eval_metric is not None:
        self.eval_metric = metrics.get_metric(
            eval_metric, self.problem_type, "eval_metric"
        )  # Note: we require higher values = better performance
    else:
        self.eval_metric = infer_eval_metric(problem_type=self.problem_type)
        logger.log(
            20,
            f"Model {self.name}'s eval_metric inferred to be '{self.eval_metric.name}' because problem_type='{self.problem_type}' and eval_metric was not specified during init.",
        )

    if stopping_metric is None:
        self.stopping_metric = self.eval_metric
    else:
        self.stopping_metric = stopping_metric

    if self.eval_metric.name in OBJECTIVES_TO_NORMALIZE:
        self.normalize_pred_probas = True
        logger.debug(
            self.name
            + " predicted probabilities will be transformed to never =0 since eval_metric="
            + self.eval_metric.name
        )
    else:
        self.normalize_pred_probas = False

    if isinstance(self.eval_metric, metrics._ProbaScorer):
        self.metric_needs_y_pred = False
    elif isinstance(self.eval_metric, metrics._ThresholdScorer):
        self.metric_needs_y_pred = False
    else:
        self.metric_needs_y_pred = True

    if isinstance(self.stopping_metric, metrics._ProbaScorer):
        self.stopping_metric_needs_y_pred = False
    elif isinstance(self.stopping_metric, metrics._ThresholdScorer):
        self.stopping_metric_needs_y_pred = False
    else:
        self.stopping_metric_needs_y_pred = True

    self.feature_metadata = feature_metadata  # TODO: Should this be passed to a model on creation? Should it live in a Dataset object and passed during fit? Currently it is being updated prior to fit by trainer
    self.features = features
    self.debug = debug

    self.fit_time = None  # Time taken to fit in seconds (Training data)
    self.predict_time = None  # Time taken to predict in seconds (Validation data)
    self.val_score = None  # Score with eval_metric (Validation data)

    self.params = {}
    self.params_aux = {}

    self._set_default_auxiliary_params()
    if hyperparameters is not None:
        hyperparameters = hyperparameters.copy()
        if AG_ARGS_FIT in hyperparameters:
            ag_args_fit = hyperparameters.pop(AG_ARGS_FIT)
            self.params_aux.update(ag_args_fit)
    self._set_default_params()
    self.nondefault_params = []
    if hyperparameters is not None:
        self.params.update(hyperparameters)
        self.nondefault_params = list(hyperparameters.keys())[
            :
        ]  # These are hyperparameters that user has specified.
    self.params_trained = dict()