一、Tensor属性
import torch
#整数类型
a = torch.tensor([1, 2, 3],dtype = int)
print(a)
#查看数据类型
print(a.dtype)
#浮点数类型
b = torch.tensor([4,5,6],dtype = float)
print(b)
print(b.dtype)
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
#查看维度
print(tensor.ndim)
#查看形状
print(tensor.shape)
print(tensor.size())
二、数据生成
import torch
import numpy as np
a = torch.ones(2,3)
print(a)
b = torch.zeros(3,3)
print(b)
c = torch.rand(3,4)
print(c)
d = torch.randint(0,10,(2,3))
print(d)
#随机生成符合正态分布的随机数
e = torch.randn(3,4)
print(e)
#生成一个三行两列的数据
f = torch.tensor([[1,2],[3,4],[5,6]])
print(f)
#生成跟f相同的数据
g = torch.rand_like(a,dtype = float)
print(g)
#修改数据形状
h = g.view(6)
h = g.reshape(6)
#查看tensor里的值
print(h[1].item)
#tensor转换为nparray
i = np.array(h)
array = np.array([1,2,3])
#nparray转换为tensor
tensor = torch.tensor(array)
print(tensor)
三、基本运算操作
import torch
import numpy as np
a = torch.randint(1,5,(2,3))
b = torch.randint(1,5,(2,3))
#加法
print(a + b)
print(torch.add(a,b))
#注意:add_()是inplace操作,即直接修改a的值
a.add_(b)
#减法
print(a - b)
print(torch.sub(a,b))
#乘法
print(a * b)
print(torch.mul(a,b))
#除法
print(a / b)
print(torch.div(a,b))
#取余数
print(a % b)
print(torch.fmod(a,b))
#取整
print(a // b)
print(torch.floor_divide(a,b))
#矩阵乘法
tensor = torch.ones(3,5,dtype = int)
print(torch.matmul(a,tensor))
#矩阵的转置
print(a.T)
sample = torch.rand(2,3)
#求和
print(torch.sum(sample))
#求均值
print(torch.mean(sample))
#求最大值
print(torch.max(sample))
#求最大值所在的索引
print(torch.argmax(sample))
#求最小值
print(torch.min(sample))
#求最小值所在的索引
print(torch.argmin(sample))
#求方差
print(torch.var(sample))
#求标准差
print(torch.std(sample))
#求对数
print(torch.log(sample))
四、数据索引
import torch
import numpy as np
tensor = torch.arange(2,14)
print(tensor)
#取第三个数据
print(tensor[2])
#取第3到第5个数据
print(tensor[2:5])
#取第3个数据到倒数第二个数据
print(tensor[2:-1])
print(tensor[:5])
print(tensor[-3:])
index = [1,3,4,5,5]
print(tensor[index])
五、自动求导
import torch
#requires_grad表示可以计算它的梯度
x = torch.ones((2,2),requires_grad = True)
y = x + 2
z = y * y * 3
out = z.mean()
print(out)
#求导,计算梯度
out.backward()
print(x.grad)