local-linr.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import argparse
  17. import pandas
  18. import numpy as np
  19. import os
  20. from sklearn.linear_model import SGDRegressor
  21. from sklearn.metrics import mean_squared_error, r2_score, explained_variance_score
  22. from pipeline.utils.tools import JobConfig
  23. def main(config="../../config.yaml", param="./linr_config.yaml"):
  24. # obtain config
  25. if isinstance(param, str):
  26. param = JobConfig.load_from_file(param)
  27. data_guest = param["data_guest"]
  28. data_host = param["data_host"]
  29. idx = param["idx"]
  30. label_name = param["label_name"]
  31. if isinstance(config, str):
  32. config = JobConfig.load_from_file(config)
  33. data_base_dir = config["data_base_dir"]
  34. else:
  35. data_base_dir = config.data_base_dir
  36. # prepare data
  37. df_guest = pandas.read_csv(os.path.join(data_base_dir, data_guest), index_col=idx)
  38. df_host = pandas.read_csv(os.path.join(data_base_dir, data_host), index_col=idx)
  39. df = df_guest.join(df_host, rsuffix="host")
  40. y = df[label_name]
  41. X = df.drop(label_name, axis=1)
  42. lm = SGDRegressor(loss="squared_loss", penalty=param["penalty"], random_state=42,
  43. fit_intercept=True, max_iter=param["max_iter"], average=param["batch_size"])
  44. lm_fit = lm.fit(X, y)
  45. y_pred = lm_fit.predict(X)
  46. mse = mean_squared_error(y, y_pred)
  47. rmse = np.sqrt(mse)
  48. r2 = r2_score(y, y_pred)
  49. explained_var = explained_variance_score(y, y_pred)
  50. metric_summary = {"r2_score": r2,
  51. "mean_squared_error": mse,
  52. "root_mean_squared_error": rmse,
  53. "explained_variance": explained_var}
  54. data_summary = {}
  55. return data_summary, metric_summary
  56. if __name__ == "__main__":
  57. parser = argparse.ArgumentParser("BENCHMARK-QUALITY LOCAL JOB")
  58. parser.add_argument("-param", type=str,
  59. help="config file for params")
  60. args = parser.parse_args()
  61. if args.param is not None:
  62. main(args.param)
  63. else:
  64. main()