tensor的创建
- list或ndarray–》tensor:
torch.tensor(list_or_array)
- 范围等距创建:
torch.arange(start,end,step)
- 全1创建:
torch.ones((1,2,3))
- 全0创建:
torch.zeros((1,2,3))
- 随机数创建:
torch.randn(1,2,3)
注意是0均值1标准差的高斯分布 - 创建标量:
a = torch.randn(size=())
tensor的操作
- tensor拼接:
torch.cat((x,y),dim=0)
第一维度上拼接,行拼接 - tensor的重构:
torch.reshape(3,4,2)
从最后一维进行重塑 - tensor的结构信息:
x.shape
算数运算
x=torch.tensor(list1)
y=torch.tensor(list2)
x+y
x-y
x*y
x/y
x**y
都是x与y中元素级别的一一运算
广播机制–解决x和y的维度不一致的现象
x=torch.tensor([[1,2],[3,4]])
y=torch.tensor([[1,2],[3,4],[5,6],[7,8]])
此时的x与y的运算是不可行的,但是通过广播机制,将x的形状同方向上复制得到(4,2)的形状,再与y进行算数运算
关系运算
x==y x>y x>=y x<y x<=y x!=y
元素级别的一一对比
类型转换
#实现array和tensor转换
x=torch.arange(12)
A=x.numpy()
B=torch.tensor(A)
#实现标量tensor的值转化
x=torch.tensor([1])
x.item()
float(x)
int(x)
索引
x[1,2]
x[:,2]
x[-1]#得到最后一个元素
节省内存
X=X+Y的操作最终是将X的指针指向了X+Y新开创的内存空间,而不是X原始地址
需要保持原始地址不被改变:
X[:]=Y+Z
或
X+=Y