Example #1
0
def run_fn(fn_args: FnArgs):
    """Train the model based on given args.

  Args:
    fn_args: Holds args used to train the model as name/value pairs.
  """
    schema = io_utils.parse_pbtxt_file(fn_args.schema_file,
                                       schema_pb2.Schema())

    x_train, y_train = _input_fn(fn_args.train_files, fn_args.data_accessor,
                                 schema)
    x_eval, y_eval = _input_fn(fn_args.eval_files, fn_args.data_accessor,
                               schema)

    steps_per_epoch = _TRAIN_DATA_SIZE / _TRAIN_BATCH_SIZE

    model = MLPClassifier(hidden_layer_sizes=[8, 8, 8],
                          activation='relu',
                          solver='adam',
                          batch_size=_TRAIN_BATCH_SIZE,
                          learning_rate_init=0.0005,
                          max_iter=int(fn_args.train_steps / steps_per_epoch),
                          verbose=True)
    model.feature_keys = _FEATURE_KEYS
    model.label_key = _LABEL_KEY
    model.fit(x_train, y_train)
    absl.logging.info(model)

    score = model.score(x_eval, y_eval)
    absl.logging.info('Accuracy: %f', score)

    os.makedirs(fn_args.serving_model_dir)

    model_path = os.path.join(fn_args.serving_model_dir, 'model.pkl')
    with fileio.open(model_path, 'wb+') as f:
        pickle.dump(model, f)