How to input a matrix to CNN in pytorch

WIND.Knight Source

I'm very new to pytorch and I want to figure out how to input a matrix rather than image into CNN. I have try it in the following way, but some errors occur. I define my dataset as following:

class FrameDataSet(tud.Dataset):
    def __init__(self, data):
        targets = data['class'].values.tolist()
        features = data.drop('class', axis=1).astype(np.int64).values

        self.datalist = features.reshape((-1, feature_num, frame_size))
        self.labellist = targets

    def __getitem__(self, index):
        return torch.Tensor(self.datalist[index].astype(float)), self.labellist[index]

    def __len__(self):
        return self.datalist.shape[0]

And my CNN is:

self.conv = nn.Sequential(
        nn.Conv2d(1, 12, 3),
        nn.MaxPool2d(3, 3))
self.fc1 = nn.Linear(80, 100)
self.fc2 = nn.Linear(100, 30)
self.fc3 = nn.Linear(30, 5)

But when the data was inputted to CNN, the error brings:

File "/home/sparks/anaconda2/lib/python2.7/site-packages/torch/nn/", line 48, in conv2d raise ValueError("Expected 4D tensor as input, got {}D tensor instead.".format(input.dim())) Expected 4D tensor as input, got 3D tensor instead.



answered 11 months ago loose11 #1

Your input probably missing one dimension. It should be:

(batch_size, channels, width, height)

If you only have one element in the batch, the tensor have to be in your case

e.g (1, 1, 28, 28)

because your first conv2d-layer expected a 1-channel input.

comments powered by Disqus