pytorch基础

本文介绍了PyTorch中训练模型的基本顺序,强调了反向传播的位置灵活性,同时也讲解了如何在不同版本的PyTorch中将模型和数据迁移到GPU上进行计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.训练时顺序
    #第一种写法
    
    #梯度置零,也就是把loss关于weight的导数变成0
    optimizer.zero_grad()
    
    #前馈计算输出和损失
    outputs = net(images)
    loss = criterion(outputs, labels)
    
    #反向传播
    loss.backward()
    optimizer.step()

	#第二种写法
	
	#前馈计算输出和损失
	outputs = net(images)
	loss = criterion(outputs, labels)
    
    #梯度置零,也就是把loss关于weight的导数变成0
    optimizer.zero_grad()
    
    #反向传播
    loss.backward()
    optimizer.step()
不管哪种写法,都是最后进行反向传播,至于梯度置0和前馈计算谁先谁后都行。
2.使用gpu
#1.设置decive,下面是一些常用的写法
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device = torch.device('cuda:0') or  device = torch.device('cuda',0)
device = torch.device('cuda',1)  or torch.device('cpu',0)   
    
#2.定义的损失需要放到gpu中,用.to(device)
self.bce_with_logits_loss = nn.BCEWithLogitsLoss().to(device)

#3.模型需要放到gpu中,用.to(device)
model = NeuralNet().to(device)

for i, (images, labels) in enumerate(train_loader):
	#4.训练的images和labels需要放到gpu中,用.to(device)
    images = images.reshape(-1, 28 * 28).to(device)
    labels = labels.to(device)
对于1.0及以上版本使用 .to(device),低版本的可能会使用.cuda(),作用是一样的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值