|
| 1 | +# Build and commit an xgboost model |
| 2 | +# Deliberately simplistic in approach |
| 3 | + |
| 4 | +import os |
| 5 | + |
| 6 | +import pandas as pd |
| 7 | +import sklearn |
| 8 | +from matplotlib import pyplot |
| 9 | + |
| 10 | +from xgboost import plot_importance |
| 11 | +from xgboost import XGBClassifier |
| 12 | +from xgboost import XGBRegressor |
| 13 | + |
| 14 | +from absl import app |
| 15 | +from absl import flags |
| 16 | +from absl import logging |
| 17 | +from google.protobuf import text_format |
| 18 | + |
| 19 | +import xgboost_model_pb2 |
| 20 | + |
| 21 | +FLAGS = flags.FLAGS |
| 22 | + |
| 23 | +flags.DEFINE_string("activity", "", "Name of training set activity file") |
| 24 | +flags.DEFINE_string("desc", "", "Name of training set descriptor file") |
| 25 | +flags.DEFINE_boolean("classification", False, "True if this is a classification task") |
| 26 | +flags.DEFINE_string("mdir", "", "Directory into which the model is placed") |
| 27 | +flags.DEFINE_integer("max_num_features", 0, "Maximum number of features to plot in variable importance") |
| 28 | +flags.DEFINE_string("feature_importance", "", "File containing feature importance values") |
| 29 | +flags.DEFINE_integer("xgverbosity", 0, "xgboost verbosity") |
| 30 | +flags.DEFINE_string("proto", "", "A file containing an XGBoostParameters proto") |
| 31 | +flags.DEFINE_float("eta", 0.3, "xgboost learning rate parameter eta") |
| 32 | +flags.DEFINE_integer("max_depth", 6, "xgboost max depth") |
| 33 | +flags.DEFINE_integer("n_estimators", 100, "xboost number of estimators") |
| 34 | + |
| 35 | +class Options: |
| 36 | + def __init__(self): |
| 37 | + self.classification = False |
| 38 | + self.mdir: str = "" |
| 39 | + self.max_num_features: int = 10 |
| 40 | + self.verbosity = 0 |
| 41 | + self.proto = xgboost_model_pb2.XGBoostParameters() |
| 42 | + |
| 43 | + def read_proto(self, fname)->bool: |
| 44 | + """Read self.proto from `fname` |
| 45 | + """ |
| 46 | + with open(fname, "r") as reader: |
| 47 | + text = reader.read() |
| 48 | + |
| 49 | + self.proto = text_format.Parse(text, xgboost_model_pb2.XGBoostParameters()) |
| 50 | + if not self.proto: |
| 51 | + logging.error("Cannot intpret %s", text) |
| 52 | + return False |
| 53 | + |
| 54 | + return True |
| 55 | +def classification(x, y, options: Options)->bool: |
| 56 | + """build a classification model |
| 57 | + """ |
| 58 | + booster = XGBClassifier(verbosity=options.verbosity) |
| 59 | + booster.fit(x, y) |
| 60 | + |
| 61 | +def regression(x, y, options: Options): |
| 62 | + """build a regression model. |
| 63 | + """ |
| 64 | + booster = XGBRegressor(verbosity=options.verbosity, |
| 65 | + eta=options.proto.eta, |
| 66 | + max_depth=options.proto.max_depth, |
| 67 | + n_estimators = options.proto.n_estimators) |
| 68 | + booster.fit(x, y) |
| 69 | + |
| 70 | + booster.save_model(os.path.join(options.mdir, "xgboost.json")) |
| 71 | + if options.max_num_features: |
| 72 | + plot_importance(booster, max_num_features=options.max_num_features) |
| 73 | + pyplot.show() |
| 74 | + if options.feature_importance: |
| 75 | + feature_importance = booster.get_booster().get_score(importance_type='weight') |
| 76 | + feature_importance = sorted(feature_importance.items(), key=lambda x:x[1]) |
| 77 | + if options.feature_importance: |
| 78 | + with open(os.path.join(options.mdir, options.feature_importance), "w") as writer: |
| 79 | + # Write a markdown table, easy to undo if needed. |
| 80 | + print("| Feature | Weight |", file=writer) |
| 81 | + print("| ------- | ------ |", file=writer) |
| 82 | + for f, i in feature_importance: |
| 83 | + print(f"| {f} | {i} |", file=writer) |
| 84 | + |
| 85 | + # config = booster.save_config() |
| 86 | + |
| 87 | + return True |
| 88 | + |
| 89 | +def build_xgboost_model(descriptor_fname: str, |
| 90 | + activity_fname: str, |
| 91 | + options: Options)->bool: |
| 92 | + """Build an xgboost model on the data in `descriptor_fname` and |
| 93 | + `activity_fname`. |
| 94 | + This function does data preprocessing. |
| 95 | + """ |
| 96 | + |
| 97 | + descriptors = pd.read_csv(descriptor_fname, sep=' ', header=0, low_memory=False) |
| 98 | + logging.info("Read %d rows and %d columns from %s", len(descriptors), |
| 99 | + descriptors.shape[1], descriptor_fname) |
| 100 | + activity = pd.read_csv(activity_fname, sep=' ', header=0) |
| 101 | + logging.info("Read %d rows from %s", activity.shape[0], activity_fname) |
| 102 | + |
| 103 | + |
| 104 | + descriptors.rename(columns={descriptors.columns[0]: "Id"}, inplace=True) |
| 105 | + activity.rename(columns={activity.columns[0]: "Id"}, inplace=True) |
| 106 | + combined = pd.concat([activity.set_index("Id"), |
| 107 | + descriptors.set_index("Id")], axis=1, join='inner').reset_index() |
| 108 | + if len(combined) != len(descriptors): |
| 109 | + logging.error("Combined set has %d rows", len(combined)) |
| 110 | + return 1 |
| 111 | + |
| 112 | + if not os.path.isdir(options.mdir): |
| 113 | + os.mkdir(options.mdir) |
| 114 | + |
| 115 | + y = combined.iloc[:,1].to_numpy() |
| 116 | + |
| 117 | + x = combined.iloc[:,2:] |
| 118 | + x.apply(pd.to_numeric).to_numpy() |
| 119 | + |
| 120 | + rc = False |
| 121 | + if options.classification: |
| 122 | + rc = classification(x, y, options) |
| 123 | + else: |
| 124 | + rc = regression(x, y, options) |
| 125 | + |
| 126 | + if not rc: |
| 127 | + return False |
| 128 | + |
| 129 | + response = activity.columns[1] |
| 130 | + |
| 131 | + proto = xgboost_model_pb2.XGBoostModel(); |
| 132 | + proto.model_type = "XGBD" |
| 133 | + proto.classification = False |
| 134 | + proto.response = response |
| 135 | + proto.parameters.CopyFrom(options.proto) |
| 136 | + with open(os.path.join(options.mdir, "model_metadata.txt"), "w") as f: |
| 137 | + f.write(text_format.MessageToString(proto)) |
| 138 | + |
| 139 | + return True |
| 140 | + |
| 141 | +def main(argv): |
| 142 | + """Build xgboost models from activity file and descriptor file. |
| 143 | + """ |
| 144 | + if not FLAGS.activity: |
| 145 | + logging.error("Must specifythe name of the activity file with the --activity option") |
| 146 | + return False |
| 147 | + if not FLAGS.desc: |
| 148 | + logging.error("Must specifythe name of the descriptor file with the --desc option") |
| 149 | + return False |
| 150 | + if not FLAGS.mdir: |
| 151 | + logging.error("Must specifyi the model directory via the --mdir option") |
| 152 | + return False |
| 153 | + |
| 154 | + options = Options() |
| 155 | + options.classification = FLAGS.classification |
| 156 | + options.mdir = FLAGS.mdir |
| 157 | + options.max_num_features = FLAGS.max_num_features |
| 158 | + options.feature_importance = FLAGS.feature_importance |
| 159 | + options.verbosity = FLAGS.xgverbosity |
| 160 | + |
| 161 | + # Build the proto first, and then anything that might overwrite it. |
| 162 | + if FLAGS.proto: |
| 163 | + if not options.read_proto(FLAGS.proto): |
| 164 | + logging.error("Cannot read textproto parameters %s", FLAGS.proto) |
| 165 | + return False |
| 166 | + else: |
| 167 | + options.proto.eta = FLAGS.eta |
| 168 | + options.proto.max_depth = FLAGS.max_depth |
| 169 | + options.proto.n_estimators = FLAGS.n_estimators |
| 170 | + |
| 171 | + if not build_xgboost_model(FLAGS.desc, FLAGS.activity, options): |
| 172 | + logging.error("Model %s not build", options.mdir) |
| 173 | + return False |
| 174 | + |
| 175 | + return True |
| 176 | + |
| 177 | +if __name__ == '__main__': |
| 178 | + app.run(main) |
0 commit comments