我正在尝试使用 pytorch 实现多元时间序列。在这里,我仅给出出现错误的那部分代码,但我已将所有提到的类包含在我的完整代码中。该代码已引用自https://towardsdatascience.com/building-rnn-lstm-and-gru-for-time-series-using-pytorch-a46e5b094e7b
class Optimization:
def __init__(self, model, loss_fn, optimizer):
self.model = model
self.loss_fn = loss_fn
self.optimizer = optimizer
self.train_losses = []
self.val_losses = []
def train_step(self, x, y):
# Sets model to train mode
self.model.train()
# Makes predictions
yhat = self.model(x)
# Computes loss
loss = self.loss_fn(y, yhat)
# Computes gradients
loss.backward()
# Updates parameters and zeroes gradients
self.optimizer.step()
self.optimizer.zero_grad()
# Returns the loss
return loss.item()
import torch.optim as optim
def get_model(model, model_params):
models = {
"rnn": RNNModel,
"lstm": LSTMModel,
"gru": GRUModel,
}
return models.get(model.lower())(**model_params)
input_dim = len(X_train.columns)
output_dim = 1
hidden_dim = 64
layer_dim = 3
batch_size = 64
dropout = 0.2
n_epochs = 100
learning_rate = 1e-3
weight_decay = 1e-6
model_params = {'input_dim': input_dim,
'hidden_dim' : hidden_dim,
'layer_dim' : layer_dim,
'output_dim' : output_dim,
'dropout_prob' : dropout}
model = get_model('lstm', model_params)
loss_fn = nn.MSELoss(reduction="mean")
optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
opt = Optimization(model=model, loss_fn=loss_fn, optimizer=optimizer)
opt.train(train_loader, val_loader, batch_size=batch_size,
n_epochs=n_epochs, n_features=input_dim)
我收到此错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
e:\codefolder\multivar.ipynb Cell 21 in <cell line: 25>()
22 optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
24 opt = Optimization(model=model, loss_fn=loss_fn, optimizer=optimizer)
---> 25 opt.train(train_loader, val_loader, batch_size=batch_size, n_epochs=n_epochs, n_features=input_dim)
26 opt.plot_losses()
28 predictions, values = opt.evaluate(test_loader_one, batch_size=1, n_features=input_dim)
AttributeError: 'Optimization' object has no attribute 'train'
附注我已将所有类和代码包含到我的代码中,如我提到的文章中给出的那样。由于代码的空间和长度,我只包含了出现错误的主要代码。
你已经写了
opt = Optimization(...)
无需导入或定义该类。 Python 告诉你它无法识别该对象或其方法
我找到了
torch.optim.Optimizer
这里,这可能就是你要找的吗?