I have a tensor size of 1x2x32x32x32
. I want to feed it into spatial transformation network using the tutorial in pytorch. I have change the size of fc based on my input size. The final size before send to the grid = F.affine_grid(theta, x.size())
is
theta: (1,6)
x (1,2,32,32,32)
However, I got the error. How should I fix it? You can run my code in the colab at Google Colab
ret = torch.affine_grid_generator(theta, size)
RuntimeError: invalid argument 6: wrong matrix size at /opt/conda/conda-bld/pytorch-nightly_1555305720252/work/aten/src/THC/generic/THCTensorMathBlas.cu:494
This is my code
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np
plt.ion() # interactive mode
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Spatial transformer localization-network
self.localization = nn.Sequential(
nn.Conv3d(2, 8, kernel_size=7),
nn.MaxPool3d(2, stride=2),
nn.ReLU(True),
nn.Conv3d(8, 10, kernel_size=5),
nn.MaxPool3d(2, stride=2),
nn.ReLU(True)
)
# Regressor for the 3 * 2 affine matrix
self.fc_loc = nn.Sequential(
nn.Linear(10 * 4 * 4 * 4, 32),
nn.ReLU(True),
nn.Linear(32, 3 * 2)
)
# Initialize the weights/bias with identity transformation
self.fc_loc[2].weight.data.zero_()
self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))
# Spatial transformer network forward function
def stn(self, x):
xs = self.localization(x)
print (xs.size())
xs = xs.view(-1, 10 * 4 * 4 * 4)
theta = self.fc_loc(xs)
theta = theta.view(-1, 2, 3)
grid = F.affine_grid(theta, x.size())
x = F.grid_sample(x, grid)
return x
def forward(self, x):
# transform the input
x = self.stn(x)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = Net().to(device)
x = torch.rand(1,2,32,32,32).to(device)
print('Input shape', x.shape)
x_stn = model(x)