python关键字evaluate_Python utils.evaluate方法代码示例

本文展示了如何在训练和验证神经网络模型过程中使用Python的utils.evaluate方法。通过导入utils模块,设置训练配置,构建数据加载器,初始化模型和优化器,进行训练并调用evaluate方法评估模型性能,根据评估结果更新学习率,并保存最佳模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 需要导入模块: import utils [as 别名]

# 或者: from utils import evaluate [as 别名]

def main():

args = parse_args()

C = importlib.import_module(args.config).TrainConfig

print("MODEL ID: {}".format(C.model_id))

summary_writer = SummaryWriter(C.log_dpath)

train_iter, val_iter, test_iter, vocab = build_loaders(C)

model = build_model(C, vocab)

optimizer = torch.optim.Adam(model.parameters(), lr=C.lr, weight_decay=C.weight_decay, amsgrad=True)

lr_scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=C.lr_decay_gamma,

patience=C.lr_decay_patience, verbose=True)

best_val_scores = { 'CIDEr': 0. }

best_epoch = 0

best_ckpt_fpath = None

for e in range(1, C.epochs + 1):

ckpt_fpath = C.ckpt_fpath_tpl.format(e)

""" Train """

print("\n")

train_loss = train(e, model, optimizer, train_iter, vocab, C.decoder.rnn_teacher_forcing_ratio,

C.reg_lambda, C.recon_lambda, C.gradient_clip)

log_train(C, summary_writer, e, train_loss, get_lr(optimizer))

""" Validation """

val_loss = test(model, val_iter, vocab, C.reg_lambda, C.recon_lambda)

val_scores = evaluate(val_iter, model, model.vocab)

log_val(C, summary_writer, e, val_loss, val_scores)

if e >= C.save_from and e % C.save_every == 0:

print("Saving checkpoint at epoch={} to {}".format(e, ckpt_fpath))

save_checkpoint(e, model, ckpt_fpath, C)

if e >= C.lr_decay_start_from:

lr_scheduler.step(val_loss['total'])

if e == 1 or val_scores['CIDEr'] > best_val_scores['CIDEr']:

best_epoch = e

best_val_scores = val_scores

best_ckpt_fpath = ckpt_fpath

""" Test with Best Model """

print("\n\n\n[BEST]")

best_model = load_checkpoint(model, best_ckpt_fpath)

test_scores = evaluate(test_iter, best_model, best_model.vocab)

log_test(C, summary_writer, best_epoch, test_scores)

save_checkpoint(best_epoch, best_model, C.ckpt_fpath_tpl.format("best"), C)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值