chenyuntc / pytorch-book

PyTorch tutorials and fun projects including neural talk, neural style, poem writing, anime generation (《深度学习框架PyTorch:入门与实战》)
MIT License
11.99k stars 3.73k forks source link

第六章 配置文件 #190

Open GYE19970220 opened 4 years ago

GYE19970220 commented 4 years ago

小弟只有一事不明,在第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')    #???????????????????????????????

    print('user config:')
    for k, v in self.__class__.__dict__.items():#实例对应的类的属性
        if not k.startswith('_'):               #如果不是以'__'开头
            print(k, getattr(self, k))          #打印值

opt = DefaultConfig()` 求各位大佬帮助解惑

LawsonAbs commented 4 years ago

建议把Python语法学一遍

wzhings commented 4 years ago

不知道LZ搞懂了没有? 我的理解是_parse()函数在创建opt实例的时候还没有被调用,它不检查内部的实现。但是在main.py 里面执行 opt._parse(kwargs) 这句时候,它才会进到内部去检查,发现已经有了一个opt的实例,并且追加一个属性(device)。 如果你有更好的理解,可以跟我交流,谢谢。