Pytorch RNN具有准确性0.0

发布于 2025-01-21 19:17:12 字数 1507 浏览 0 评论 0原文

我试图运行以下代码,但输出为[0.0,0.0]。我想这个shld不会发生,但似乎无法弄清可能导致这个问题的原因。知道什么可能出了什么问题吗?感谢任何帮助,谢谢

def load_array(data_arrays, batch_size, is_train=True): 
    """Construct a PyTorch data iterator."""
    dataset = data.TensorDataset(*data_arrays)
    return data.DataLoader(dataset, batch_size, shuffle=is_train)

data_iter = load_array((train_x, train_y), 1)

class extractlastcell(nn.Module):
  def forward(self,x):
    out , _ = x
    return out[:, -1, :]

net= nn.Sequential(
    nn.Embedding(5000, 256), 
    nn.LSTM(256, 32), 
    extractlastcell(),
    nn.Linear(32, 16), nn.Softmax())

def init_weights(m): 
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights)

def train_model(train_dl, model, epoch):
    train_ls = []
    # define the optimization
    loss = nn.BCELoss(reduction='none')
    trainer = torch.optim.Adam(net.parameters(), lr=0.1)
    # enumerate epochs
    for epoch in range(epoch):
        # enumerate mini batches
        for i, (inputs, targets) in enumerate(train_dl):
            # clear the gradients
            trainer.zero_grad()
            # compute the model output
            yhat = model(inputs)
            # calculate loss
            l = loss(yhat, targets)
            # credit assignment
            l.sum().backward()
            # update model weights
            trainer.step()
        
        train_ls.append(d2l.evaluate_accuracy(net, train_dl))
    return train_ls

train_model(data_iter,net,2)

I tried to run the following code but the output is [0.0, 0.0]. I suppose this shld not happen, but cannot seem to figure out what could be causing this issue. Any idea what could have gone wrong? Appreciate any help, thanks

def load_array(data_arrays, batch_size, is_train=True): 
    """Construct a PyTorch data iterator."""
    dataset = data.TensorDataset(*data_arrays)
    return data.DataLoader(dataset, batch_size, shuffle=is_train)

data_iter = load_array((train_x, train_y), 1)

class extractlastcell(nn.Module):
  def forward(self,x):
    out , _ = x
    return out[:, -1, :]

net= nn.Sequential(
    nn.Embedding(5000, 256), 
    nn.LSTM(256, 32), 
    extractlastcell(),
    nn.Linear(32, 16), nn.Softmax())

def init_weights(m): 
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights)

def train_model(train_dl, model, epoch):
    train_ls = []
    # define the optimization
    loss = nn.BCELoss(reduction='none')
    trainer = torch.optim.Adam(net.parameters(), lr=0.1)
    # enumerate epochs
    for epoch in range(epoch):
        # enumerate mini batches
        for i, (inputs, targets) in enumerate(train_dl):
            # clear the gradients
            trainer.zero_grad()
            # compute the model output
            yhat = model(inputs)
            # calculate loss
            l = loss(yhat, targets)
            # credit assignment
            l.sum().backward()
            # update model weights
            trainer.step()
        
        train_ls.append(d2l.evaluate_accuracy(net, train_dl))
    return train_ls

train_model(data_iter,net,2)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文