Converting tensor to numpy array

x.cpu().detach().numpy() seems quite convoluted. Is that the right way to transform a tensor to a numpy array? Is there a shortform?

Currently doing this (tensor is on GPU):

    action = action.cpu().detach().numpy()
    log_prob = log_prob.cpu().detach().numpy()
    state_value = state_value.cpu().detach().numpy()

Can this maybe be written more efficiently as a with block? Can this be done in place? Is there a lot of overhead doing the above?

Hello,

Yes, this is the right way. You could always wrap the operations inside a function that looks like that:

def to_numpy(tensor):
    return tensor.cpu().detach().numpy()

I do not think a with block would work, and as far as I know, you can’t do those operations inplace (except detach_). The main overhead will be in the .cpu() call, since you have to transfer data from the GPU to the CPU.

1 Like