0
雷鋒網(wǎng) AI 開發(fā)者按:在大多數(shù)機器學(xué)習(xí)競賽中,特診工程的質(zhì)量通常決定著整個作品的得分與排名,也是參賽者們非??粗氐囊徊糠帧T?GitHub 上,作者 Nomi(專注于計算機視覺與嵌入式技術(shù),也是 tiny-dnn 的原作者)向我們介紹了一個面向 kaggle 數(shù)據(jù)科學(xué)和離線競賽的實用工具庫 nyaggle,可供開發(fā)者專用于特征工程與驗證。
作者簡介 來源:Nomi
在機器學(xué)習(xí)和模式識別中,特征工程的好壞將會影響整個模型的預(yù)測性能。其中特征是在觀測現(xiàn)象中的一種獨立、可測量的屬性。選擇信息量大、有差別性、獨立的特征是模式識別、分類和回歸問題的關(guān)鍵一步,可以幫助開發(fā)者最大限度地從原始數(shù)據(jù)中提取特征以供算法和模型使用。
數(shù)據(jù)科學(xué)思維導(dǎo)圖 來源:網(wǎng)絡(luò)
而 nyaggle 就是一個特定于 Kaggle 和離線比賽的實用工具庫,它主要作用于四個部分,即:特征工程、模型驗證、模型實驗以及模型融合,尤其在特征工程和模型驗證方面有較強的性能。
其中,在特征工程方面,nyaggle 包含了 K 個特征目標(biāo)編碼和 BERT 句子向量化。目標(biāo)編碼使用的是目標(biāo)變量的均值編碼類別變量,為訓(xùn)練集中的每個分組計算目標(biāo)變量的統(tǒng)計量,之后會合并驗證集、測試集以捕捉分組和目標(biāo)之間的關(guān)系。BERT 句子向量化則是對 Bert 模型的輸入做一個向量化,提取詞句的三維信息。
BERT 詞句向量化示例 來源:網(wǎng)絡(luò)
nyaggle GitHub 地址:
API 詳情說明:nyaggle.experiment 類,實現(xiàn)模型實驗的各個功能
最簡 Kaggle 實驗記錄器,該模塊為記錄 Kaggle 實驗提供了最簡化的函數(shù)變量記錄。開發(fā)者可以通過 log_numpy 和 log_dataframe 在目錄下添加 numpy 數(shù)組和 pandas 數(shù)據(jù)框:
classnyaggle.experiment.Experiment(logging_directory, overwrite=False, custom_logger=None, with_mlflow=False, mlflow_run_id=None, logging_mode='w')
將排行榜得分記錄到現(xiàn)有實驗?zāi)夸浿校?br/>
nyaggle.experiment.add_leaderboard_score(logging_directory, score)
計算模型融合數(shù)據(jù):
nyaggle.experiment.average_results(source_files, output_filename, weight=None, input_format='csv', sample_submission_filename=None)
使用 optuna 在超參數(shù)中搜索 lightgbm 參數(shù):
nyaggle.experiment.find_best_lgbm_parameter(base_param, X, y, cv=None, groups=None, time_budget=None, type_of_target='auto')
通過交叉驗證評估指標(biāo)并將結(jié)果(日志,預(yù)測,測試預(yù)測,特征重要性圖和提交文件)存儲在指定目錄下。過程中將使用估計器 LGBM 分類器、LGBM 回歸器、CatBoost 分類器、CatBoost 回歸器其中之一,具體估計器由 type_of_target(y)和 gbdt_type 根據(jù)實際情況自動調(diào)用:
nyaggle.experiment.run_experiment(model_params,X_train,y,X_test = None,logging_directory ='output / {time}',overwrite = False,eval_func = None,algorithm_type ='lgbm',fit_params = None,cv = None,groups = None,categorical_feature = None,sample_submission = None,submission_filename = None,type_of_target ='auto',feature_list = None,feature_directory = None,with_auto_hpo = False,with_auto_prep = False,with_mlflow = False)
實驗詳細代碼
在典型的表格數(shù)據(jù)競賽中,開發(fā)者可能會通過交叉驗證重復(fù)進行評估,并記錄參數(shù)和結(jié)果以跟蹤實驗。
其中,run_experiment()正是用于此類交叉驗證實驗的高級 API,它在指定目錄下輸出參數(shù)、指標(biāo)、異常預(yù)測、測試預(yù)測、功能重要性和 Submitting.csv。
它可以與 mlflow 跟蹤結(jié)合使用,如果使用 LightGBM 作為模型,則代碼將非常簡單如下所示:
import pandas as pdfrom nyaggle.experiment import run_experimentfrom nyaggle.experiment import make_classification_df
INPUT_DIR = '../input'target_column = 'target'
X_train = pd.read_csv(f'{INPUT_DIR}/train.csv')X_test = pd.read_csv(f'{INPUT_DIR}/test.csv')sample_df = pd.read_csv(f'{INPUT_DIR}/sample_submission.csv') # OPTIONAL
y = X_train[target_column]X_train = X_train.drop(target_column, axis=1)
lightgbm_params = {
'max_depth': 8}
result = run_experiment(lightgbm_params,
X_train,
y,
X_test,
sample_submission=sample_df)
值得注意的是,默認的驗證策略是包含了 5 個特征的計算機視覺,開發(fā)者可以通過傳遞 cv 參數(shù)來更改此行為(可參閱 API 參考,https://nyaggle.readthedocs.io/en/latest/source/nyaggle.html#)。
之后,run_experiment API 執(zhí)行交叉驗證后,會將工件存儲到日志目錄。輸出文件存儲如下:
output
└── 20200130123456 # yyyymmssHHMMSS
├── params.txt # Parameters
├── metrics.txt # Metrics (single fold & overall CV score)
├── oof_prediction.npy # Out of fold prediction
├── test_prediction.npy # Test prediction
├── 20200130123456.csv # Submission csv file
├── importances.png # Feature importance plot
├── log.txt # Log file
└── models # The trained models for each fold
├── fold1
├── fold2
├── fold3
├── fold4
└── fold5
而如果要使用 XGBoost、CatBoost 或其他 sklearn 估計器,則需要在代碼開頭指定算法類型,其中的參數(shù)將傳遞給 sklearn API 的構(gòu)造函數(shù)(例如 LGBMClassifier)。
# CatBoostcatboost_params = {
'eval_metric': 'Logloss',
'loss_function': 'Logloss',
'depth': 8,
'task_type': 'GPU'}result = run_experiment(catboost_params,
X_train,
y,
X_test,
algorithm_type='cat')
# XGBoostxgboost_params = {
'objective': 'reg:linear',
'max_depth': 8}result = run_experiment(xgboost_params,
X_train,
y,
X_test,
algorithm_type='xgb')
# sklearn estimatorfrom sklearn.linear_model import Ridgerigde_params = {
'alpha': 1.0}result = run_experiment(rigde_params,
X_train,
y,
X_test,
algorithm_type=Ridge)
如果想讓 GUI 儀表板管理實驗,開發(fā)者則可以通過只設(shè)置 with_mlfow = True 來將 run_experiment 與 mlflow 一起使用(需要預(yù)先安裝 mlflow)。然后在與執(zhí)行腳本相同的目錄中,運行即可。
result = run_experiment(params,
X_train,
y,
X_test,
with_mlflow=True)
然后在與執(zhí)行腳本相同的目錄中,運行即可,相關(guān)結(jié)果(帶有 CV 得分和參數(shù)的實驗列表)可在 http:// localhost:5000 頁面上查看。
mlflow 結(jié)果頁面示例
注意:如果要自定義日志記錄的行為,可以在 mlflow run 上下文中調(diào)用 run_experiment;如果正在運行,則 run_experiment 將使用當(dāng)前正在運行的運行,而不是創(chuàng)建新的運行。
mlflow.set_tracking_uri('gs://ok-i-want-to-use-gcs')
with mlflow.start_run(run_name='your-favorite-run-name'):
mlflow.log_param('something-you-want-to-log', 42)
result = run_experiment(params,
X_train,
y,
X_test,
with_mlflow=True)
nyaggle.feature 類——以特征格式管理運行系列功能
nyaggle.feature.category_encoder
其中,Kfold 包裝器用于類似 sklearn 的界面;此類包裝器的 TransformerMixIn 具有 fit / transform / fit_transform 方法的對象,并以 K 個特征方式進行調(diào)用。而對于不同分類特征的目標(biāo)編碼運行方式如下:
對于分類目標(biāo) 將特征替換為給定特定分類值的目標(biāo)后驗概率與所有訓(xùn)練數(shù)據(jù)上目標(biāo)的先驗概率的混合。
對于連續(xù)目標(biāo) 用給定特定分類值的目標(biāo)期望值和所有訓(xùn)練數(shù)據(jù)上目標(biāo)的期望值的混合替換特征。
Class
nyaggle.feature.category_encoder.KFoldEncoderWrapper(base_transformer,cv = None,return_same_type = True,groups = None)
nyaggle.feature.nlp
其中 Sentence Vectorizer 使用的是 BERT 預(yù)訓(xùn)練模型,并使用 BERT 從可變長度的英語/日語句子中提取固定長度特征向量。
Class
nyaggle.feature.nlp.BertSentenceVectorizer(lang ='en',n_components = None,text_columns = None,pooling_strategy ='reduce_mean',use_cuda = False,tokenizer = None,model = None,return_same_type = True,column_format ='{col } _ {idx}')
nyaggle.feature_store 類——sklearn 兼容特征生成器
包裝器包裝了一個函數(shù),該函數(shù)將返回帶有記憶調(diào)用的 pd.DataFrame 并使用 feature_store.save_feature 保存數(shù)據(jù)幀:
nyaggle.feature_store.cached_feature(feature_name,directory ='。/ features /',ignore_columns = None)
加載特征作為 pandas 數(shù)據(jù)框架:
nyaggle.feature_store.load_feature(feature_name,directory ='。/ features /',ignore_columns = None)
加載特征并返回連接的數(shù)據(jù)框架:
nyaggle.feature_store.load_features(base_df,feature_names,directory ='。/ features /',ignore_columns = None,create_directory = True,rename_duplicate = True)
將 pandas 數(shù)據(jù)框架另存為特征格式:
nyaggle.feature_store.save_feature(df,feature_name,directory ='。/ features /',with_csv_dump = False,create_directory = True,reference_target_variable = None,overwrite = True)
nyaggle.validation 類——對抗性驗證,其中的驗證拆分器與 sklearn 兼容
滑動窗口時間序列交叉驗證器,也是時間序列交叉驗證器。該驗證器基于滑動窗口提供測試索引,以分割可變間隔時間序列數(shù)據(jù)。此類與 sklearn 的 BaseCrossValidator(KFold,GroupKFold 等的基類)兼容:
classnyaggle.validation.SlidingWindowSplit(source, train_from, train_to, test_from, test_to, n_windows, stride)
返回基礎(chǔ)驗證器的前 N 個特征,該驗證器打包基本驗證器以迭代返回前 n 個特征:
classnyaggle.validation.Take(n, base_validator)
時間序列交叉驗證器,提供訓(xùn)練/測試索引以拆分可變間隔時間序列數(shù)據(jù)。此類提供了用于時間序列驗證策略的低級 API。此類與 sklearn 的 BaseCrossValidator(KFold,GroupKFold 等的基類)兼容:
classnyaggle.validation.TimeSeriesSplit(source, times=None)
在 X_train 和 X_test 之間執(zhí)行對抗驗證:
nyaggle.validation.adversarial_validate(X_train, X_test, importance_type='gain', estimator=None, cat_cols=None, cv=None)
通過交叉驗證評估指標(biāo);同時,它還記錄了異常預(yù)測和測試預(yù)測:
nyaggle.validation.cross_validate(estimator, X_train, y, X_test=None, cv=None, groups=None, predict_proba=False, eval_func=None, logger=None, on_each_fold=None, fit_params=None, importance_type='gain', early_stopping=True, type_of_target='auto')
nyaggle.util 類
繪制特征重要性并寫入圖像:
nyaggle.util.plot_importance(importance, path=None, top_n=100, figsize=None, title=None)
nyaggle.hyper_parameters 類——從以往的解決方案中選取 Hypara 相關(guān)參數(shù)
通過參數(shù)名稱獲取超參數(shù):
nyaggle.hyper_parameters.get_hyperparam_byname(name,gbdt_type ='lgbm',with_metadata = False)
列出所有的超參數(shù):
nyaggle.hyper_parameters.list_hyperparams(gbdt_type ='lgbm',with_metadata = False)
雷鋒網(wǎng) AI 開發(fā)者 雷鋒網(wǎng)
雷峰網(wǎng)原創(chuàng)文章,未經(jīng)授權(quán)禁止轉(zhuǎn)載。詳情見轉(zhuǎn)載須知。