Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Convert PyTorch tensor to python list

How do I convert a PyTorch Tensor into a python list?

My current use case is to convert a tensor of size [1, 2048, 1, 1] into a list of 2048 elements.

My tensor has floating point values. Is there a solution which also accounts for int and possibly other data types?

question from:https://stackoverflow.com/questions/53903373/convert-pytorch-tensor-to-python-list

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

1 Reply

0 votes
by (71.8m points)

I found Tensor.tolist() which gives the following usage example:

>>> import torch
>>> a = torch.randn(2, 2)
>>> a.tolist()
[[0.012766935862600803, 0.5415473580360413],
 [-0.08909505605697632, 0.7729271650314331]]
>>> a[0,0].tolist()
0.012766935862600803

So, to answer the question, use a.squeeze().tolist() to remove all dimensions of size 1.

Also consider .flatten() if a list of lists is not desired.


Before I came across .tolist(), I was using:

list = [element.item() for element in tensor.flatten()]

This flattens the tensor into a single dimension then calls .item() to convert each element into a Python number.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...