Reputation: 53796
Here is my convolution
net that creates training data , then trains on this data using a single convolution
with relu
activation :
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()))
To make a single prediction I use :
model(x2[10].unsqueeze_(0).cuda())
Which outputs :
tensor([[ 4.4880, -4.3128]], device='cuda:0')
Should this not return an image tensor of shape (100,10) of the prediction ?
Update : In order to perform a prediction I use :
torch.argmax(model(x2[2].unsqueeze_(0).cuda()), dim=1)
src : https://discuss.pytorch.org/t/argmax-with-pytorch/1528/11
torch.argmax
in this context returns the position of the value that maximises the prediction.
Upvotes: 1
Views: 169
Reputation: 114786
As noted by Koustav your net is not "fully convolutional": although you have two nn.Conv2d
layers, you still have a "fully-connected" (aka nn.Linear
) layer on top, which outputs only 2 dimensional (num_classes
) output tensor.
More specifically, your net expects a 1x100x10 input (single channel, 100 by 10 pixels image).
After self.layer1
you have a 16x50x5 tensor (16 channels from the convolution, spatial dimensions reduced by max pooling layer).
After self.layer2
you have a 32x25x2 tensor (32 channels from the convolution, spatial dimensions reduced by another max pooling layer).
Finally, your fully connected self.fc
nn.Linear
layer takes the entire 32*25*2
dimensional input tensor and produces a num_classes
output from the entire input.
Upvotes: 1