提问人:user7431005 提问时间:11/13/2023 更新时间:11/13/2023 访问量:17
从 GridSearchCV 输出到日志(使用并行 joblib)
output from GridSearchCV to log (with parallel joblib)
问:
我正在集群上运行一些超参数优化。
群集会在一段时间后自动终止我的作业。
当这种情况发生时,我会失去所有初步结果。
将初步结果(打印到控制台的输出)存储在某个文件中会很棒。
我的计划是使用日志记录库来完成此任务。GridSearchCV
我想做什么:我希望能够将输出重定向到我的记录器。
我试图根据本网站上的一些建议简单地将所有输出重定向到我的记录器。
但是,它不起作用。GridSearchCV
sys.stdout
根据我找到的信息,我认为我面临的问题是每个进程都独立于我的主标准。
我也不确定是否有更聪明的方法可以做到这一点 - 我试图通过回调来解决它,但没有成功。GridSearchCV
这是一个最小的示例:
import xgboost as xgb
from sklearn.model_selection import GridSearchCV
import numpy as np
import logging
import sys
class StreamToLogger(object):
def __init__(self, logger, level):
self.logger = logger
self.level = level
self.linebuf = ''
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.level, line.rstrip())
def flush(self):
pass
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] %(message)s')
logger = logging.getLogger('sklearn.model_selection._search')
sys.stdout = StreamToLogger(logger, logging.INFO)
sys.stderr = StreamToLogger(logger, logging.ERROR)
X = np.random.randn(100,2)
y = np.random.randn(100)
reg = xgb.XGBRegressor(max_depth=10, n_estimators=100)
param_grid = {"gamma": [0.1]}
gs = GridSearchCV(reg, param_grid, cv=5, verbose=3, n_jobs=1)
gs.fit(X,y)
我将初步结果重定向到我的记录器:n_jobs=1
[2023-11-13 12:01:23,382] [INFO] Fitting 5 folds for each of 1 candidates, totalling 5 fits
[2023-11-13 12:01:23,434] [INFO] [CV 1/5] END ........................gamma=0.1;, score=-0.730 total time= 0.1s
[2023-11-13 12:01:23,451] [INFO] [CV 2/5] END ........................gamma=0.1;, score=-1.663 total time= 0.0s
[2023-11-13 12:01:23,467] [INFO] [CV 3/5] END ........................gamma=0.1;, score=-0.310 total time= 0.0s
[2023-11-13 12:01:23,483] [INFO] [CV 4/5] END ........................gamma=0.1;, score=-1.536 total time= 0.0s
[2023-11-13 12:01:23,507] [INFO] [CV 5/5] END ........................gamma=0.1;, score=-0.841 total time= 0.0s
当我将其更改为 时,输出变为n_jobs=2
[2023-11-13 11:58:54,220] [INFO] Fitting 5 folds for each of 1 candidates, totalling 5 fits
[CV 2/5] END ........................gamma=0.1;, score=-0.793 total time= 0.0s
[CV 1/5] END ........................gamma=0.1;, score=-0.111 total time= 0.0s
[CV 3/5] END ........................gamma=0.1;, score=-1.091 total time= 0.0s
[CV 4/5] END ........................gamma=0.1;, score=-0.139 total time= 0.0s
[CV 5/5] END ........................gamma=0.1;, score=-0.621 total time= 0.0s
(请注意,第一行仍然转发到我的记录器,但所有 [CV X/5] 行都不再重定向到我的记录器 - 因此,如果我添加文件处理程序,它们将不会包含在 .log 文件中)。
通过调用我的脚本使用的另一种方法似乎在进程被终止时不会刷新缓冲区......因此,我更愿意使用日志记录方法。$ python file.py > "file.log" 2>&1
答: 暂无答案
评论