赞
踩
对着敲代码时常会遇到零星问题,本篇博客意在记录实现过程中琐碎知识点,边学边记~
报错: Expected object of scalar type Double but got scalar type Float for argument #2 ‘mat2’
异常代码行:
def linreg(X, w, b):
return torch.mm(X, w) + b
解决:
features = torch.randn(num_examples, num_inputs,dtype=torch.float32)
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()),dtype=torch.float32)
补充:
@torchsnooper.snoop()
def linreg(X, w, b):
return torch.mm(X, w) + b
Pytorch optimizer.step() 和loss.backward()和scheduler.step()的关系与区别 (Pytorch 代码讲解)
优化器工作需要两个东西
optimizer = optim.SGD(net.parameters(), lr=0.03)
net.parameters()
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] for p in group['params']: if p.grad is None: continue d_p = p.grad.data if weight_decay != 0: d_p.add_(weight_decay, p.data) if momentum != 0: param_state = self.state[p] if 'momentum_buffer' not in param_state: buf = param_state['momentum_buffer'] = torch.clone(d_p).detach() else: buf = param_state['momentum_buffer'] buf.mul_(momentum).add_(1 - dampening, d_p) if nesterov: d_p = d_p.add(momentum, buf) else: d_p = buf p.data.add_(-group['lr'], d_p) return loss
基于上述两方面,优化三步走 (求导和优化是两个步骤)
optimizer.zero_grad()
l.backward()
optimizer.step()
报错: import torchvision时提示ImportError: DLL load failed: 找不到指定的模块
解决: torch 和 torchvision版本是有匹配要求的,我的pytorch是1.1.0版本,试过其他教程提供的torchvision版本 都失败了。按照这个安装导入成功。
pip install torchvision==0.2.2.post3 -i https://pypi.tuna.tsinghua.edu.cn/simple
d2lzh_pytorch.ipynb
这样的后缀jupyter nbconvert --to script d2lzh_pytorch.ipynb
,转完之后就可以import了Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。