Dice and CE loss not training network together











up vote
2
down vote

favorite












I am training a segmentation network on the Kaggle Salt challenge. My dice and ce decrease, but then suddenly dice increases and CE jumps up a bit, this keeps happening to dice. I have been trying all day to fix this but can’t get my code to run. I am running on only 10 data points to overfit my data but it just is not happening. Any help would be greatly appreciated.



Plots of dice(top) and CE:



Loss curve



Heres my dice and train:



def dice(input, target,weights=torch.tensor([1,1]).float().cuda()):
smooth=.001

dummy=np.zeros([batch_size,2,100,100]) # create dummy to one hot encode target for weighted dice
dummy[:,0,:,:][target==0]=1 # background class is 0
dummy[:,1,:,:][target==1]=1 # salt class is 1


target=torch.tensor(dummy).float().cuda()

# print(input.size(),input[:,0,:,:].size())
input1=input[:,0,:,:].contiguous().view(-1) #flatten both classes seperately
target1=target[:,0,:,:].contiguous().view(-1)

input2=input[:,1,:,:].contiguous().view(-1)
target2=target[:,1,:,:].contiguous().view(-1)

score1=2*(input1*target1).sum()/(input1.sum()+target1.sum()+smooth) #back
score2=2*(input2*target2).sum()/(input2.sum()+target2.sum()+smooth) #salt


score=1-(weights[0]*score1+weights[1]*score2)/2
if score<0:
score=score-score

return(score)
Heres the train:


def train(epoch):
for idx, batch_data in enumerate(dataloader) :
x, target=batch_data['image'].float().cuda(),batch_data['label'].float().cuda()


optimizer.zero_grad()
output = net(x)
# print(output.size())
output.squeeze_(1)

# print('out',output.size(),target.size())
bce_loss = criterion(output, target.long())
lc.append(bce_loss.item())

dice_loss = dice((output), target)
ld.append(dice_loss.item())
loss = dice_loss + bce_loss
l.append(loss.item())

loss.backward()
optimizer.step()

print('Epoch {}, loss {}, bce {}, dice {}'.format(
epoch, sum(l)/len(l), sum(lc)/len(lc) , sum(ld)/len(ld) ))


Heres the rest of the code( I downed from gaggle kernel): https://github.com/bluesky314/Salt-Segmentation/blob/master/kernel-2.ipynb 1 (the training showed here is when I ran that cell(14) a second time so the ups and downs don’t appear but can be seen in the plot)



dataset=DatasetSalt(limit_paths=10) just limits the dataset to any number by only taking the top paths to get the images from



Would really appreciate any help, have been literally struggling on this for 8+ hrs










share|improve this question









New contributor




