根据训练有素的卷积网络进行预测

时间:2018-08-22 11:09:22

标签: neural-network deep-learning computer-vision conv-neural-network pytorch

这是我的convolution网络,它创建训练数据,然后使用激活了convolution的单个relu对这些数据进行训练:

train_dataset = []
mu, sigma = 0, 0.1 # mean and standard deviation
num_instances = 10

for i in range(num_instances) :
    image = []
    image_x = np.random.normal(mu, sigma, 1000).reshape((1 , 100, 10))
    train_dataset.append(image_x)

mu, sigma = 100, 0.80 # mean and standard deviation
for i in range(num_instances) :
    image = []
    image_x = np.random.normal(mu, sigma, 1000).reshape((1 , 100, 10))
    train_dataset.append(image_x)

labels_1 = [1 for i in range(num_instances)]
labels_0 = [0 for i in range(num_instances)]

labels = labels_1 + labels_0

print(labels)

x2 = torch.tensor(train_dataset).float()
y2 = torch.tensor(labels).long()

my_train2 = data_utils.TensorDataset(x2, y2)
train_loader2 = data_utils.DataLoader(my_train2, batch_size=batch_size_value, shuffle=False)


import torch 
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms


# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# device = 'cpu'

# Hyper parameters
num_epochs = 50
num_classes = 2
batch_size = 5
learning_rate = 0.001

# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
    def __init__(self, num_classes=1):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc = nn.Linear(32*25*2, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

model = ConvNet(num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader2)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader2):
        images = images.to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i % 10) == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

我要使用一个预测:

model(x2[10].unsqueeze_(0).cuda())

哪个输出:

tensor([[ 4.4880, -4.3128]], device='cuda:0')

这是否不返回预测形状(100,10)的图像张量?

更新:为了执行预测,我使用:

torch.argmax(model(x2[2].unsqueeze_(0).cuda()), dim=1) 

src:https://discuss.pytorch.org/t/argmax-with-pytorch/1528/11

在这种情况下,

torch.argmax返回使预测最大化的值的位置。

1 个答案:

答案 0 :(得分:1)

Koustav所述,您的网络不是“完全卷积”的:尽管您有两个nn.Conv2d层,但是您的网络上仍然有一个“完全连接”(也称为nn.Linear)层顶部,仅输出二维(num_classes)输出张量。

更具体地说,您的网络期望输入1x100x10(单通道,100 x 10像素的图像)。
self.layer1之后,您有一个16x50x5张量(卷积中的16个通道,空间尺寸由最大池化层减少)。
self.layer2之后,您有一个32x25x2张量(卷积中的32个通道,空间尺寸减少了另一个最大池化层)。
最后,完全连接的self.fc nn.Linear层将获取整个32*25*2维输入张量,并从整个输入中产生一个num_classes输出。