Broadcasting Error when trying to apply transforms.Resize()












0














I am trying to resize an image in Pytorch for later processing, while training a neural network. But get a broadcasting error, when I try to call transforms.Resize() on the image.
Here is my code snippet.



cuda:0
Classifier(
(fc1): Linear(in_features=784, out_features=256, bias=True)
(fc2): Linear(in_features=256, out_features=128, bias=True)
(fc3): Linear(in_features=128, out_features=64, bias=True)
(fc4): Linear(in_features=64, out_features=10, bias=True)
)
Traceback (most recent call last):
File "netz.py", line 71, in <module>
train()
File "netz.py", line 46, in train
outputs=model(inputs)
File "/home/yyyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "netz.py", line 18, in forward
x=F.relu(self.fc1(x))
File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/linear.py", line 55, in forward
return F.linear(input, self.weight, self.bias)
File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 1024, in linear
return torch.addmm(bias, input, weight.t())
RuntimeError: size mismatch, m1: [64 x 59536], m2: [784 x 256] at /opt/conda/conda-bld/pytorch_1532584813488/work/aten/src/THC/generic/THCTensorMathBlas.cu:249

---- Corresponding Code ---


import torch
from torch import nn,optim
import torch.nn.functional as F
from torchvision import datasets,transforms

NUM_EPOCH=700
class Classifier(nn.Module):

def __init__(self):
super().__init__()
self.fc1=nn.Linear(784,256)
self.fc2=nn.Linear(256,128)
self.fc3=nn.Linear(128,64)
self.fc4=nn.Linear(64,10)

def forward(self,x):
x=x.view(x.shape[0],-1)
x=F.relu(self.fc1(x))
x=F.relu(self.fc2(x))
x=F.relu(self.fc3(x))
x=F.log_softmax(self.fc4(x),dim=1)
return x




