douglas1997
2020-05-07 09:58:30 +08:00
哈哈随手写了一个,仅供参考~
```
import torch
import math
# y = 0.11, t=20
def fx2(t):
return 2*math.exp(-t)+3*math.exp(-t/2)+6*math.exp(-t/5)
def fx(inputs):
return inputs[0]*torch.exp(inputs[1]*t)+inputs[2]*torch.exp(inputs[3]*t)+inputs[4]*torch.exp(inputs[5]*t)
inputs = torch.Tensor([2, -1, 3, -0.5, 6, -0.2])
t = torch.ones(1, requires_grad=True)
y = 0.11
optimizer = torch.optim.SGD(params=(t,), lr=0.5)
criterion = torch.nn.MSELoss()
for i in range(2000):
optimizer.zero_grad()
y_pred = fx(inputs)
loss = criterion(y_pred, torch.Tensor([y]))
loss.backward()
optimizer.step()
print (i, loss)
print (t)
final_t = t.item()
print ("t: {}, y: {}, y_pred: {}".format(final_t, y, fx2(final_t)))
```
最后结果`t: 20.136356353759766, y: 0.11, y_pred: 0.10706461213461692`。