Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

python - Torch sum a tensor along an axis

ipdb> outputs.size()
torch.Size([10, 100])
ipdb> print sum(outputs,0).size(),sum(outputs,1).size(),sum(outputs,2).size()
(100L,) (100L,) (100L,)

How do I sum over the columns instead?

question from:https://stackoverflow.com/questions/44790670/torch-sum-a-tensor-along-an-axis

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest and best solution is to use torch.sum().

To sum all elements of a tensor:

torch.sum(outputs) # gives back a scalar

To sum over all rows (i.e. for each column):

torch.sum(outputs, dim=0) # size = [1, ncol]

To sum over all columns (i.e. for each row):

torch.sum(outputs, dim=1) # size = [nrow, 1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...