Hi,
I am trying to save images at validation time after almost every epoch to see how my network is learning but I am getting this error.
Here is my code to save images.
def test(epoch, test_loss_list):
model.eval()
for batch_idx, (subject) in enumerate(validation_loader):
image = subject['image_data']
mask = subject['gt_data']
if params['cuda']:
image, mask = image.cuda(), mask.cuda() #Loading images into the GPU and ignore the affine.
with torch.no_grad():
output = model(image)
# loss = criterion(output, mask)
loss = dice_loss(output, mask)
test_loss_list.append(loss.data.item())
# Saving the image and its mask in its own folder
save_image(subject['image_name'], image.cpu().detach().numpy(), np.array(list(subject['affine'])), epoch, params['epoch_dir'])
save_image(subject['image_name'], mask.cpu().detach().numpy(), np.array(list(subject['affine'])), epoch, params['epoch_dir'], mask = True)
if batch_idx % int(params['log_interval']) == 0:
print('Test Epoch: {} [{}/{} ({:.0f}%)]\tAverage DICE Loss: {:.6f}'.format(
epoch, batch_idx * len(image), len(validation_loader.dataset),
100. * batch_idx / len(validation_loader), loss.data.item()))
for param_group in optimizer.param_groups:
print("Learning rate: ", param_group['lr'])
sys.stdout.flush()
def save_image(image_name, image, affine, epoch, folder, mask = False):
"""
parameters:
image_name : takes in a string of the image name
image : expecting a numpy array
affine : expecting a numpy affine
epoch : the epoch count whichever you're running from
folder : the epoch where stuff is gonna be stored in
"""
c = nib.Nifti1Image(image, affine)
os.mkdir(os.path.join(folder, epoch, image_name))
if mask == True:
c = np.array(c, dtype = np.int8)
nib.save(c, os.path.join(folder, epoch, image_name, image_name + '_mask.nii.gz'))
else:
nib.save(c, os.path.join(folder, epoch, image_name, image_name + '.nii.gz'))
return
This is the error generated
save_image(subject['image_name'], image.cpu().detach().numpy(), np.array(list(subject['affine'])), epoch, params['epoch_dir'])
ValueError: only one element tensors can be converted to Python scalars
Can anyone tell me where I may be going wrong?