【发布时间】:2020-10-03 00:11:50
【问题描述】:
我有这段代码可以让 AutoKeras 运行 X 秒
def run_auto_keras(x_train, y_train, x_eval, y_eval):
print('Starting AutoKeras')
with timeout(TIME_IN_SEC):
clf = ak.StructuredDataClassifier(
max_trials=NUM_MODELS, directory=os.getcwd())
clf.fit(x_train, y_train, epochs=NUM_EPOCHS)
return clf.evaluate(x_eval, y_eval, batch_size=BATCH_SZ)
if not TRAIN_PATH.endswith('.csv'):
raise Exception(f'{TRAIN_PATH} is not CSV')
train = pd.read_csv(TRAIN_PATH)
if TARGET_COL not in train.columns:
raise Exception(f'{TARGET_COL} not in {TRAIN_PATH}')
mask = np.random.rand(len(train.index)) == SPLIT_P
y = train.pop(TARGET_COL)
x_train = train[mask]
y_train = y[mask]
x_eval = train[~mask]
y_eval = y.pop(TARGET_COL)[~mask]
x_train = x_train.to_numpy()
y_train = y_train.to_numpy()
x_eval = x_eval.to_numpy()
y_eval = y_eval.to_numpy()
try:
eval_score = run_auto_keras(x_train, y_train, x_eval, y_eval)
pd.DataFrame(data=[eval_score, NUM_MODELS, 'AutoKeras'], columns=[
'result', 'num_ensemble', 'ta2']).to_csv(LOSS_PATH, index=False)
except TimeoutError:
pd.DataFrame(data=[0, NUM_MODELS, 'AutoKeras'], columns=[
'result', 'num_ensemble', 'ta2']).to_csv(LOSS_PATH, index=False)
我在博客中读到,这种让进程运行 X 秒的方法可能是最好的
@contextmanager
def timeout(time):
signal.signal(signal.SIGALRM, raise_timeout)
signal.alarm(time)
try:
yield
except TimeoutError:
pass
finally:
signal.signal(signal.SIGALRM, signal.SIG_IGN)
def raise_timeout(signum, frame):
raise TimeoutError
这是在 X 秒内运行函数的正确方法吗?我想要的是如果它完成返回结果,如果没有,那么就抛出一个错误。
【问题讨论】:
-
@SpiderPig1297 这似乎与我在上面发布的内容相同,不是吗?此外,我不能在我的代码中使用 while 循环,因为它会实例化一个运行时间未知的 AutoML 对象,正如您在上面看到的那样,它由 .fit 调用,所以如果我有它,它会停止它下一次 while 迭代。
-
嗯,第一个答案是,但是还有另一个答案建议使用
multiprocessinglibrary。