@KFrank，Thank you for your answer。 Rounding_output_c11 = torch.stack([(Rounding_output_c1 == i).float() for i in range(256)]) #[4,224,224]->[256,4,224,224] 256 is the number of classes, means pixel from 0-255])   is truthly break the graph, I just want to use this code to use one-hot encoding to change output_c1's shape , nClass is pixel value from 0 to 255.
the values of each element of my [nBatch, 244, 244]   labels tensor is from 0 to 255.
my network’s output is output_c1 which size is [4,2,224,224] ,It value from 0-255.
I want to use
output_c1 = outputs[:,0,:,:]  # outputs [4,2,224,224] ->outputs_c1[4,224,2224]
to choose the second channel to extract Foreground image
If I want to use CrossEntropyLoss ,I don’t konw  how to change my outputs’s shape and labels’s shape to correctly calculate the loss .