AttributeError: 'numpy.ndarray' object has no attribute 'log'

File “/home/ali/BioNet_project/pytorch_version/utils.py”, line 90, in train
soft_score = soft_loss(y, x, beta=0.95)
File “/home/ali/BioNet_project/pytorch_version/metrics.py”, line 23, in soft_loss
cross_entropy = F.nll_loss(y_pred.log(), y_true, size_average=False)
AttributeError: ‘numpy.ndarray’ object has no attribute ‘log’

It seems you are trying to pass a numpy array to F.nll_loss, while a PyTorch tensor is expected.
I’m not sure how y_pred is calculated, but note that using numpy array would detach them from the computation graph, so you should stick to PyTorch tensors and operations, if possible.

thanks for your reply. yes, I am trying to calculate the soft_loss but stuck in this problem and don’t know what to do.

metrics

        x, y = output.detach().cpu().numpy(), y.detach().cpu().numpy()
        soft_score = soft_loss(y, x, beta=0.95)

def soft_loss(y_true, y_pred, beta=0.95):
cross_entropy = F.nll_loss(y_pred.log(), y_true, size_average=False)
soft_reed = -y_pred * torch.log(y_pred + 1e-8)
return beta * cross_entropy + (1 - beta) * torch.sum(soft_reed)

Remove the .numpy() operations and pass the tensors to the soft_loss function.
As described before, you won’t be able to call backward() on the loss and calculate gradients with it, since you are also explicitly detaching the tensors, but I assume that’s wanted.

thanks for your suggestion and i have followed your words but facing now this issue.
####modification######
# # loss
# l = criterion(output, y)
# # tot_loss += l.item()
# l.backward()
# optimizer.step()

        # metrics
        x, y = output.detach().cpu(), y.detach().cpu()

        # iou_score = iou(y, x)
        # dice_score = dice_coef(y, x)
        soft_score = soft_loss(y, x)
        hard_score = hard_loss(y, x)

######metrics###########
import numpy as np
import torch.nn.functional as F

def soft_loss(y_true, y_pred, beta=0.95):
cross_entropy = F.nll_loss(y_pred.log(), y_true, size_average=False)
soft_reed = -y_pred * torch.log(y_pred + 1e-8)
return beta * cross_entropy + (1 - beta) * torch.sum(soft_reed)

#####errorrr####
File “/home/ali/BioNet_project/pytorch_version/utils.py”, line 90, in train
soft_score = soft_loss(y, x)
File “/home/ali/BioNet_project/pytorch_version/metrics.py”, line 23, in soft_loss
cross_entropy = F.nll_loss(y_pred.log(), y_true, size_average=False)
File “/home/ali/miniconda3/envs/bio/lib/python3.6/site-packages/torch/nn/functional.py”, line 2117, in nll_loss
ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4

This is the shape of my data ‘‘data shape: (240, 512, 512, 3) (240, 512, 512, 1)’’.