gpt4 book ai didi

pytorch - 对于 CPU 上的 numpy 数组,torch.as_tensor() 是否与 torch.from_numpy() 相同?

转载 作者:行者123 更新时间:2023-12-04 04:09:12 28 4
gpt4 key购买 nike

在 CPU 上,是 torch.as_tensor(a)torch.from_numpy(a)对于 numpy 数组,a ?如果没有,那为什么不呢?

来自 torch.as_tensor 的文档

if the data is an ndarray of the corresponding dtype and the device is the cpu, no copy will be performed.



来自 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.



在这两种情况下,结果张量的任何更改都会更改原始 numpy 数组。

a = np.array([[1., 2], [3, 4]])
t1 = torch.as_tensor(a)
t2 = torch.from_numpy(a)
t1[0, 0] = 42.
print(a)
# prints [[42., 2.], [3., 4.]]
t2[1, 1] = 55.
print(a)
# prints [[42., 2.], [3., 55.]]

此外,在这两种情况下,尝试调整张量的大小都会导致错误。

最佳答案

它们基本相同,除了 as_tensor更通用:

  • from_numpy相反,它支持广泛的数据类型,包括列表、元组和 native Python 标量。
  • as_tensor支持直接更改dtype和device,在实践中非常方便,因为Torch张量的默认dtype是float32,而对于Numpy数组则是float64。
  • as_tensor当且仅当原始对象是 Numpy 数组,并且请求的数据类型(如果有)与原始数据相同时,才与原始数据共享内存。这些条件与 from_numpy 相同,但总是为后来的设计感到满意。

    关于pytorch - 对于 CPU 上的 numpy 数组,torch.as_tensor() 是否与 torch.from_numpy() 相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62033283/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com