问题:执行以下命令行太长了,不方便修改。
CUDA_VISIBLE_DEVICES=0 python tools/train.py --config ./configs/SegSAMPLerEmbMLP_config.py --cfg-options optimizer.lr=0.0005 optimizer.weight_decay=0.01 train_batch_size_per_gpu=4 test_batch_size_per_gpu=4 model_cfg.SAM_weights=0.1 model_cfg.hyperparameters.optimizer.lr=0.0005 model_cfg.hyperparameters.optimizer.weight_decay=0.01CUDA_VISIBLE_DEVICES=0 python tools/train.py --config ./configs/SegSAMPLerEmbMLP_config.py --cfg-options optimizer.lr=0.0005 optimizer.weight_decay=0.01 train_batch_size_per_gpu=4 test_batch_size_per_gpu=4 model_cfg.SAM_weights=0.1 model_cfg.hyperparameters.optimizer.lr=0.0005 model_cfg.hyperparameters.optimizer.weight_decay=0.01
对于过长的命令行,特别是在实验或调试中反复修改某些配置,以下几种方法可以简化命令的使用:
方法 1:使用配置文件
将命令行参数写入 YAML 或 JSON 文件,然后在脚本中加载该文件。这种方法尤其适合参数较多或需要频繁修改的情况。例如:
创建一个配置文件,如 custom_config.yaml:
config: "./configs/SegSAMPLerEmbMLP_config.py"
cfg-options:
optimizer.lr: 0.0005
optimizer.weight_decay: 0.01
train_batch_size_per_gpu: 4
test_batch_size_per_gpu: 4
model_cfg.SAM_weights: 0.1
model_cfg.hyperparameters.optimizer.lr: 0.0005
model_cfg.hyperparameters.optimizer.weight_decay: 0.01
在 train.py 脚本中添加对 YAML 文件的解析代码:
import yaml
# 加载配置文件
with open("custom_config.yaml", 'r') as f:
custom_args = yaml.safe_load(f)
将 custom_args 中的内容加载到现有的配置参数中,或直接替代 argparse 中的命令行参数。
运行简化的命令:
#bash
CUDA_VISIBLE_DEVICES=0 python tools/train.py --config custom_config.yaml
方法 2:创建 Bash 脚本
将命令行参数封装在一个 Bash 脚本中,这样可以通过直接修改脚本文件来调整参数:
创建 run_train.sh:
#!/bin/bash
CUDA_VISIBLE_DEVICES=0 python tools/train.py \
--config ./configs/SegSAMPLerEmbMLP_config.py \
--cfg-options \
optimizer.lr=0.0005 \
optimizer.weight_decay=0.01 \
train_batch_size_per_gpu=4 \
test_batch_size_per_gpu=4 \
model_cfg.SAM_weights=0.1 \
model_cfg.hyperparameters.optimizer.lr=0.0005 \
model_cfg.hyperparameters.optimizer.weight_decay=0.01
使用 chmod +x run_train.sh 赋予脚本执行权限。
之后,运行 ./run_train.sh 即可。
可能存在问题:run_train.sh: 行 3: --config:未找到命令
原因:这通常是由于格式错误,尤其是换行符的问题(可能含有 Windows 的回车符 \r)。
解决方法:使用 dos2unix 命令来转换脚本文件格式:解决方法:使用 dos2unix 命令来转换脚本文件格式:
###安装
sudo apt install dos2unix
###执行
dos2unix run_train.sh
方法 3:使用环境变量配置参数
你可以利用环境变量来传递参数,从而减少命令行长度。比如:
#bash
export TRAIN_CONFIG="./configs/SegSAMPLerEmbMLP_config.py"
export OPT_LR=0.0005
export OPT_WD=0.01
export TRAIN_BATCH=4
export TEST_BATCH=4
export SAM_WEIGHTS=0.1
然后在命令中引用这些变量:
CUDA_VISIBLE_DEVICES=0 python tools/train.py --config $TRAIN_CONFIG \
--cfg-options optimizer.lr=$OPT_LR optimizer.weight_decay=$OPT_WD \
train_batch_size_per_gpu=$TRAIN_BATCH test_batch_size_per_gpu=$TEST_BATCH \
model_cfg.SAM_weights=$SAM_WEIGHTS
这些方法都可以帮助你减少命令行长度并简化配置管理。
文章评论