1. 程式人生 > 其它 >解決 TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

解決 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)

報錯:

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.

參考TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu(),我嘗試將 intrinsic_normal 改成 intrinsic_normal.cuda().data.cpu().numpy(),繼續報新的錯:

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

參考 'numpy.ndarray' object has no attribute 'cuda' , 將 intrinsic_normal 轉化成tensor型別

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

成功解決