Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.as_tensor function

PyTorch torch.as_tensor function


PyTorch torch reference manual PyTorch torch reference manual

torch.as_tensor is a function in PyTorch used to convert data into a tensor. Unlike torch.tensor it, it shares data memory as much as possible.

Function definition

torch.as_tensor(data, dtype=None, device=None)


Usage examples

Example

import

torch

import

numpy

as

np

Create from a NumPy array (shared memory)

numpy_array

=

np.

array

(

[

1

,

2

,

3

]

)

x

=

torch.

as_tensor

(

numpy_array

)

Modify the NumPy array

numpy_array

[

0

]

=

100

print

(

"Tensor:"

,

x

)

 

The tensor changes as well

The output is:

张量: tensor([100,   2,   3])


PyTorch torch reference manual PyTorch torch reference manual