torch.from_numpy(ndarray) 功能及举例

时间:2025-03-13 18:09:42

功能:torch.from_numpy(ndarray) → Tensor,即 从创建一个张量。

说明:返回的张量和ndarray共享同一内存。对张量的修改将反映在ndarray中,反之亦然。返回的张量是不能调整大小的。

举例


>>> import torch

>>> import numpy as np

>>> a = ([1, 2, 3])

>>> t = torch.from_numpy(a)

>>> t
tensor([1, 2, 3], dtype=torch.int32)

>>> t[1]=1000

>>> t
tensor([   1, 1000,    3], dtype=torch.int32)

>>> a
array([   1, 1000,    3])

>>> a[0]=101

>>> a
array([ 101, 1000,    3])

>>> t
tensor([ 101, 1000,    3], dtype=torch.int32)

参考:/docs/stable/generated/torch.from_numpy.html?highlight=torch%20from_numpy