首页 > 其他分享 >PyTorchStepByStep - Chapter 2: Rethinking the Training Loop

PyTorchStepByStep - Chapter 2: Rethinking the Training Loop

时间:2024-10-12 21:34:10浏览次数:9  
标签:Chapter Rethinking Training tensor loss step train model fn

 

 

def make_train_step_fn(model, loss_fn, optimizer):
    def perform_train_step_fn(x, y):
        # Set model to TRAIN mode
        model.train()

        # Step 1 - Compute model's predictions - forward pass
        yhat = model(x)

        # Step 2 - Compute the loss
        loss = loss_fn(yhat, y)

        # Step 3 - Compute the gradients for both parameters "b" and "w"
        loss.backward()

        # Step 4 - Update parameters using gradients and the learning rate
        optimizer.step()
        optimizer.zero_grad()

        # Return the loss
        return loss.item()
    
    return perform_train_step_fn

 

%%writefile model_configuration/v1.py

device = 'cuda' if torch.cuda.is_available() else 'cpu'

# Set learning rate
lr = 0.1

torch.manual_seed(42)

model = nn.Sequential(nn.Linear(1, 1)).to(device)

# Define an SGD optimizer to update the parameters (now retrieved directly from the model)
optimizer = torch.optim.SGD(model.parameters(), lr=lr)

# Define an MSE loss function
loss_fn = nn.MSELoss(reduction='mean')

# Create the train_step function for model, loss function and optimizer
train_step_fn = make_train_step_fn(model, loss_fn, optimizer)

 

 

%%writefile model_training/v1.py

n_epochs = 1000

losses = []

for epoch in range(n_epochs):
    # Perform one train step and return the corresponding loss
    loss = train_step_fn(x_train_tensor.reshape(-1, 1), y_train_tensor.reshape(-1, 1))
    losses.append(loss)

 

 

class CustomDataset(Dataset):
    def __init__(self, x_tensor, y_tensor):
        self.x = x_tensor
        self.y = y_tensor

    def __getitem__(self, index):
        return (self.x[index], self.y[index])

    def __len__(self):
        return len(self.x)

# Wait, is this a CPU tensor now? Why? Where is .to(device)?
x_train_tensor = torch.from_numpy(x_train).float()
y_train_tensor = torch.from_numpy(y_train).float()

train_data = CustomDataset(x_train_tensor, y_train_tensor)
print(train_data[0])  # (tensor(0.8446), tensor(2.8032))

 

 

标签:Chapter,Rethinking,Training,tensor,loss,step,train,model,fn
From: https://www.cnblogs.com/zhangzhihui/p/18461534

相关文章

  • Cornell cs3110 - Chapter9 Lessons
    使用Menhir构建SimPL的编译器LexerandParser语法分析模块Lexer,Parser,AST是三个依次耦合的模块,可以这么描述三者的关系:Lexer---tokens-->Parser---nodes-->AST相对于上面的图像化描述,cs3110反过来构建整个Lexer和Parser的结构在ast.ml中,定义了AST上......
  • 《M5Product: Self-harmonized Contrastive Learning for E-commercial Multi-modal P
    系列论文研读目录文章目录系列论文研读目录摘要1.引言2.相关工作3.M5Product数据集4.我们的方法4.1.SCALE框架设计4.2.借助掩蔽多模态任务的SCALE4.3.自我和谐的通道间对比学习5.实验5.1.模态多样性5.2.多模式下游任务5.3.消融研究和可视化6.局限性和今后的工作7.结......
  • Cornell cs3110 - Chapter7 Exercises
    (*Exercise:mutablefields*)typestudent={name:string;mutablegpa:float;}letstuA={name="Alice";gpa=3.7}let()=stuA.gpa<-4.0(*Exercise:intfun*)letinc=ref(funx->x+1)letnum=!inc3109(*Exercise:a......
  • 2017中国大学生程序设计竞赛 - 女生专场(SDKD 2024 Summer Training Contest K2)
    A-AutomaticJudge题意\(n\)个问题,\(m\)条记录,每条记录有题号、时间、状态,第一次\(AC\)的时候计入罚时,其他没发罚\(20\)分钟。求队伍过题数和罚时。思路模拟。代码点击查看代码#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongvoidsolve()......
  • Cornell cs3110 - Chapter6 Exercises
    (*Exercise:specgame*)(*Whereisanotherprogrammer?*)(*Exercise:polyspec*)(*[Poly]representsimmutablepolynomialswithintegercoeffcients*)moduletypePoly=sig(*[t]isthetypeofpolynomials*)typet(*[evalxp]is[p]e......
  • Cornell cs3110 - Chapter5 Exercises
    (*Exercise:complexsynonym*)moduletypeComplexSig=sigtypecomplexvalzero:complexvaladd:complex->complex->complexend(*Exercise:complexencapsulation*)moduleComplex:ComplexSig=structtypecomplex=float*flo......
  • 【HITCON-Training】Lab 14 - MagicHeap
    学习于2024-10-0312:50:42星期四心得感想:分析ida一打开就看到很明显的提示(毕竟是教学关卡):那么我们需要将magic修改为一个大于0x1305的数,并且该程序没有开PIE,那么magic地址就是固定的。Delete操作删的非常彻底,很明显这里没有任何可以利用的:Create部分看起也没有任何问题......
  • 【HITCON-Training】Lab 12 - SecretGarden
    学习于2024-10-0122:00:17星期二心得感想:这次真的把我整笑了,现在是10/2的晚上23点,我都不敢想象自己弄了多久(整整两天国庆的下午......
  • Cornell cs3110 - Chapter4 Exercises
    (*Exercise:mysteryoperator1*)let($)fx=fx;;(*使得函数的连续调用具有一部分右结合的特质square$2+2与square2+2的运行结果分别是16和6*)(*Exercise:repeat*)letrecrepeatfnx=matchnwith|0->x|_->repeatf(n-1)......
  • Cornell cs3110 - Chapter3 Exercises
    (*Exercise:listexpressions*)letlist1=[1;2;3;4;5];;letlist2=1::2::3::4::5::[];;letlist3=[1]@[2;3;4;]@[5];;(*Exercise:product*)letrecproductl=matchlwith|[]->1|h::t->h*productt;;(*......