pytorch教程tensor1
作者:
晓博
,
2022-01-10 09:53:11
,
所有人可见
,
阅读 194
import torch
import numpy as np
device = "cuda:0" if torch.cuda.is_available() else "cpu"
my_tensor = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype = torch.float32, device = device,requires_grad = True)
#tensor的各种变量
print(my_tensor)
print(my_tensor.dtype)
print(my_tensor.device)
print(my_tensor.shape)
print(my_tensor.requires_grad)
#如何初始化tensor
x = torch.empty(size = (3, 3))
x = torch.zeros((3, 3))
x = torch.rand((3, 3))
x = torch.ones((3 , 3))
x = torch.eye(5, 5)
x = torch.arange( start = 0, end = 5, step = 1)
x = torch.linspace(start = 0.1, end = 1, steps = 10)
x = torch.empty((1, 5)).uniform_(0, 1)
print(x)
#类型转换
tensor = torch.arange(4)
print(tensor.bool())
print(tensor.short())
print(tensor.long())
print(tensor.half())
print(tensor.float())
print(tensor.double())
#numpy 类型转换
np_array = np.zeros((5, 5))
tensor = torch.from_numy(np_array)
np_array_back = tensor.numpy()