torch.from_numpy VS torch.Tensor

torch.from_numpy VS torch.Tensor
最近在造dataset的时候,突然发现,在输入图像转tensor的时候,我可以用torch.Tensor直接强制转型将numpy类转成tensor类,也可以用torch.from_numpy这个方法将numpy类转换成tensor类,那么,torch.Tensor和torch.from_numpy这两个到底有什么区别呢?既然torch.Tensor能搞定,那torch.from_numpy留着不就是冗余吗?

答案
有区别,使用torch.from_numpy更加安全,使用tensor.Tensor在非float类型下会与预期不符。

解释
实际上,两者的区别是大大的。打个不完全正确的比方说,torch.Tensor就如同c的int,torch.from_numpy就如同c++的static_cast,我们都知道,如果将int64强制转int32,只要是高位转低位,一定会出现高位被抹去的隐患的,不仅仅可能会丢失精度,甚至会正负对调。这里的torch.Tensor与torch.from_numpy也会存在同样的问题。

看看torch.Tensor的文档,里面清楚地说明了,

torch.Tensor is an alias for the default tensor type (torch.FloatTensor).

torch.from_numpy的文档则是说明,

The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa. The returned tensor is not resizable.

也即是说,

当转换的源是float类型,torch.Tensor与torch.from_numpy会共享一块内存!且转换后的结果的类型是torch.float32
当转换的源不是float类型,torch.Tensor得到的是torch.float32,而torch.from_numpy则是与源类型一致!

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BILLY BILLY

你的奖励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值