[solved]How to turn list to Tensor?

According to the documents, we can create a Tensor with the data in ‘list’ object like this:

a = torch.FloatTensor([[1, 2, 3], [4, 5, 6]])

However, when I’m trying to initialize FloatTensor with list object in the following way:

def load_data_from_file(file_name='data.csv'):
    x = []
    y = []
    with open(file_name) as f:
        f_csv = csv.reader(f)
        headers = next(f_csv)
        for row in f_csv:
            x.append(row[3:9])
            y.append(row[9])
    return x, y


def convert2tensor(x):
    x = torch.FloatTensor(x)
    return x


def load_train_test(file_name='data.csv'):
    x, y = load_data_from_file(file_name)
    train_x = convert2tensor(x[:45])
    train_y = convert2tensor(y[:45])
    test_x = convert2tensor(x[45:])
    test_y = convert2tensor(y[45:])
    return Variable(train_x), Variable(train_y), Variable(test_x), Variable(test_y)

A runtime error occurs:

Traceback (most recent call last):
  File "/home/shawn/PythonWS/CDX/utils.py", line 32, in <module>
    x, y, x1, y1 = load_train_test()
  File "/home/shawn/PythonWS/CDX/utils.py", line 26, in load_train_test
    train_x = convert2tensor(x[:45])
  File "/home/shawn/PythonWS/CDX/utils.py", line 20, in convert2tensor
    x = torch.FloatTensor(x)
RuntimeError: already counted a million dimensions in a given sequence. Most likely your items are also sequences and there's no way to infer how many dimension should the tensor have

How could I solve this problem?

2 Likes

Alright, it’s caused by that data of ‘x’ is in type ‘str’.

May I ask what was the solution? I have some tuple in a list. want to convert each tuple to tensor.

Please provide description of what the problem exactly is (with code): what you are trying to do, what is your expected output, what you’ve tried etc. From what I’ve understood you have list of tuples (what data type?) and you want convert each tuple to tensor, so to form list of tensors?

Sure @mmisiur
There are two lists (e.g. A and B), each contains n number of tuples. for each to corresponding tuples in A and B, I wanna compute score:

a1 = []
b1 = []
score = []

for a1, b1 in zip(A, B):

  'score.append(torch.bmm(a1,b1))`

However, I faced an error as a1 and a2 are tuples, not tensors.
By adding this two lines before for loop, I still not able to reach my problem goal:

A = [item for sublist in A for item in sublist]
B = [item for sublist in B for item in sublist]