为什么要相互转换:
简单一句话, numpy操作多样, 简单. 但网络前向只能是tensor类型, 各有优势, 所以需要相互转换补充.
# convert Tensor x of torch to array y of numpy:
y = x.numpy();
# convert array x of numpy to Tensor y of torch:
y = torch.from_numpy(x)
# 先将数据转换成Tensor, 再使用CUDA函数来将Tensor移动到GPU上加速
如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tensor随后再转到numpy格式。
x_np = x.data.numpy()
# 改为:
x_np = x.data.cpu().numpy()
# 或者兼容上面两者的方式
x_np = x.detach().cpu().numpy() if x.requires_grad else x.cpu().numpy()
参考1:https://blog.csdn.net/ljs_a/article/details/78758116
参考2:https://blog.csdn.net/u012436149/article/details/54627597
参考3:https://blog.csdn.net/weixin_39449466/article/details/80410314
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)