import torch
x=torch.arange(12)
x
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
x.shape
torch.Size([12])
x.numel()
12
x.reshape(3,4)
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
torch.tensor([[1,2,3,4],[4,5,6,7],[2,3,4,5]]).shape
torch.Size([3, 4])
x=torch.tensor([1.0,2,3,4])
y=torch.tensor([2,5,7,9])
x+y,x-y,x*y,x/y,x**y
(tensor([ 3., 7., 10., 13.]),
tensor([-1., -3., -4., -5.]),
tensor([ 2., 10., 21., 36.]),
tensor([0.5000, 0.4000, 0.4286, 0.4444]),
tensor([1.0000e+00, 3.2000e+01, 2.1870e+03, 2.6214e+05]))
torch.exp(x)
tensor([ 2.7183, 7.3891, 20.0855, 54.5981])
x=torch.arange(12,dtype=torch.float32).reshape(3,4)
y=torch.tensor([[1,2,3,4],[2,3,0,5],[0,4,5,6]])
torch.cat((x,y),dim=0)
torch.cat((x,y),dim=1)
tensor([[ 0., 1., 2., 3., 1., 2., 3., 4.],
[ 4., 5., 6., 7., 2., 3., 0., 5.],
[ 8., 9., 10., 11., 0., 4., 5., 6.]])
x.sum()
tensor(66.)
a=torch.arange(3).reshape(3,1)
b=torch.arange(2).reshape(1,2)
a,b
(tensor([[0],
[1],
[2]]),
tensor([[0, 1]]))
a+b
tensor([[0, 1],
[1, 2],
[2, 3]])
x
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
x[-1]
tensor([ 8., 9., 10., 11.])
x[1:3]
tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
x[1:3]=12
x
tensor([[ 0., 1., 2., 3.],
[12., 12., 12., 12.],
[12., 12., 12., 12.]])
x[1:3,]=13
x
tensor([[ 0., 1., 2., 3.],
[13., 13., 13., 13.],
[13., 13., 13., 13.]])
before=id(x)
x=x+y
id(x)==before
False
z=torch.zeros_like(y)
before=id(z)
z[:]=x+y
id(z)==before
True
z=x+y
z
tensor([[ 3., 7., 11., 15.],
[19., 22., 13., 28.],
[13., 25., 28., 31.]])
z[:]=x+y
z
tensor([[ 3., 7., 11., 15.],
[19., 22., 13., 28.],
[13., 25., 28., 31.]])
before=id(x)
x+=y
id(x)==before
True
A=x.numpy()
B=torch.tensor(A)
type(A),type(B),
(numpy.ndarray, torch.Tensor)
c=torch.tensor([3.5])
c,c.item(),float(c),int(c)
(tensor([3.5000]), 3.5, 3.5, 3)
a=torch.arange(12)
b=a.reshape([3,4])
b[:]=2
a
tensor([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])