BigQuery 和 XGBoost 集成:用于二元分类的 Jupyter Notebook 教程

PHPz
发布: 2024-08-12 15:20:04
转载
489人浏览过

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)
登录后复制

解释

从 bigquery 加载数据

以前,数据以 csv 文件的形式存储在 cloud storage 中,但缓慢的数据加载降低了我们学习过程的效率,促使我们转向 bigquery 以加快数据处理速度。

设置 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 训练模型

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)
登录后复制

该函数将数据拆分为训练集和验证集,这对于测试模型的性能和避免过度拟合至关重要。

宣小二
宣小二

宣小二:媒体发稿平台,自媒体发稿平台,短视频矩阵发布平台,基于AI驱动的企业自助式投放平台。

宣小二 21
查看详情 宣小二

参数优化

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云存储作为数据源

在某些情况下,从 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)
登录后复制

使用 lightgbm 训练模型

如果您想使用 lightgbm 而不是 xgboost,只需在同一设置中将 xgbclassifier 替换为 lgbmclassifier 即可。

import lightgbm as lgb
model = lgb.LGBMClassifier()
登录后复制

结论

未来的文章将介绍如何使用 bigquery ml (bqml) 进行训练。

以上就是BigQuery 和 XGBoost 集成:用于二元分类的 Jupyter Notebook 教程的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号