[Python] RuntimeError: all elements of target should be between 0 and 1. Please help my...

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I use the BCELoss(),and it show up RuntimeError: all elements of target should be between 0 and 1, but I already use sigmoid, I can't understand why it still not working...


    # Build CustomDataset for loading data from Google Drive
    class CustomDataset(Dataset):
    def __init__(self,image_dir,mask_dir,transform):
    super().__init__()
    self.image_dir=image_dir
    self.mask_dir=mask_dir
    self.transform=transform
    self.images=os.listdir(image_dir)
    def __len__(self):
    return len(self.images)
    def __getitem__(self, index):
    img_path=os.path.join(self.image_dir,self.images[index])
    mask_path=os.path.join(self.mask_dir,self.images[index])
    image=np.array(Image.open(img_path).convert('L'))
    mask=np.array(Image.open(mask_path).convert('L'))
    return self.transform(image),self.transform(mask)


    # Load data
    all_data = CustomDataset('images', 'masks', T.Compose([T.ToTensor(), T.Resize((IMG_HEIGHT, IMG_WIDTH))]))

    # Split data into train and val
    train_data, val_data = torch.utils.data.random_split(all_data, [0.7, 0.3])

    # Create loader for mini-batch gradient descent
    from torch.utils.data import DataLoader
    train_loader = DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)
    val_loader = DataLoader(val_data, batch_size=BATCH_SIZE, shuffle=False)


    # The loss function for bianry classification
    # loss_function = nn.BCELoss()
    loss_function = nn.BCEWithLogitsLoss()



    I want to finish training this model...I use this model to do Semantic Segmentation on spinal X-ray photo.

    Continue reading...

Compartilhe esta Página