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

2024-08-12 0 519

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

介绍

在为表格数据选择二元分类模型时,我决定快速尝试一种快速的非深度学习模型:梯度提升决策树(gbdt)。本文介绍了使用 bigquery 作为数据源并使用 xgboost 算法进行建模来创建 jupyter notebook 脚本的过程。

完整脚本

对于那些喜欢直接跳入脚本而不进行解释的人,这里是。请调整project_name、dataset_name和Table_name以适合您的项目。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

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>

解释

从 bigquery 加载数据

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

设置 bigquery 客户端

1

2

from google.cloud import bigquery

client = bigquery.client()

代码使用 google cloud 凭据初始化 bigquery 客户端,该凭据可以通过环境变量或 google cloud sdk 设置。

查询和加载数据

1

2

3

4

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

模型初始化

1

2

import xgboost as xgb

model = xgb.xgbclassifier(eval_metric='logloss')

这里实例化了xgbclassifier类,使用对数损失作为评估指标。

数据分割

1

2

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)

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

参数优化

1

2

3

4

5

6

7

8

9

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 分数和对数损失来评估模型的性能。

1

2

3

4

5

6

7

8

9

10

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)

输出结果

运行笔记本时,您将得到以下输出,显示最佳参数和模型评估指标。

1

2

3

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 函数互换使用。

1

2

3

4

5

6

7

8

9

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

使用示例:

1

2

3

4

5

bucket_name = '<bucket-name>'

file_path = '<file-path>'

df = load_data_from_gcs(bucket_name, file_path)

</file-path></bucket-name>

使用 lightgbm 训练模型

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

1

2

import lightgbm as lgb

model = lgb.LGBmclassifier()

结论

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

免责声明
1. 本站所有资源来源于用户上传和网络等,如有侵权请邮件联系本站整改team@lcwl.fun!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系本站工作人员处理!
6. 本站资源售价或VIP只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 因人力时间成本问题,部分源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
9.本站所有源码资源都是经过本站工作人员人工亲测可搭建的,保证每个源码都可以正常搭建,但不保证源码内功能都完全可用,源码属于可复制的产品,无任何理由退款!

网站搭建学习网 Python BigQuery 和 XGBoost 集成:用于二元分类的 Jupyter Notebook 教程 https://www.xuezuoweb.com/11908.html

常见问题
  • 本站所有的源码都是经过平台人工部署搭建测试过可用的
查看详情
  • 购买源码资源时购买了带主机的套餐是指可以享受源码和所选套餐型号的主机两个产品,在本站套餐里开通主机可享优惠,最高免费使用主机
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

Fa快捷助手
手机编程软件开发

在手机上用手点一点就能轻松做软件

去做软件
链未云主机
免备案香港云主机

开通主机就送域名的免备案香港云主机

去使用
链未云服务器
免备案香港云服务器

支持售后、超低价、稳定的免备案香港云服务器

去使用