目录
Tensors和numpy的ndarray类似,通常在pytorch中用于编码模型的输入输出和模型的参数。可以在GPU和其他硬件上运行。
一、初始化
#直接初始化
data = [[1,2],[3,4]]
x_data = torch.tensor(data)
#转化numpy array
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
#复制tensor
x_ones = torch.ones_like(x_data) # x_data全部置为1
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # 覆写x_data为0到1之间的数
print(f"Random Tensor: \n {x_rand} \n")
#赋随机值或者常数值
shape = (2,3,)#元组,决定阶数
rand_tensor = torch.rand(shape)#0到1的随机值
ones_tensor = torch.ones(shape)#全为1
zeros_tensor = torch.zeros(shape)#全为0
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
二、Tensor的属性
tensor = torch.rand(3,4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")#存储位置
三、常用操作
下面方法每一个都可以在GPU上运行。
默认情况下tensors是在CPU上创建的。我们需要使用.to方法将tensors移动到GPU。复制大量tensors很费时间和内存。
# 如果GPU可用,移动到GPU上
if torch.cuda.is_available():
tensor = tensor.to("cuda")
1.索引和切片(类似numpy)
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")#三点表示剩余全部
tensor[:,1] = 0
print(tensor)
First row: tensor([1., 1., 1., 1.]) First column: tensor([1., 1., 1., 1.]) Last column: tensor([1., 1., 1., 1.]) tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]])
2.连接
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
dim指定连接维数,对于二维,dim=0行拼接,dim=1列拼接。
类似还有torch.stack(tensors,dim=0,*,out=None)
tensor必须具有相同大小
3.运算
# 矩阵乘积,y1,y2,y3具有相同值
# ``tensor.T``为转置
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)
# 元素对应相乘,z1,z2,z3具有相同值
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
#求和
agg = tensor.sum()
#将单元素tensor转为python原有数据类型
agg_item = agg.item()
print(agg_item, type(agg_item))
#加法
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
四、与numpy转化
Tensor to NumPy array
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
#会同时改变
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
NumPy array to Tensor
n = np.ones(5)
t = torch.from_numpy(n)
#会同时改变
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")