23

I have a CSV files with all numeric values except the header row. When trying to build tensors, I get the following exception:

Traceback (most recent call last):
  File "pytorch.py", line 14, in <module>
    test_tensor = torch.tensor(test)
ValueError: could not determine the shape of object type 'DataFrame'

This is my code:

import torch
import dask.dataframe as dd

device = torch.device("cuda:0")

print("Loading CSV...")
test = dd.read_csv("test.csv", encoding = "UTF-8")
train = dd.read_csv("train.csv", encoding = "UTF-8")

print("Converting to Tensor...")
test_tensor = torch.tensor(test)
train_tensor = torch.tensor(train)

Using pandas instead of Dask for CSV parsing produced the same error. I also tried to specify dtype=torch.float64 inside the call to torch.tensor(data), but got the same error again.

5 Answers 5

24

Try converting it to an array first:

test_tensor = torch.Tensor(test.values)
Sign up to request clarification or add additional context in comments.

2 Comments

Doing so results in the following error: Traceback (most recent call last): File "pytorch.py", line 11, in <module> test_tensor = torch.tensor(test.values) ValueError: cannot convert float NaN to integer
I cannot get the same error here even though I have some NaNs in the dataframe. Does it come from pandas (test.values)? What are test.dtypes? Are there any int columns? It may help to change them to floats.
14

I think you're just missing .values

import torch
import pandas as pd

train = pd.read_csv('train.csv')
train_tensor = torch.tensor(train.values)

Comments

8

Newer version of pandas highly recommend to use to_numpy instead of values

train_tensor = torch.tensor(train.to_numpy())

Comments

1

Only using NumPy

import numpy as np
import torch

tensor = torch.from_numpy(
    np.genfromtxt("train.csv", delimiter=",")
)

Comments

0

The import functions all appear to require a .csv with an array of numbers. You mentioned in your original problem case that your .csv includes column headers. Please try your code without the headers in the .csv file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.