import torch
from torch import nn
from torch import optim
import numpy as np
from matplotlib import pyplot as plt
import time
# 1. 定义数据
x = torch.rand([50,1])
y = x*3 + 0.8
#2 .定义模型
class Lr(nn.Module):
def __init__(self):
super(Lr,self).__init__()
self.linear = nn.Linear(1,1)
def forward(self, x):
out = self.linear(x)
return out
# 3. 实例化模型,loss,和优化器
epoch = 3500 # 迭代次数
lr=0.001 # 学习率
if torch.cuda.is_available():
model = Lr().cuda()
else:
model = Lr()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(),lr=lr)
#4. 训练模型
for i in range(epoch):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
x,y = x.to(device),y.to(device)
out = model(x)
loss = criterion(y,out)
o