首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PyTorch -从预测中接收0填充列表

PyTorch -从预测中接收0填充列表
EN

Stack Overflow用户
提问于 2022-11-26 04:45:28
回答 1查看 40关注 0票数 -1

发行:

代码语言:javascript
运行
复制
EXPECTED:tensor([[1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.,
         0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
         0., 0., 1., 1.]], dtype=torch.float64)
ACTUAL:tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], device='cuda:0')

我正在构建自己的数据采集器,其中我有一个图像列表,每个图像都有40个属性,每个属性都是0或1。例如:索引1可能表示“吸引”,而索引2可能表示“大鼻子”。

我试图在每个数字的旁边发送一个这些数字的列表,该列表中的每个索引对应于一个属性,与该图像相关的是0或1。

我的问题是,当训练时,预测值都是0。

在dataloader中获取项,在图像中发送一个名为“属性”的数字列表

代码语言:javascript
运行
复制
    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()


        img_name = os.path.join(self.root_dir,
                                self.malefemale_frame.iloc[idx, 0])
        image = read_image(img_name)
        

        attributes = self.malefemale_frame.iloc[idx, 2:]
        attributes = [float(i) for i in attributes]
        attributes = torch.from_numpy(np.asarray(attributes))
        #print(attributes)
        return image.float(), attributes

这里使用的批次大小

代码语言:javascript
运行
复制
import torch
import torchvision
import torchvision.transforms as transforms
import os
transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

batch_size = 8

trainset = MaleFemaleDataset(csv_file='attribute-files/CelebAMask-HQ-attribute-anno.txt', root_dir='CelebA-HQ-img//',transform=transform,train=True)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
                                          shuffle=True, num_workers=0)

testset = MaleFemaleDataset(csv_file='attribute-files/CelebAMask-HQ-attribute-anno.txt', root_dir='CelebA-HQ-img//',transform=transform,train=False)

testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
                                         shuffle=False, num_workers=0)

print("Training/Testing sets initialized")
代码语言:javascript
运行
复制
criterion = nn.CrossEntropyLoss(reduction='none')
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

训练回路

代码语言:javascript
运行
复制
for epoch in range(1):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        inputs, labels = data[0].to(device), data[1].to(device)
        #print(data[1])
        optimizer.zero_grad()
        outputs = net(inputs.to(device))
        loss = criterion(outputs, labels)
        loss.backward(gradient=torch.ones_like(loss))
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        if i % 100 == 99:    # print every 100 mini-batches
            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 100:.3f}')
            running_loss = 0.0

print('Finished Training')

再好不过30.

代码语言:javascript
运行
复制
[1,   100] loss: 33.356
[1,   200] loss: 36.982
[1,   300] loss: 36.495
[1,   400] loss: 33.763
...etc

测试回路

代码语言:javascript
运行
复制
correct, total = 0, 0
with torch.no_grad():

# Iterate over the test data and generate predictions
    for i, data in enumerate(testloader, 0):

      # Get inputs
        inputs, targets = data

      # Generate outputs
        outputs = net(inputs.to(device))

        # Set total and correct
        _, predicted = torch.max(outputs, 0)
        total += targets.size(0)
        print("EXPECTED:"+ str(targets))
        print("ACTUAL:"+ str(predicted.tolist()))
        #for predict in predicted:
        #    print(predict.item())
        correct += (predicted == targets).sum().item()

    # Print accuracy
    print('Accuracy: %d %%' % (100 * correct / total))

最终输出

代码语言:javascript
运行
复制
EXPECTED:tensor([[1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.,
         0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
         0., 0., 1., 1.]], dtype=torch.float64)
ACTUAL:tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], device='cuda:0')
EN

回答 1

Stack Overflow用户

发布于 2022-11-26 23:57:52

我通过修改我的测试循环让它工作起来。我删除了torch.max()函数,只返回了从网络中得到的值。

代码语言:javascript
运行
复制
correctAttributes = 0
threshold = .5
with torch.no_grad():

for i, data in enumerate(testloader, 0):

    # Get inputs
    inputs, targets = data

    # Generate outputs
    outputs = net(inputs.to(device))
    
    #Check predictions
    for predictedAttributes, targetAttributes in zip(outputs.tolist(), targets.tolist()):
        for predictedAttribute, targetAttribute in zip(predictedAttributes, targetAttributes):
            if predictedAttribute > threshold and targetAttribute > threshold:
                correctAttributes+=1
            elif predictedAttribute < threshold and targetAttribute < threshold:
                correctAttributes+=1
            total+=1

# Print accuracy
print('Accuracy: %d %%' % (100 * correctAttributes / total))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74579784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档