在为表格数据选择二元分类模型时,我决定快速尝试一种快速的非深度学习模型:梯度提升决策树(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)
以前,数据以 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)
如果您想使用 LightGBM 而不是 XGBoost,只需在同一设置中将 XGBClassifier 替换为 LGBMClassifier。
import lightgbm as lgb model = lgb.LGBMClassifier()
未来的文章将介绍如何使用 BigQuery ML (BQML) 进行训练。
以上是BigQuery 和 XGBoost 集成:用于二元分类的 Jupyter Notebook 教程的详细内容。更多信息请关注PHP中文网其他相关文章!