One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    2
    down vote

    favorite












    I am training a segmentation network on the Kaggle Salt challenge. My dice and ce decrease, but then suddenly dice increases and CE jumps up a bit, this keeps happening to dice. I have been trying all day to fix this but can’t get my code to run. I am running on only 10 data points to overfit my data but it just is not happening. Any help would be greatly appreciated.



    Plots of dice(top) and CE:



    Loss curve



    Heres my dice and train:



    def dice(input, target,weights=torch.tensor([1,1]).float().cuda()):
    smooth=.001

    dummy=np.zeros([batch_size,2,100,100]) # create dummy to one hot encode target for weighted dice
    dummy[:,0,:,:][target==0]=1 # background class is 0
    dummy[:,1,:,:][target==1]=1 # salt class is 1


    target=torch.tensor(dummy).float().cuda()

    # print(input.size(),input[:,0,:,:].size())
    input1=input[:,0,:,:].contiguous().view(-1) #flatten both classes seperately
    target1=target[:,0,:,:].contiguous().view(-1)

    input2=input[:,1,:,:].contiguous().view(-1)
    target2=target[:,1,:,:].contiguous().view(-1)

    score1=2*(input1*target1).sum()/(input1.sum()+target1.sum()+smooth) #back
    score2=2*(input2*target2).sum()/(input2.sum()+target2.sum()+smooth) #salt


    score=1-(weights[0]*score1+weights[1]*score2)/2
    if score<0:
    score=score-score

    return(score)
    Heres the train:


    def train(epoch):
    for idx, batch_data in enumerate(dataloader) :
    x, target=batch_data['image'].float().cuda(),batch_data['label'].float().cuda()


    optimizer.zero_grad()
    output = net(x)
    # print(output.size())
    output.squeeze_(1)

    # print('out',output.size(),target.size())
    bce_loss = criterion(output, target.long())
    lc.append(bce_loss.item())

    dice_loss = dice((output), target)
    ld.append(dice_loss.item())
    loss = dice_loss + bce_loss
    l.append(loss.item())

    loss.backward()
    optimizer.step()

    print('Epoch {}, loss {}, bce {}, dice {}'.format(
    epoch, sum(l)/len(l), sum(lc)/len(lc) , sum(ld)/len(ld) ))


    Heres the rest of the code( I downed from gaggle kernel): https://github.com/bluesky314/Salt-Segmentation/blob/master/kernel-2.ipynb 1 (the training showed here is when I ran that cell(14) a second time so the ups and downs don’t appear but can be seen in the plot)



    dataset=DatasetSalt(limit_paths=10) just limits the dataset to any number by only taking the top paths to get the images from



    Would really appreciate any help, have been literally struggling on this for 8+ hrs










    share|improve this question









    New contributor




    One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I am training a segmentation network on the Kaggle Salt challenge. My dice and ce decrease, but then suddenly dice increases and CE jumps up a bit, this keeps happening to dice. I have been trying all day to fix this but can’t get my code to run. I am running on only 10 data points to overfit my data but it just is not happening. Any help would be greatly appreciated.



      Plots of dice(top) and CE:



      Loss curve



      Heres my dice and train:



      def dice(input, target,weights=torch.tensor([1,1]).float().cuda()):
      smooth=.001

      dummy=np.zeros([batch_size,2,100,100]) # create dummy to one hot encode target for weighted dice
      dummy[:,0,:,:][target==0]=1 # background class is 0
      dummy[:,1,:,:][target==1]=1 # salt class is 1


      target=torch.tensor(dummy).float().cuda()

      # print(input.size(),input[:,0,:,:].size())
      input1=input[:,0,:,:].contiguous().view(-1) #flatten both classes seperately
      target1=target[:,0,:,:].contiguous().view(-1)

      input2=input[:,1,:,:].contiguous().view(-1)
      target2=target[:,1,:,:].contiguous().view(-1)

      score1=2*(input1*target1).sum()/(input1.sum()+target1.sum()+smooth) #back
      score2=2*(input2*target2).sum()/(input2.sum()+target2.sum()+smooth) #salt


      score=1-(weights[0]*score1+weights[1]*score2)/2
      if score<0:
      score=score-score

      return(score)
      Heres the train:


      def train(epoch):
      for idx, batch_data in enumerate(dataloader) :
      x, target=batch_data['image'].float().cuda(),batch_data['label'].float().cuda()


      optimizer.zero_grad()
      output = net(x)
      # print(output.size())
      output.squeeze_(1)

      # print('out',output.size(),target.size())
      bce_loss = criterion(output, target.long())
      lc.append(bce_loss.item())

      dice_loss = dice((output), target)
      ld.append(dice_loss.item())
      loss = dice_loss + bce_loss
      l.append(loss.item())

      loss.backward()
      optimizer.step()

      print('Epoch {}, loss {}, bce {}, dice {}'.format(
      epoch, sum(l)/len(l), sum(lc)/len(lc) , sum(ld)/len(ld) ))


      Heres the rest of the code( I downed from gaggle kernel): https://github.com/bluesky314/Salt-Segmentation/blob/master/kernel-2.ipynb 1 (the training showed here is when I ran that cell(14) a second time so the ups and downs don’t appear but can be seen in the plot)



      dataset=DatasetSalt(limit_paths=10) just limits the dataset to any number by only taking the top paths to get the images from



      Would really appreciate any help, have been literally struggling on this for 8+ hrs










      share|improve this question









      New contributor




      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I am training a segmentation network on the Kaggle Salt challenge. My dice and ce decrease, but then suddenly dice increases and CE jumps up a bit, this keeps happening to dice. I have been trying all day to fix this but can’t get my code to run. I am running on only 10 data points to overfit my data but it just is not happening. Any help would be greatly appreciated.



      Plots of dice(top) and CE:



      Loss curve



      Heres my dice and train:



      def dice(input, target,weights=torch.tensor([1,1]).float().cuda()):
      smooth=.001

      dummy=np.zeros([batch_size,2,100,100]) # create dummy to one hot encode target for weighted dice
      dummy[:,0,:,:][target==0]=1 # background class is 0
      dummy[:,1,:,:][target==1]=1 # salt class is 1


      target=torch.tensor(dummy).float().cuda()

      # print(input.size(),input[:,0,:,:].size())
      input1=input[:,0,:,:].contiguous().view(-1) #flatten both classes seperately
      target1=target[:,0,:,:].contiguous().view(-1)

      input2=input[:,1,:,:].contiguous().view(-1)
      target2=target[:,1,:,:].contiguous().view(-1)

      score1=2*(input1*target1).sum()/(input1.sum()+target1.sum()+smooth) #back
      score2=2*(input2*target2).sum()/(input2.sum()+target2.sum()+smooth) #salt


      score=1-(weights[0]*score1+weights[1]*score2)/2
      if score<0:
      score=score-score

      return(score)
      Heres the train:


      def train(epoch):
      for idx, batch_data in enumerate(dataloader) :
      x, target=batch_data['image'].float().cuda(),batch_data['label'].float().cuda()


      optimizer.zero_grad()
      output = net(x)
      # print(output.size())
      output.squeeze_(1)

      # print('out',output.size(),target.size())
      bce_loss = criterion(output, target.long())
      lc.append(bce_loss.item())

      dice_loss = dice((output), target)
      ld.append(dice_loss.item())
      loss = dice_loss + bce_loss
      l.append(loss.item())

      loss.backward()
      optimizer.step()

      print('Epoch {}, loss {}, bce {}, dice {}'.format(
      epoch, sum(l)/len(l), sum(lc)/len(lc) , sum(ld)/len(ld) ))


      Heres the rest of the code( I downed from gaggle kernel): https://github.com/bluesky314/Salt-Segmentation/blob/master/kernel-2.ipynb 1 (the training showed here is when I ran that cell(14) a second time so the ups and downs don’t appear but can be seen in the plot)



      dataset=DatasetSalt(limit_paths=10) just limits the dataset to any number by only taking the top paths to get the images from



      Would really appreciate any help, have been literally struggling on this for 8+ hrs







      deep-learning conv-neural-network pytorch






      share|improve this question









      New contributor




      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited Nov 19 at 12:18









      blue-phoenox

      3,11681438




      3,11681438






      New contributor




      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Nov 19 at 6:03









      One Life

      111




      111




      New contributor




      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      One Life is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





























          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',
          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
          });


          }
          });






          One Life is a new contributor. Be nice, and check out our Code of Conduct.










           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53369111%2fdice-and-ce-loss-not-training-network-together%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          One Life is a new contributor. Be nice, and check out our Code of Conduct.










           

          draft saved


          draft discarded


















          One Life is a new contributor. Be nice, and check out our Code of Conduct.













          One Life is a new contributor. Be nice, and check out our Code of Conduct.












          One Life is a new contributor. Be nice, and check out our Code of Conduct.















           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53369111%2fdice-and-ce-loss-not-training-network-together%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

          Tonle Sap (See)

          I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

          Guatemaltekische Davis-Cup-Mannschaft