1 import torch 2 import numpy as np 3 4 # details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations 5 6 # convert numpy to tensor or vise versa 7 np_data = np.arange(6).reshape((2, 3)) 8 torch_data = torch.from_numpy(np_data) 9 tensor2array = torch_data.numpy() 10 print( 11 '\nnumpy array:', np_data, # [[0 1 2], [3 4 5]] 12 '\ntorch tensor:', torch_data, # 0 1 2 \n 3 4 5 [torch.LongTensor of size 2x3] 13 '\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]] 14 ) 15 16 17 # abs 18 data = [-1, -2, 1, 2] 19 tensor = torch.FloatTensor(data) # 32-bit floating point 20 print( 21 '\nabs', 22 '\nnumpy: ', np.abs(data), # [1 2 1 2] 23 '\ntorch: ', torch.abs(tensor) # [1 2 1 2] 24 ) 25 26 # sin 27 print( 28 '\nsin', 29 '\nnumpy: ', np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743] 30 '\ntorch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093] 31 ) 32 33 # mean 34 print( 35 '\nmean', 36 '\nnumpy: ', np.mean(data), # 0.0 37 '\ntorch: ', torch.mean(tensor) # 0.0 38 ) 39 40 # matrix multiplication 41 data = [[1,2], [3,4]] 42 tensor = torch.FloatTensor(data) # 32-bit floating point 43 # correct method 44 print( 45 '\nmatrix multiplication (matmul)', 46 '\nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]] 47 '\ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]] 48 ) 49 # incorrect method 50 data = np.array(data) 51 print( 52 '\nmatrix multiplication (dot)', 53 '\nnumpy: ', data.dot(data), # [[7, 10], [15, 22]] 54 '\ntorch: ', tensor.dot(tensor) # this will convert tensor to [1,2,3,4], you'll get 30.0 55 )