簡體   English   中英

將 CSV 解析為 Pytorch 張量

[英]Parsing CSV into Pytorch tensors

我有一個 CSV 文件,其中包含除 header 行以外的所有數值。 嘗試構建張量時,出現以下異常:

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'

這是我的代碼:

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)

使用pandas而不是Dask進行 CSV 解析產生了同樣的錯誤。 我還嘗試在對torch.tensor(data)的調用中指定dtype=torch.float64 ,但再次遇到相同的錯誤。

首先嘗試將其轉換為數組:

test_tensor = torch.Tensor(test.values)

我認為你只是缺少.values

import torch
import pandas as pd

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

新版本的to_numpy強烈建議使用to_numpy而不是values

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

僅使用 NumPy

import numpy as np
import torch

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM