|
|
import pyarrow.parquet as pq |
|
|
import numpy as np |
|
|
import xgboost as xgb |
|
|
import matplotlib.pyplot as plt |
|
|
from sklearn.metrics import mean_squared_error, r2_score |
|
|
|
|
|
def load_parquet_as_numpy(path): |
|
|
|
|
|
table = pq.read_table(path) |
|
|
|
|
|
|
|
|
df = table.to_pandas() |
|
|
|
|
|
|
|
|
X = df.drop(columns=["value"]).values.astype(np.float32) |
|
|
|
|
|
|
|
|
y = df["value"].values.astype(np.float32) |
|
|
|
|
|
return xgb.DMatrix(X, label=y), y |
|
|
|
|
|
def load_parquet_as_dmatrix(path): |
|
|
|
|
|
cols = [f"feature_{i}" for i in range(2048)] + ["value"] |
|
|
table = pq.read_table(path, columns=cols) |
|
|
|
|
|
|
|
|
X = np.column_stack([table[col].to_numpy(zero_copy_only=False) for col in table.column_names if col != "value"]).astype(np.float32) |
|
|
y = table["value"].to_numpy(zero_copy_only=False).astype(np.float32) |
|
|
|
|
|
return xgb.DMatrix(X, label=y), y |
|
|
|
|
|
def main(): |
|
|
print("Loading training data...") |
|
|
dtrain, y_train = load_parquet_as_dmatrix("intermediate_data/d2/data_train_features.parquet") |
|
|
|
|
|
print("Loading validation data...") |
|
|
dval, y_val = load_parquet_as_dmatrix("intermediate_data/d2/data_val_features.parquet") |
|
|
|
|
|
print("Loading test data...") |
|
|
dtest, y_test = load_parquet_as_dmatrix("intermediate_data/d2/data_test_features.parquet") |
|
|
|
|
|
print("Training model with histogram-based tree method...") |
|
|
params = { |
|
|
"objective": "reg:squarederror", |
|
|
"tree_method": "hist", |
|
|
"max_depth": 8, |
|
|
"eta": 0.1, |
|
|
"nthread": 10, |
|
|
"verbosity": 1 |
|
|
} |
|
|
|
|
|
evals_result = {} |
|
|
model = xgb.train( |
|
|
params, |
|
|
dtrain, |
|
|
num_boost_round=300, |
|
|
evals=[(dtrain, "train"), (dval, "eval")], |
|
|
early_stopping_rounds=20, |
|
|
evals_result=evals_result, |
|
|
verbose_eval=10 |
|
|
) |
|
|
|
|
|
|
|
|
y_pred = model.predict(dtest) |
|
|
rmse = mean_squared_error(y_test, y_pred, squared=False) |
|
|
r2 = r2_score(y_test, y_pred) |
|
|
|
|
|
print(f"Test RMSE: {rmse:.4f}") |
|
|
print(f"Test R^2: {r2:.4f}") |
|
|
|
|
|
os.makedirs("results", exist_ok=True) |
|
|
plt.figure() |
|
|
plt.plot(evals_result["train"]["rmse"], label="Train RMSE") |
|
|
plt.plot(evals_result["eval"]["rmse"], label="Validation RMSE") |
|
|
plt.xlabel("Boosting Round") |
|
|
plt.ylabel("RMSE") |
|
|
plt.title("XGBoost RMSE over Epochs") |
|
|
plt.legend() |
|
|
plt.savefig("results/d2/xgboost_d2_learning_curve.png", dpi=300) |
|
|
print("Saved learning curve to results/xgboost_d2_learning_curve.png") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|
|
|
|