Escapist367
2020-10-16 18:16:21 +08:00
import torch
inputs=[]
outputs=[]
for year1 in range(1900,2020):
for year2 in range(1900,2020):
for age1 in range(0,120):
inputs.append([year1,year2,age1])
outputs.append([year2-year1+age1])
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(3, 1)
def forward(self, inputs):
outputs = self.linear(inputs)
return outputs
model = LinearModel().cuda()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for epoch in range(100):
Loss=0
for i in range(len(inputs)//1000):
x=torch.tensor(inputs[i*1000:i*1000+1000]).cuda().float()
y=torch.tensor(outputs[i*1000:i*1000+1000]).cuda().float()
y_pred = model(x)
loss = criterion(y, y_pred)
optimizer.zero_grad()
loss.backward()
optimizer.step()
Loss+=loss.item()
print("Loss:%.2f"%Loss)
print("1999 年 45 岁的人在 2020 年为%.0f 岁"%model(torch.tensor([1999,2020,45]).cuda().float()))
print("1927 年 15 岁的人在 2020 年为%.0f 岁"%model(torch.tensor([1927,2020,15]).cuda().float()))
print("1979 年 77 岁的人在 2020 年为%.0f 岁"%model(torch.tensor([1979,2020,77]).cuda().float()))