1
import torch
1
2
x = torch.arange(12)#row vector
x
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
1
x.shape#size of tensor
torch.Size([12])
1
x.numel()#number of elements, the product of the number of rows and columns, called size大小
12
1
2
X1 = x.reshape(3, 4)
X1#Changing the shape doesn't change the size12
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
1
2
X2 = x.reshape(3, -1)
X2#automatically adjust the shape using -1
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
1
2
#create a torch with shape (2,3,4)
torch.zeros((2,3,4))
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.]]])
1
2
#create a torch with shape(3,4) and every element will have mean value 0, var 1
torch.randn(3,4)
tensor([[ 0.1186, -1.9117,  0.3001, -0.4835],
        [ 0.0431, -0.2108,  1.5440,  0.3805],
        [-0.0525,  0.5332,  1.3334,  1.7662]])

2.1.2 operator

1
2
3
4
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
#The calculation will conduct using one element in the first tensor and corresponding element in the second.
(tensor([ 3.,  4.,  6., 10.]),
 tensor([-1.,  0.,  2.,  6.]),
 tensor([ 2.,  4.,  8., 16.]),
 tensor([0.5000, 1.0000, 2.0000, 4.0000]),
 tensor([ 1.,  4., 16., 64.]))
1
torch.exp(x)
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])
1
2
3
4
X = torch.arange(12, dtype=torch.float32).reshape((3, 4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
#We concatenate elements by axis, dim=0 stands for x-axis, so (3, 4) -> (6, 4)
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [ 2.,  1.,  4.,  3.],
         [ 1.,  2.,  3.,  4.],
         [ 4.,  3.,  2.,  1.]]),
 tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))
1
2
X == Y
#It can be used to construct bool tensor.
tensor([[False,  True, False,  True],
        [False, False, False, False],
        [False, False, False, False]])
1
X.sum()
tensor(66.)

2.1.3 broadcasting machanism

1
2
3
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b
(tensor([[0],
         [1],
         [2]]),
 tensor([[0, 1]]))
1
2
3
4
a + b
#Due to diffenent shape, both the two tensor would broadcast rows and columns respectively,
#and become the same size, then complete addition.
#a deplicate columns, b deplicate rows.
tensor([[0, 1],
        [1, 2],
        [2, 3]])

2.1.4 indexing and splitting into piece

1
2
X[-1], X[1:3]
#1:3 represents 2nd and 3rd.
(tensor([ 8.,  9., 10., 11.]),
 tensor([[ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.]]))
1
2
3
X[1, 2] = 9
X
#write new element into matrix
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  9.,  7.],
        [ 8.,  9., 10., 11.]])
1
2
3
X[0:2, :] = 12
X
#First access 1st row and 2nd row, then determine the whole column, written by 12.
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])

2.1.5 saving RAM

1
2
3
4
5
before = id(Y)
Y = Y + X
id(Y) == before
#id shows the accurate address of the accessed object Y.
#Y = Y + X, then id(Y) will point to a new location.
False
1
2
3
4
5
6
#but we don't want to use new memory every time.
Z = torch.zeros_like(Y)# it has the same shape as Y, but elements all 0
print('id(Z):', id(Z))
Z[:] = X + Y;
print('id(Z):', id(Z))
#That is we can use cutting into piece method to assign new results to previous Z
id(Z): 4460493216
id(Z): 4460493216
1
2
3
4
before = id(X)
X += Y
id(X) == before
#we can also use X adding to itself, to save memory.
True

2.1.6 translating into other Python objects

1
2
3
4
A = X.numpy()
B = torch.tensor(A)
A, B, type(A), type(B)
#torch tensor and numpy array could share their bottom memory.
(array([[26., 25., 28., 27.],
        [25., 26., 27., 28.],
        [20., 21., 22., 23.]], dtype=float32),
 tensor([[26., 25., 28., 27.],
         [25., 26., 27., 28.],
         [20., 21., 22., 23.]]),
 numpy.ndarray,
 torch.Tensor)
1
2
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
(tensor([3.5000]), 3.5, 3.5, 3)

2.2 data preprocessing

2.2.1 reading datasets

1
2
3
4
5
6
7
8
9
10
11
12
import os

os.makedirs(os.path.join('.', 'data'), exist_ok=True)#if dir exists, no error will be displayed, if not, we will create it.
data_file = os.path.join('.', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
f.write('''
NumRooms, RoofType, Price
NA, NA, 127500
2, NA, 106000
4, Slate, 178100
NA, NA, 140000''')
f.close()
1
2
3
4
import pandas as pd
data = pd.read_csv(data_file)
print(data)
#extract information from table.
      NumRooms  RoofType   Price
0           NA        NA  127500
1            2        NA  106000
2            4     Slate  178100
3           NA        NA  140000

2.2.2 data preparation

1
2
3
4
5
6
7
inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]
#note: in this function iloc(), the inputs index we specify is 0th column and 1st column, different as previous.
inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)
#iloc is to choose specific rows and columns.
#get_dummies is a encoding method called one-hot encoding,
#which can regard NaN as a feature like previous features, creating 2-based columns.
       NumRooms_    2      NumRooms_    4      NumRooms_    NA  \
0               False               False                 True   
1                True               False                False   
2               False                True                False   
3               False               False                 True   

       NumRooms_nan   RoofType_ NA   RoofType_ Slate   RoofType_nan  
0             False           True             False          False  
1             False           True             False          False  
2             False          False              True          False  
3             False           True             False          False  
1
2
3
inputs = inputs.fillna(inputs.mean)
print(inputs)
#using mean value to pad NaN value
       NumRooms_    2      NumRooms_    4      NumRooms_    NA  \
0               False               False                 True   
1                True               False                False   
2               False                True                False   
3               False               False                 True   

       NumRooms_nan   RoofType_ NA   RoofType_ Slate   RoofType_nan  
0             False           True             False          False  
1             False           True             False          False  
2             False          False              True          False  
3             False           True             False          False  

2.2.3 Conversion to the Tensor Format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import torch
import os
import pandas as pd
data_file = os.path.join('.', 'data','house_tiny.csv')
with open(data_file, 'w') as f:
f.write('''
NumRooms, RoofType, Price
3.0, Slate, 127500
2.0, Slate, 110000
4, Slate, 140000''')
data = pd.read_csv(data_file)#firstly read the csv file
inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]#choosing specific rows and columns
inputs = pd.get_dummies(inputs, dummy_na=True)#inputs only contains former two columns, not including Price.
inputs = inputs.astype('float64')
targets = targets.astype('float64')#type converting
print(inputs)
f.close()
X, Y = torch.tensor(inputs.values), torch.tensor(targets.values)
X, Y
       NumRooms   RoofType_ Slate   RoofType_nan
0           3.0               1.0            0.0
1           2.0               1.0            0.0
2           4.0               1.0            0.0

(tensor([[3., 1., 0.],
         [2., 1., 0.],
         [4., 1., 0.]], dtype=torch.float64),
 tensor([127500., 110000., 140000.], dtype=torch.float64))