Tag Archives: TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

[Solved] TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

normal_traffic = np.concatenate((intrinsic_normal, content_normal, time_based_normal, host_based_normal, categorical_normal), axis=1)

report errors:

Traceback (most recent call last):
  File "test_wgan.py", line 165, in <module>
    main()
  File "test_wgan.py", line 24, in main
    test_ids(options)
  File "test_wgan.py", line 37, in test_ids
    data = reassemble(options.attack, adversarial, adversarial_ff, nor_nff, nor_ff)
  File "test_wgan.py", line 51, in reassemble
    adversarial_traffic = np.concatenate((intrinsic, content, time_based, host_based, categorical), axis=1)
  File "/root/miniconda3/envs/ids_attack/lib/python3.7/site-packages/torch/tensor.py", line 433, in __array__
    return self.numpy()
TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

Solution:

Change intrinsic_normal to intrinsic_normal.cuda().data.cpu().numpy() will report another error:

'numpy.ndarray' object has no attribute 'cuda'

Refer to ‘numpy.Ndarray’ object has no attribute ‘CUDA’, and set the intrinsic_ Convert normal to tensor type

intrinsic_normal = torch.tensor(intrinsic_normal).cuda().data.cpu().numpy()

Successfully solved