import torch
x = torch.arange(12,0,-1)
print(x)
# shape返回torch.Size (行为类似一个元组 tuple)
print(x.shape)
# numel()返回int
print(x.numel())
x = x.reshape(3,4)
print(x)
# shape返回torch.Size (行为类似一个元组 tuple)
print(x.shape)
# numel()返回int
print(x.numel())
print(torch.zeros(2,3,4))
print(torch.ones(2,3,4))
y=torch.tensor([[2,1,4,3],[1,2,3,4],[6,7,8,9]])
print(y)
print(y.shape)
print(torch.exp(y))
xx = torch.arange(12,dtype=torch.float32).reshape((3,4))
yy= torch.tensor([[2.0,1,4,3],[1,2,6,8],[2,4,6,8]])
print(torch.cat((xx,yy),dim=0))
print(torch.cat((xx,yy),dim=1))
print(xx==yy)
# 属性不加括号,函数加括号
print(xx.sum())
a = torch.arange(3).reshape((3,1))
b = torch.arange(2).reshape((1,2))
print(a)
print(b)
# 广播机制
print(a+b)
# 原地操作
z = torch.zeros_like(x)
before = id(z)
z[:]=x+y
print(id(z)==before)
# 也可以使用x[:]=x+y或x+=y减少内存
# numpy类型和tensor类型的互相转化
print(x)
aa = x.numpy()
bb = torch.tensor(aa)
print(aa)
print(type(aa))
print(bb)
print(type(bb))
a = torch.tensor([3.5])
print(a)
print(type(a))
print(a.item())
print(type(a.item()))
print(int(a))
print(type(int(a)))
输出
tensor([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
torch.Size([12])
12
tensor([[12, 11, 10, 9],
[ 8, 7, 6, 5],
[ 4, 3, 2, 1]])
torch.Size([3, 4])
12
tensor([[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]])
tensor([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])
tensor([[2, 1, 4, 3],
[1, 2, 3, 4],
[6, 7, 8, 9]])
torch.Size([3, 4])
tensor([[7.3891e+00, 2.7183e+00, 5.4598e+01, 2.0086e+01],
[2.7183e+00, 7.3891e+00, 2.0086e+01, 5.4598e+01],
[4.0343e+02, 1.0966e+03, 2.9810e+03, 8.1031e+03]])
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 2., 1., 4., 3.],
[ 1., 2., 6., 8.],
[ 2., 4., 6., 8.]])
tensor([[ 0., 1., 2., 3., 2., 1., 4., 3.],
[ 4., 5., 6., 7., 1., 2., 6., 8.],
[ 8., 9., 10., 11., 2., 4., 6., 8.]])
tensor([[False, True, False, True],
[False, False, True, False],
[False, False, False, False]])
tensor(66.)
tensor([[0],
[1],
[2]])
tensor([[0, 1]])
tensor([[0, 1],
[1, 2],
[2, 3]])
True
tensor([[12, 11, 10, 9],
[ 8, 7, 6, 5],
[ 4, 3, 2, 1]])
[[12 11 10 9]
[ 8 7 6 5]
[ 4 3 2 1]]
<class 'numpy.ndarray'>
tensor([[12, 11, 10, 9],
[ 8, 7, 6, 5],
[ 4, 3, 2, 1]])
<class 'torch.Tensor'>
tensor([3.5000])
<class 'torch.Tensor'>
3.5
<class 'float'>
3
<class 'int'>
775

被折叠的 条评论
为什么被折叠?



