1. Check whether it is a tensor object
torch.is_tensor(x)
2. Construct a row and two columns of random numbers
y = torch.rand(1,2)
Three, the tensor has several elements
torch.numel(y)
4. Create a tensor
z = torch.zeros(3,3) with all 0s
5. Create a tensor
torch.eye(3,3) with a diagonal of 1
6. Convert numpy to tensor
import numpy as np
x = np.array([3,4,5,6,7])
torch.from_numpy(x)
7. Segment linspace, steps indicate the number of shares
torch.linspace(2,10,steps=5)
Eight, uniform distribution, the value is between 0 and 1
torch.rand(10)
9. Normal distribution, with a mean of 0 and a variance of 1
torch.randn(10)
10. Choose random numbers and disrupt the order
torch.randperm(10)
Eleven, generate an interval number, (10,30), 5 steps, not including 30
torch.arange(10,30,5)
12. Get the index
x = torch.randint(1,99,(3,3)) of the minimum and maximum values of the row or column
# dim is 1 for rows, 0 for columns
torch.argmin(x,dim=0)
torch.argmax(x,dim=0)
Thirteen, connect
x = torch.randint(1,10,(2,3))
# Vertical axis connection
torch.cat((x,x))
# The horizontal axis is connected
torch.cat((x,x),dim=1) #1 is the horizontal axis
Fourteen, cut chunk
a = torch.randint(1,10,(3,3))
torch.chunk(a,2,0) #0 means one cut horizontally, 1 means one cut vertically
torch.chunk(a,2,1)
Fifteen, index_select Select
x according to the index = torch.randn(4,4)
indices = torch.tensor([0,2]) # select 0 and 2 for the subscript
torch.index_select(x,0,indices) # Horizontal 0 and 2 rows
Sixteen, split style
x = torch.tensor([1,2,3,4,5,6,7])
torch.split(x,3) # cut three parts
Seventeen, transpose .t and .transpose
x = torch.tensor([[1,2],[3,4]])
xt() === x.transpose(1,0) #The effect is the same
Eighteen, tensor operation
x = torch.tensor([[1,2],[3,4]])
torch.add(x,1) # add one overall
torch.mul(x,2) # multiply by 2 as a whole