import numpy as np
import torch
data = [[1,2],[3,4]]
x_data = torch.tensor(data)
print(x_data)
np_arr = np.array(data)
x_np = torch.from_numpy(np_arr)
print(x_np)
#新张量保留参数张量的属性(形状/数据类型)
x_ones= torch.ones_like(x_data) #保留x_data的属性
print(f"Ones Tensor: \n{x_ones}\n") #print(f" "), f表示在字符串内支持大括号内的python表达式,\n换行
x_rand= torch.randn_like(x_data,dtype=torch.float) #重写x_data数据类型
print(f"Random Tensor:\n{x_rand}\n")
该张量由区间[0,1)上均匀分布的随机数填充。
rand_like(input)相当于torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)。
shape = (2,3,) #决定了输出张量的维数
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor:\n{rand_tensor}\n")
print(f"Ones Tenser:\n{ones_tensor}\n")
print(f"Zeros Tensor:\n{zeros_tensor}\n")
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}")
# we move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
tensor = torch.ones(4,4)
print('First row:',tensor[0])
print('First colum:',tensor[:,0])
print('Last colum:',tensor[...,-1])
tensor[:,1] = 0 #第一列置为0
print(tensor)
t1 = torch.cat([tensor,tensor],dim = 1)
print(t1)
t = torch.ones(5) #1行5列数组
print(f"t:{t}")
n = t.numpy()
print(f"n:{n}")
tt = torch.from_numpy(n)
print(f"t:{tt}")
计算两个张量之间的矩阵乘法 y1 y2 y3 的值是一样的
tensor = torch.ones(2,4)#2行4列全1矩阵
print(tensor)
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)#创建一个tensor.shape的随机张量,用于接收下一行矩阵乘积
torch.matmul(tensor,tensor.T,out = y3)
print(f"y1:{y1}")
print(f"y2:{y2}")
print(f"y3:{y3}")
它对应元素的乘积 z1 z2 z3的值是一样的
# 它对应元素的乘积 z1 z2 z3的值是一样的
data = [[1,2,3,4],[5,6,7,8]]
tensor2= torch.tensor(data)
print(tensor2)
z1 = tensor * tensor2
z2 = tensor.mul(tensor2)
z3 = torch.rand_like(tensor)#创建一个tensor.shape的随机张量,用于接收下一行的乘积
torch.mul(tensor,tensor2,out = z3)
print(f"\nz1:{z1}")
print(f"z2:{z2}")
print(f"z3:{z3}")