eval_interval
eval_interval是一个用于控制模型评估频率的参数。它表示在训练过程中,每经过多少个训练步骤后进行一次模型评估。评估的目的是为了衡量模型在验证集上的性能,以便及时监控模型的训练进展并进行调整。
通过设置eval_interval,可以灵活地控制模型评估的频率。较小的eval_interval值会增加评估的次数,可以更及时地了解模型的性能变化,但也会增加训练时间。较大的eval_interval值则会减少评估的次数,节省训练时间,但可能会延迟对模型性能变化的感知。
在实际应用中,eval_interval的选择需要根据具体情况进行权衡。通常建议根据数据集大小、模型复杂度和计算资源等因素进行调整,以达到在训练过程中既能及时监控模型性能又不会过于频繁地进行评估的效果。
同时运行run和evalMAPPO的light版本代码默认是不进行eval操作的,源头在run函数中有体现: # eval if episode % self.eval_interval == 0 and self.use_eval: self.eval(total_num_steps)123在config的文件中,默认--use_eval为False,所以在运行run函数时不会进行eval操作,这里只需要把这个参数改为True即可同时运行self.eval函数。parser.add_argument("--use_eval", action='store_true', default=True, help="by default,
修改配置以支持 --use_eval
参数
为了实现 run
和 evalMAPPO
的轻量级版本代码同时执行评估 (eval
) 操作,可以通过设置 --use_eval=True
来启用评估功能。以下是具体方法以及需要注意的关键点:
配置文件调整
在配置文件中,需确保以下参数被正确定义并传递给模型训练和评估流程:
use_eval
: 设置此参数为True
将激活评估逻辑[^1]。class_weights_of_eval_data
: 如果数据集中存在类别不平衡的情况,则可以利用该参数指定不同类别的权重,从而提升评估效果。
# config.yaml example
training:
use_eval: True
evaluation:
class_weights_of_eval_data: [0.5, 1.0, 1.5] # Example weight values per class
脚本中的参数解析
在脚本入口处,应通过命令行参数或配置加载机制读取上述选项,并将其应用于训练与评估阶段。例如,在 Python 中可使用 argparse
或其他类似的工具处理输入参数。
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='Run and Evaluate MAPPO Light Version')
parser.add_argument('--use_eval', action='store_true', help='Enable evaluation during training.')
args = parser.parse_args()
return args
args = parse_args()
if args.use_eval:
print("Evaluation is enabled.")
else:
print("Evaluation is disabled.")
使用贝叶斯优化进行超参调优 (Optional)
对于更复杂的场景,可通过引入贝叶斯优化进一步提高性能表现。基于引用内容提到的方法[^2],推荐采用 scikit-optimize
库完成这一目标。安装方式如下所示:
conda install -c conda-forge scikit-optimize
随后编写相应的优化函数定义及调用过程:
from skopt import BayesSearchCV
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
# 假设已准备好特征矩阵 X 及标签 y
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)
search_space = {
'learning_rate': (0.01, 0.3),
'n_estimators': (50, 500),
}
model = XGBClassifier(use_label_encoder=False, eval_metric='logloss')
optimizer = BayesSearchCV(model, search_space, n_iter=32, random_state=42)
optimizer.fit(X_train, y_train, eval_set=[(X_val, y_val)])
print(f'Best parameters found: {optimizer.best_params_}')
结合视频展示结果 (Optional)
最后一步可能涉及可视化部分成果。假设生成了一段 MP4 文件用于演示算法的实际运行状况,则可以根据已有代码片段稍作修改以便嵌入 Notebook 环境下播放[^3]。
import torch
import base64
from IPython.display import HTML
outpath = "/root/RobustVideoMatting/output/com.mp4"
mp4 = open(outpath, 'rb').read()
data_url = "data:video/mp4;base64," + base64.b64encode(mp4).decode()
HTML_code = f"""
<video width=800 controls>
<source src="{data_url}" type="video/mp4">
</video>
"""
display(HTML(HTML_code))
import time import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.examples.tutorials.mnist import input_data import mnist_inference import mnist_train tf.compat.v1.reset_default_graph() EVAL_INTERVAL_SECS = 10 def evaluate(mnist): with tf.Graph().as_default() as g: #定义输入与输出的格式 x = tf.compat.v1.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input') y_ = tf.compat.v1.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input') validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels} #直接调用封装好的函数来计算前向传播的结果 y = mnist_inference.inference(x, None) #计算正确率 correcgt_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correcgt_prediction, tf.float32)) #通过变量重命名的方式加载模型 variable_averages = tf.train.ExponentialMovingAverage(0.99) variable_to_restore = variable_averages.variables_to_restore() saver = tf.train.Saver(variable_to_restore) #每隔10秒调用一次计算正确率的过程以检测训练过程中正确率的变化 while True: with tf.compat.v1.Session() as sess: ckpt = tf.train.get_checkpoint_state(minist_train.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: #load the model saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] accuracy_score = sess.run(accuracy, feed_dict=validate_feed) print("After %s training steps, validation accuracy = %g" % (global_step, accuracy_score)) else: print('No checkpoint file found') return time.sleep(EVAL_INTERVAL_SECS) def main(argv=None): mnist = input_data.read_data_sets(r"D:\Anaconda123\Lib\site-packages\tensorboard\mnist", one_hot=True) evaluate(mnist) if __name__ == '__main__': tf.compat.v1.app.run()对代码进行改进
以下是对代码的改进建议:
在代码开头添加注释,简要说明代码功能和使用方法。
将导入模块的语句放在代码开头。
将模型保存路径和评估时间间隔定义为常量,并使用有意义的变量名。
将计算正确率和加载模型的过程封装为函数。
在主函数中调用评估函数。
改进后的代码如下:
# 该代码实现了使用已训练好的模型对 MNIST 数据集进行评估
import time
import tensorflow.compat.v1 as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist_inference
import mnist_train
# 定义常量
MODEL_SAVE_PATH = 'model/'
EVAL_INTERVAL_SECS = 10
def evaluate(mnist):
"""
计算模型在验证集上的正确率
"""
with tf.Graph().as_default() as g:
# 定义输入和输出格式
x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')
y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
# 直接调用封装好的函数计算前向传播结果
y = mnist_inference.inference(x, None)
# 计算正确率
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 加载模型
variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
# 在验证集上计算正确率
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
accuracy_score = sess.run(accuracy, feed_dict={x: mnist.validation.images, y_: mnist.validation.labels})
print("After %s training steps, validation accuracy = %g" % (global_step, accuracy_score))
else:
print('No checkpoint file found')
def main(argv=None):
# 读取数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 每隔一定时间评估模型在验证集上的正确率
while True:
evaluate(mnist)
time.sleep(EVAL_INTERVAL_SECS)
if __name__ == '__main__':
tf.app.run()
相关推荐
















