【问题标题】:PyTorch bool value of tensor with more than one value is ambiguous具有多个值的张量的 PyTorch bool 值不明确
【发布时间】:2022-04-27 23:32:53
【问题描述】:

我正在尝试使用 PyTorch 训练神经网络,但我得到了标题中的错误。我关注了this tutorial,我只是应用了一些小改动来满足我的需求。这是网络:

class ChordClassificationNetwork(nn.Module):
    def __init__(self, train_model=False):
        super(ChordClassificationNetwork, self).__init__()
        self.train_model = train_model
        self.flatten = nn.Flatten()
        self.firstConv = nn.Conv2d(3, 64, (3, 3))
        self.secondConv = nn.Conv2d(64, 64, (3, 3))
        self.pool = nn.MaxPool2d(2)
        self.drop = nn.Dropout(0.25)
        self.fc1 = nn.Linear(33856, 256)
        self.fc2 = nn.Linear(256, 256)
        self.outLayer = nn.Linear(256, 7)

    def forward(self, x):
        x = self.firstConv(x)
        x = F.relu(x)
        x = self.pool(x)
        x = self.secondConv(x)
        x = F.relu(x)
        x = self.pool(x)
        x = self.drop(x)
        x = self.flatten(x)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = F.relu(x)
        x = self.drop(x)
        x = self.outLayer(x)
        output = F.softmax(x, dim=1)
        return output 

以及导致错误的准确检查部分:

device = ("cuda" if torch.cuda.is_available() else "cpu")

transformations = transforms.Compose([
     transforms.Resize((100, 100))
])

num_epochs = 10
learning_rate = 0.001
train_CNN = False
batch_size = 32
shuffle = True
pin_memory = True
num_workers = 1

dataset = GuitarDataset("../chords_data/cropped_images/train", transform=transformations)
train_set, validation_set = torch.utils.data.random_split(dataset, [int(0.8 * len(dataset)), len(dataset) - int(0.8*len(dataset))])
train_loader = DataLoader(dataset=train_set, shuffle=shuffle, batch_size=batch_size, num_workers=num_workers,
                          pin_memory=pin_memory)
validation_loader = DataLoader(dataset=validation_set, shuffle=shuffle, batch_size=batch_size, num_workers=num_workers,
                               pin_memory=pin_memory)

model = ChordClassificationNetwork().to(device)

criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)


def check_accuracy(loader, model):
    if loader == train_loader:
        print("Checking accuracy on training data")
    else:
        print("Checking accuracy on validation data")

    num_correct = 0
    num_samples = 0
    model.eval()

    with torch.no_grad():
        for x, y in loader:
            x = x.to(device=device)
            y = y.to(device=device)

            scores = model(x)
            predictions = torch.tensor([1.0 if i >= 0.5 else 0.0 for i in scores]).to(device)
            num_correct += (predictions == y).sum()
            num_samples += predictions.size(0)
            print(
                f"Got {num_correct} / {num_samples} with accuracy {float(num_correct) / float(num_samples) * 100:.2f}"
            )
    return f"{float(num_correct) / float(num_samples) * 100:.2f}"


def train():
    model.train()
    for epoch in range(num_epochs):
        loop = tqdm(train_loader, total=len(train_loader), leave=True)
        if epoch % 2 == 0:
            loop.set_postfix(val_acc=check_accuracy(validation_loader, model))
        for imgs, labels in loop:
            imgs = imgs.to(device)
            labels = labels.to(device)
            outputs = model(imgs)
            loss = criterion(outputs, labels)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            loop.set_description(f"Epoch [{epoch}/{num_epochs}]")
            loop.set_postfix(loss=loss.item())


if __name__ == "__main__":
    train()

错误是在这一行引起的:predictions = torch.tensor([1.0 if i >= 0.5 else 0.0 for i in scores]).to(device) 但我不明白为什么。我看到了其他一些答案,但这些都无法解决我的问题。

完整的堆栈跟踪:

  0%|          | 0/13 [00:00<?, ?it/s]Checking accuracy on validation data
Traceback (most recent call last):
  File "/home/deffo/Documents/Unimore/Magistrale/Computer Vision and Cognitive Systems/Guitar_Fingering_&_Chords_Recognition/ChordsClassification/train_CCN.py", line 80, in <module>
    train()
  File "/home/deffo/Documents/Unimore/Magistrale/Computer Vision and Cognitive Systems/Guitar_Fingering_&_Chords_Recognition/ChordsClassification/train_CCN.py", line 66, in train
    loop.set_postfix(val_acc=check_accuracy(validation_loader, model))
  File "/home/deffo/Documents/Unimore/Magistrale/Computer Vision and Cognitive Systems/Guitar_Fingering_&_Chords_Recognition/ChordsClassification/train_CCN.py", line 52, in check_accuracy
    predictions = torch.tensor([1.0 if i >= 0.5 else 0.0 for i in scores]).to(device)
  File "/home/deffo/Documents/Unimore/Magistrale/Computer Vision and Cognitive Systems/Guitar_Fingering_&_Chords_Recognition/ChordsClassification/train_CCN.py", line 52, in <listcomp>
    predictions = torch.tensor([1.0 if i >= 0.5 else 0.0 for i in scores]).to(device)
RuntimeError: Boolean value of Tensor with more than one value is ambiguous
  0%|          | 0/13 [00:02<?, ?it/s]

【问题讨论】:

  • 您似乎期望 7 类(outLayer 的定义),但您在准确度计算中只处理标签 01。另外请修复您的模型,它无效(请参阅我在您其他帖子中的回答)。
  • @Ivan 对模型感到抱歉,这只是一个复制/粘贴错误,但我已修复它,实际上错误现在不同了。无论如何,我不明白如何处理所有 7 个类...我需要更改什么?
  • 请提供与您的代码当前状态相对应的完整错误回溯。
  • @Ivan 问题更新了堆栈跟踪

标签: python neural-network pytorch


【解决方案1】:

模型的输出将是 7 个类的离散分布。要检索预测图像,您可以直接对其应用 argmax:

scores = model(x)
predictions = scores.argmax(1)

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 2019-03-27
    • 2020-02-16
    • 2020-08-03
    • 1970-01-01
    • 2019-11-14
    • 2021-12-07
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多