PyTorch torch.as_tensor Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.as_tensoris a function in PyTorch used to convert data into tensors. Unliketorch.tensorit shares data memory as much as possible.

Function Definition

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

Usage Example

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 will also change

The output result is:

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

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions