PyTorch: Checking Model Accuracy Results in "TypeError: 'bool' object is not iterable."

PyTorch: Checking Model Accuracy Results in "TypeError: 'bool' object is not iterable."

我正在训练神经网络并想检查其准确性。我使用 Librosa 和 SciKitLearn 以一维 Numpy 数组的形式表示音频。因此 x_train, x_test, y_train, y_test 都是一维 Numpy 数组,其中 x_* 数组包含浮点数,y_* 数组包含对应于 class 数据的字符串。例如:

x_train = [0.235, 1.101, 3.497]
y_train = ['happy', 'angry', 'neutral'] 

我写了一个字典来将这些 classes(字符串)表示为整数:

emotions = {
'01' : 'neutral',
'02' : 'calm',
'03' : 'happy',
'04' : 'sad',
'05' : 'angry',
'06' : 'fearful',
'07' : 'disgust',
'08' : 'surprised'}

emotion_list = list(emotions.values())

接下来我定义了一个 class 来转换此数据,以便它可以传递给 torch.utils.data.DataLoader():

class MakeDataset(Dataset):
    def __init__(self, x_train, y_train):
        self.x_train = torch.FloatTensor(x_train)
        self.y_train = torch.FloatTensor([emotion_list.index(each) for each in y_train])
    def __len__(self):
        return self.x_train.shape[0]
    def __getitem__(self, ind):
        x = self.x_train[ind]
        y = emotion_list.index(y_train[ind])
        return x, y

我定义了训练集、测试集、批量大小,并加载数据:

train_set = MakeDataset(x_train, y_train)
test_set = MakeDataset(x_test, y_test)

batch_size = 512

train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False)

我定义模型、训练和测试如下:

class TwoLayerMLP(torch.nn.Module):
    def __init__(self, D_in, H, D_out):
        super(TwoLayerMLP, self).__init__()
        self.linear1 = torch.nn.Linear(D_in, H)
        self.linear2 = torch.nn.Linear(H, D_out)

    def forward(self, x):
        h_relu = self.linear1(x).clamp(min=0)
        y_pred = self.linear2(h_relu)
        return y_pred


model = TwoLayerMLP(180, 90, 8)
optimizer = torch.optim.Adam(model.parameters())
criterion = nn.CrossEntropyLoss()

epochs = 5000

total_train = 0
correct_train = 0
for epoch in range(epochs):
    model.train()
    running_loss = 0.0
    for batch_num, data in enumerate(train_loader):
        audio , label = data
        optimizer.zero_grad()
        outputs = model(audio.float())
        loss = criterion(outputs, label)
        loss.backward()
        optimizer.step()
        
        predicted = torch.max(outputs.data,1)
        total_train += float(label.size(0))
        
        # Code runs with line below commented 
        # Else returns "TypeError: 'bool' object not iterable."
        correct_train += sum(predicted == label)

请注意,此代码已更新,以前有问题的行是:

correct_train += float((predicted == label)).sum()

谁能解释为什么不能按预期迭代此布尔对象?

已解决

请参阅下面 abhiskk 的回答中的评论,但为了清楚和简洁起见,以下更改解决了问题:

pred_values, pred_indices = torch.max(outputs.data,1)
total_train += float(label.size(0))
correct_train += (sum(pred_indices == label)).item()

预测变量包含值和索引,你需要做pred_vals, pred_inds = torch.max(outputs.data, 1)然后你可以做correct_train += (sum(pred_inds == label)).item()

另外求和前不需要转为浮点数,可以使用:

(predicted == label).sum().item()

(predicted == label) returns一个BoolTensor可以求和得到一个浮点值。

替换

correct_train += float((predicted == label)).sum()

correct_train += sum(predicted == label)

您不需要将布尔张量转换为浮点数,sum 函数足够智能,可以将 False 转换为 0,将 True 转换为 1