Tensor创建:直接创建
2.Tensor:直接创建
(1)torch,tensor()
import torch
import numpy as np
torch.manual_seed(1)
#通过创建torch.tensor创建张量
arr=np.ones((3,3))
print("ndarray的数据类型:",arr.dtype)
t=torch.tensor(arr)
print(t)
输出结果:

如果想对张量加速
需要将tensor的device改为cuda
t=torch.tensor(arr,device='cuda')
(2)torch.from_numpy(ndarray) //从numpy创建tensor
注意:从torch.from_numpy创建的tensor与原ndarray共享内存,当修改其中一个数据时,另一个也会变动

arr=np.array([[1,2,3],[4,5,6]])
t=torch.from_numpy(arr)

修改arr的数据
arr[0,0]=0

改变tensor
t[0,0]=100

本文详细介绍了如何使用PyTorch从NumPy数组创建张量,并探讨了Tensor与原数组共享内存的特性。同时,文章还讲解了如何将Tensor设备设置为CUDA以加速计算。

413

被折叠的 条评论
为什么被折叠?