def train():
transform=transforms.Compose([
transforms.Resize(244),
transforms.ToTensor(),
transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
trainset=datasets.FashionMNIST('./data',download=True,transform=transform)
trainloader=torch.utils.data.DataLoader(trainset,batch_size=64,shuffle=True,num_workers=2)
model=Classifier()
model=model.to(device)
criterion=nn.CrossEntropyLoss()
optimizer=optim.Adam(model.parameters(),lr=0.001)

for epoch in range(NUM_EPOCH):
running_loss=0.0
for i, data in enumerate(trainloader,0):
inputs,labels=data
inputs=inputs.to(device)
labels=labels.to(device)
optimizer.zero_grad()
outputs=model(inputs)
outputs.to(device)
loss=criterion(outputs,labels)
loss.backward()
optimizer.step()
running_loss+=loss.item()
if(i%20 == 19):
print("epoch: ",epoch+1)
print("i + 1",i)
print("loss: ",running_loss/20.0)
#print('[%d, 5d] loss: %.3f' %(epoch+1,i+1,running_loss/20))
running_loss=0.0




device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

net=Classifier()
net.to(device)
print(net)
train()


So my question is, what is the most appropriate way to resize images while I am
training the network for my particular use case?



I am using Cuda8.0 and CudaDNN7.1 with Pytorch version 0.4.1 and Python3.7 on Ubuntu 16.04 LTS system.










share|improve this question



























    0














    I am trying to resize an image in Pytorch for later processing, while training a neural network. But get a broadcasting error, when I try to call transforms.Resize() on the image.
    Here is my code snippet.



    cuda:0
    Classifier(
    (fc1): Linear(in_features=784, out_features=256, bias=True)
    (fc2): Linear(in_features=256, out_features=128, bias=True)
    (fc3): Linear(in_features=128, out_features=64, bias=True)
    (fc4): Linear(in_features=64, out_features=10, bias=True)
    )
    Traceback (most recent call last):
    File "netz.py", line 71, in <module>
    train()
    File "netz.py", line 46, in train
    outputs=model(inputs)
    File "/home/yyyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
    result = self.forward(*input, **kwargs)
    File "netz.py", line 18, in forward
    x=F.relu(self.fc1(x))
    File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
    result = self.forward(*input, **kwargs)
    File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/linear.py", line 55, in forward
    return F.linear(input, self.weight, self.bias)
    File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 1024, in linear
    return torch.addmm(bias, input, weight.t())
    RuntimeError: size mismatch, m1: [64 x 59536], m2: [784 x 256] at /opt/conda/conda-bld/pytorch_1532584813488/work/aten/src/THC/generic/THCTensorMathBlas.cu:249

    ---- Corresponding Code ---


    import torch
    from torch import nn,optim
    import torch.nn.functional as F
    from torchvision import datasets,transforms

    NUM_EPOCH=700
    class Classifier(nn.Module):

    def __init__(self):
    super().__init__()
    self.fc1=nn.Linear(784,256)
    self.fc2=nn.Linear(256,128)
    self.fc3=nn.Linear(128,64)
    self.fc4=nn.Linear(64,10)

    def forward(self,x):
    x=x.view(x.shape[0],-1)
    x=F.relu(self.fc1(x))
    x=F.relu(self.fc2(x))
    x=F.relu(self.fc3(x))
    x=F.log_softmax(self.fc4(x),dim=1)
    return x




    def train():
    transform=transforms.Compose([
    transforms.Resize(244),
    transforms.ToTensor(),
    transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
    trainset=datasets.FashionMNIST('./data',download=True,transform=transform)
    trainloader=torch.utils.data.DataLoader(trainset,batch_size=64,shuffle=True,num_workers=2)
    model=Classifier()
    model=model.to(device)
    criterion=nn.CrossEntropyLoss()
    optimizer=optim.Adam(model.parameters(),lr=0.001)

    for epoch in range(NUM_EPOCH):
    running_loss=0.0
    for i, data in enumerate(trainloader,0):
    inputs,labels=data
    inputs=inputs.to(device)
    labels=labels.to(device)
    optimizer.zero_grad()
    outputs=model(inputs)
    outputs.to(device)
    loss=criterion(outputs,labels)
    loss.backward()
    optimizer.step()
    running_loss+=loss.item()
    if(i%20 == 19):
    print("epoch: ",epoch+1)
    print("i + 1",i)
    print("loss: ",running_loss/20.0)
    #print('[%d, 5d] loss: %.3f' %(epoch+1,i+1,running_loss/20))
    running_loss=0.0




    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print(device)

    net=Classifier()
    net.to(device)
    print(net)
    train()


    So my question is, what is the most appropriate way to resize images while I am
    training the network for my particular use case?



    I am using Cuda8.0 and CudaDNN7.1 with Pytorch version 0.4.1 and Python3.7 on Ubuntu 16.04 LTS system.










    share|improve this question

























      0












      0








      0







      I am trying to resize an image in Pytorch for later processing, while training a neural network. But get a broadcasting error, when I try to call transforms.Resize() on the image.
      Here is my code snippet.



      cuda:0
      Classifier(
      (fc1): Linear(in_features=784, out_features=256, bias=True)
      (fc2): Linear(in_features=256, out_features=128, bias=True)
      (fc3): Linear(in_features=128, out_features=64, bias=True)
      (fc4): Linear(in_features=64, out_features=10, bias=True)
      )
      Traceback (most recent call last):
      File "netz.py", line 71, in <module>
      train()
      File "netz.py", line 46, in train
      outputs=model(inputs)
      File "/home/yyyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
      result = self.forward(*input, **kwargs)
      File "netz.py", line 18, in forward
      x=F.relu(self.fc1(x))
      File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
      result = self.forward(*input, **kwargs)
      File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/linear.py", line 55, in forward
      return F.linear(input, self.weight, self.bias)
      File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 1024, in linear
      return torch.addmm(bias, input, weight.t())
      RuntimeError: size mismatch, m1: [64 x 59536], m2: [784 x 256] at /opt/conda/conda-bld/pytorch_1532584813488/work/aten/src/THC/generic/THCTensorMathBlas.cu:249

      ---- Corresponding Code ---


      import torch
      from torch import nn,optim
      import torch.nn.functional as F
      from torchvision import datasets,transforms

      NUM_EPOCH=700
      class Classifier(nn.Module):

      def __init__(self):
      super().__init__()
      self.fc1=nn.Linear(784,256)
      self.fc2=nn.Linear(256,128)
      self.fc3=nn.Linear(128,64)
      self.fc4=nn.Linear(64,10)

      def forward(self,x):
      x=x.view(x.shape[0],-1)
      x=F.relu(self.fc1(x))
      x=F.relu(self.fc2(x))
      x=F.relu(self.fc3(x))
      x=F.log_softmax(self.fc4(x),dim=1)
      return x




      def train():
      transform=transforms.Compose([
      transforms.Resize(244),
      transforms.ToTensor(),
      transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
      trainset=datasets.FashionMNIST('./data',download=True,transform=transform)
      trainloader=torch.utils.data.DataLoader(trainset,batch_size=64,shuffle=True,num_workers=2)
      model=Classifier()
      model=model.to(device)
      criterion=nn.CrossEntropyLoss()
      optimizer=optim.Adam(model.parameters(),lr=0.001)

      for epoch in range(NUM_EPOCH):
      running_loss=0.0
      for i, data in enumerate(trainloader,0):
      inputs,labels=data
      inputs=inputs.to(device)
      labels=labels.to(device)
      optimizer.zero_grad()
      outputs=model(inputs)
      outputs.to(device)
      loss=criterion(outputs,labels)
      loss.backward()
      optimizer.step()
      running_loss+=loss.item()
      if(i%20 == 19):
      print("epoch: ",epoch+1)
      print("i + 1",i)
      print("loss: ",running_loss/20.0)
      #print('[%d, 5d] loss: %.3f' %(epoch+1,i+1,running_loss/20))
      running_loss=0.0




      device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
      print(device)

      net=Classifier()
      net.to(device)
      print(net)
      train()


      So my question is, what is the most appropriate way to resize images while I am
      training the network for my particular use case?



      I am using Cuda8.0 and CudaDNN7.1 with Pytorch version 0.4.1 and Python3.7 on Ubuntu 16.04 LTS system.










      share|improve this question













      I am trying to resize an image in Pytorch for later processing, while training a neural network. But get a broadcasting error, when I try to call transforms.Resize() on the image.
      Here is my code snippet.



      cuda:0
      Classifier(
      (fc1): Linear(in_features=784, out_features=256, bias=True)
      (fc2): Linear(in_features=256, out_features=128, bias=True)
      (fc3): Linear(in_features=128, out_features=64, bias=True)
      (fc4): Linear(in_features=64, out_features=10, bias=True)
      )
      Traceback (most recent call last):
      File "netz.py", line 71, in <module>
      train()
      File "netz.py", line 46, in train
      outputs=model(inputs)
      File "/home/yyyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
      result = self.forward(*input, **kwargs)
      File "netz.py", line 18, in forward
      x=F.relu(self.fc1(x))
      File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 477, in __call__
      result = self.forward(*input, **kwargs)
      File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/modules/linear.py", line 55, in forward
      return F.linear(input, self.weight, self.bias)
      File "/home/yyy/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 1024, in linear
      return torch.addmm(bias, input, weight.t())
      RuntimeError: size mismatch, m1: [64 x 59536], m2: [784 x 256] at /opt/conda/conda-bld/pytorch_1532584813488/work/aten/src/THC/generic/THCTensorMathBlas.cu:249

      ---- Corresponding Code ---


      import torch
      from torch import nn,optim
      import torch.nn.functional as F
      from torchvision import datasets,transforms

      NUM_EPOCH=700
      class Classifier(nn.Module):

      def __init__(self):
      super().__init__()
      self.fc1=nn.Linear(784,256)
      self.fc2=nn.Linear(256,128)
      self.fc3=nn.Linear(128,64)
      self.fc4=nn.Linear(64,10)

      def forward(self,x):
      x=x.view(x.shape[0],-1)
      x=F.relu(self.fc1(x))
      x=F.relu(self.fc2(x))
      x=F.relu(self.fc3(x))
      x=F.log_softmax(self.fc4(x),dim=1)
      return x




      def train():
      transform=transforms.Compose([
      transforms.Resize(244),
      transforms.ToTensor(),
      transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
      trainset=datasets.FashionMNIST('./data',download=True,transform=transform)
      trainloader=torch.utils.data.DataLoader(trainset,batch_size=64,shuffle=True,num_workers=2)
      model=Classifier()
      model=model.to(device)
      criterion=nn.CrossEntropyLoss()
      optimizer=optim.Adam(model.parameters(),lr=0.001)

      for epoch in range(NUM_EPOCH):
      running_loss=0.0
      for i, data in enumerate(trainloader,0):
      inputs,labels=data
      inputs=inputs.to(device)
      labels=labels.to(device)
      optimizer.zero_grad()
      outputs=model(inputs)
      outputs.to(device)
      loss=criterion(outputs,labels)
      loss.backward()
      optimizer.step()
      running_loss+=loss.item()
      if(i%20 == 19):
      print("epoch: ",epoch+1)
      print("i + 1",i)
      print("loss: ",running_loss/20.0)
      #print('[%d, 5d] loss: %.3f' %(epoch+1,i+1,running_loss/20))
      running_loss=0.0




      device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
      print(device)

      net=Classifier()
      net.to(device)
      print(net)
      train()


      So my question is, what is the most appropriate way to resize images while I am
      training the network for my particular use case?



      I am using Cuda8.0 and CudaDNN7.1 with Pytorch version 0.4.1 and Python3.7 on Ubuntu 16.04 LTS system.







      python neural-network pytorch






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 7:37









      user38041

      32




      32





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257658%2fbroadcasting-error-when-trying-to-apply-transforms-resize%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257658%2fbroadcasting-error-when-trying-to-apply-transforms-resize%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues