1. to_scalar()
1 import torch 2 import torch.autograd as autograd 3 import torch.nn as nn 4 import torch.optim as optim 5 from torch.autograd import Variable 6 7 torch.manual_seed(1234) 8 9 def to_scalar(var): 10 return var.view(-1).data.tolist()[0] 11 12 a = Variable(torch.LongTensor([[1, 3, 5], [2, 4, 5]])) 13 print(a) 14 ‘‘‘ 15 Variable containing: 16 1 3 5 17 2 4 5 18 [torch.LongTensor of size 2x3] 19 ‘‘‘ 20 print(a.view(-1)) 21 ‘‘‘ 22 Variable containing: 23 1 24 3 25 5 26 2 27 4 28 5 29 [torch.LongTensor of size 6] 30 ‘‘‘ 31 print(a.view(-1).data) 32 ‘‘‘ 33 1 34 3 35 5 36 2 37 4 38 5 39 [torch.LongTensor of size 6] 40 ‘‘‘ 41 print(a.view(-1).data.tolist()) 42 ‘‘‘ 43 [1, 3, 5, 2, 4, 5] 44 ‘‘‘ 45 print(a.view(-1).data.tolist()[0]) # 1 46 a = to_scalar(a) 47 print(a) # 1
2.
时间: 2024-10-17 19:44:52