BigQuery 和 XGBoost 集成:用于二元分类的 Jupyter Notebook 教程
在为表格数据选择二元分类模型时,我决定快速尝试一种快速的非深度学习模型:梯度提升决策树(gbdt)。本文介绍了使用 bigquery 作为数据源并使用 xgboost 算法进行建模来创建 jupyter notebook 脚本的过程。
对于那些喜欢直接跳入脚本而不进行解释的人,这里是。请调整project_name、dataset_name和table_name以适合您的项目。
import xgboost as xgb from sklearn.model_selection import train_test_split, gridsearchcv from sklearn.metrics import precision_score, recall_score, f1_score, log_loss from google.cloud import bigquery # function to load data from bigquery def load_data_from_bigquery(query): client = bigquery.client() query_job = client.query(query) df = query_job.to_dataframe() return df def compute_metrics(labels, predictions, prediction_probs): precision = precision_score(labels, predictions, average='macro') recall = recall_score(labels, predictions, average='macro') f1 = f1_score(labels, predictions, average='macro') loss = log_loss(labels, prediction_probs) return { 'precision': precision, 'recall': recall, 'f1': f1, 'loss': loss } # query in bigquery query = """ select * from `<project_name>.<dataset_name>.<table_name>` """ # loading data df = load_data_from_bigquery(query) # target data y = df["reaction"] # input data x = df.drop(columns=["reaction"], axis=1) # splitting data into training and validation sets x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=1) # training the xgboost model model = xgb.xgbclassifier(eval_metric='logloss') # setting the parameter grid param_grid = { 'max_depth': [3, 4, 5], 'learning_rate': [0.01, 0.1, 0.2], 'n_estimators': [100, 200, 300], 'subsample': [0.8, 0.9, 1.0] } # initializing gridsearchcv grid_search = gridsearchcv(estimator=model, param_grid=param_grid, cv=3, scoring='accuracy', verbose=1, n_jobs=-1) # executing the grid search grid_search.fit(x_train, y_train) # displaying the best parameters print("best parameters:", grid_search.best_params_) # model with the best parameters best_model = grid_search.best_estimator_ # predictions on validation data val_predictions = best_model.predict(x_val) val_prediction_probs = best_model.predict_proba(x_val) # predictions on training data train_predictions = best_model.predict(x_train) train_prediction_probs = best_model.predict_proba(x_train) # evaluating the model (validation data) val_metrics = compute_metrics(y_val, val_predictions, val_prediction_probs) print("optimized validation metrics:", val_metrics) # evaluating the model (training data) train_metrics = compute_metrics(y_train, train_predictions, train_prediction_probs) print("optimized training metrics:", train_metrics) </table_name></dataset_name></project_name>
以前,数据以 csv 文件的形式存储在 cloud storage 中,但缓慢的数据加载降低了我们学习过程的效率,促使我们转向 bigquery 以加快数据处理速度。
from google.cloud import bigquery client = bigquery.client()
此代码使用 google cloud 凭据初始化 bigquery 客户端,该凭据可以通过环境变量或 google cloud sdk 设置。
def load_data_from_bigquery(query): query_job = client.query(query) df = query_job.to_dataframe() return df
该函数执行 sql 查询并将结果作为 pandas 中的 dataframe 返回,从而实现高效的数据处理。
xgboost 是一种利用梯度提升的高性能机器学习算法,广泛用于分类和回归问题。
https://arxiv.org/pdf/1603.02754
import xgboost as xgb model = xgb.xgbclassifier(eval_metric='logloss')
这里实例化了xgbclassifier类,使用对数损失作为评估指标。
from sklearn.model_selection import train_test_split x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=1)
该函数将数据拆分为训练集和验证集,这对于测试模型的性能和避免过度拟合至关重要。
from sklearn.model_selection import gridsearchcv param_grid = { 'max_depth': [3, 4, 5], 'learning_rate': [0.01, 0.1, 0.2], 'n_estimators': [100, 200, 300], 'subsample': [0.8, 0.9, 1.0] } grid_search = gridsearchcv(estimator=model, param_grid=param_grid, cv=3, scoring='accuracy', verbose=1, n_jobs=-1) grid_search.fit(x_train, y_train)
gridsearchcv 执行交叉验证以找到模型的最佳参数组合。
使用验证数据集上的精度、召回率、f1 分数和对数损失来评估模型的性能。
def compute_metrics(labels, predictions, prediction_probs): from sklearn.metrics import precision_score, recall_score, f1_score, log_loss return { 'precision': precision_score(labels, predictions, average='macro'), 'recall': recall_score(labels, predictions, average='macro'), 'f1': f1_score(labels, predictions, average='macro'), 'loss': log_loss(labels, prediction_probs) } val_metrics = compute_metrics(y_val, val_predictions, val_prediction_probs) print("optimized validation metrics:", val_metrics)
运行笔记本时,您将得到以下输出,显示最佳参数和模型评估指标。
best parameters: {'learning_rate': 0.2, 'max_depth': 5, 'n_estimators': 300, 'subsample': 0.9} optimized validation metrics: {'precision': 0.8919952583956949, 'recall': 0.753797304483842, 'f1': 0.8078981867164722, 'loss': 0.014006406471894417} optimized training metrics: {'precision': 0.8969556573175115, 'recall': 0.7681976753444204, 'f1': 0.8199353049298048, 'loss': 0.012475375680566196}
在某些情况下,从 google cloud storage 而不是 bigquery 加载数据可能更合适。以下函数从 cloud storage 读取 csv 文件并将其作为 pandas 中的 dataframe 返回,并且可以与 load_data_from_bigquery 函数互换使用。
from google.cloud import storage def load_data_from_gcs(bucket_name, file_path): client = storage.client() bucket = client.get_bucket(bucket_name) blob = bucket.blob(file_path) data = blob.download_as_text() df = pd.read_csv(io.stringio(data), encoding='utf-8') return df
使用示例:
bucket_name = '<bucket-name>' file_path = '<file-path>' df = load_data_from_gcs(bucket_name, file_path) </file-path></bucket-name>
如果您想使用 lightgbm 而不是 xgboost,只需在同一设置中将 xgbclassifier 替换为 lgbmclassifier 即可。
import lightgbm as lgb model = lgb.LGBMClassifier()
未来的文章将介绍如何使用 bigquery ml (bqml) 进行训练。
以上就是BigQuery 和 XGBoost 集成:用于二元分类的 Jupyter Notebook 教程的详细内容,更多请关注php中文网其它相关文章!