配置文件没什么好说的,只是为了方便后期修改代码,但是小弟只有一事不明,在第37行为什么可以直接调用DefaultConfig类中根本没有device属性,为什么这里可以调用呢????????????而且类里面也没有opt这个东西啊,只是在类外面声明了这个对象,咋就可以在类里面用呢?挖坑,解决了来这里填上!
# coding:utf8
import warnings
import torch as t
class DefaultConfig(object):
env = 'default' # visdom 环境
vis_port =8097 # visdom 端口
model = 'AlexNet' # 使用的模型,名字必须与models/__init__.py中的名字一致
train_data_root = './data/train/' # 训练集存放路径
test_data_root = r'.\data\test1' # 测试集存放路径
load_model_path = None # 加载预训练的模型的路径,为None代表不加载
batch_size = 32 # batch size
use_gpu = True # user GPU or not
num_workers = 4 # how many workers for loading data
print_freq = 20 # print info every N batch
debug_file = '/tmp/debug' # if os.path.exists(debug_file): enter ipdb
result_file = 'result.csv'
max_epoch = 10
lr = 0.001 # initial learning rate
lr_decay = 0.5 # when val_loss increase, lr = lr*lr_decay
weight_decay = 0e-5 # 损失函数
def _parse(self, kwargs):
"""
根据字典kwargs 更新 config参数
"""
for k, v in kwargs.items(): #字典items方法返回可遍历的(键, 值) 元组数组。
if not hasattr(self, k): #若没有k属性打印warning
warnings.warn("Warning: opt has not attribut %s" % k)
setattr(self, k, v) #设置k属性的值
opt.device =t.device('cuda') if opt.use_gpu else t.device('cpu') #??????????????????
'''
torch.device代表将torch.Tensor分配到的设备的对象。
torch.device包含一个设备类型('cpu'或'cuda'设备类型)
和可选的设备的序号。如果设备序号不存在,则为当前设备;
例如,torch.Tensor用设备构建'cuda'的结果等同于'cuda:X',
其中X是torch.cuda.current_device()的结果。
torch.Tensor的设备可以通过Tensor.device访问属性。
构造torch.device可以通过字符串/字符串和设备编号。
'''
print('user config:')
for k, v in self.__class__.__dict__.items():#实例对应的类的属性
if not k.startswith('_'): #如果不是以'__'开头
print(k, getattr(self, k)) #打印值
opt = DefaultConfig()