将Pandas数据框转换为PyTorch张量? [英] Convert Pandas dataframe to PyTorch tensor?

查看:2532
本文介绍了将Pandas数据框转换为PyTorch张量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用个人数据库在PyTorch上训练一个简单的神经网络.该数据库是从Excel文件导入的,并存储在df中.

I want to train a simple neural network on PyTorch using a personal database. This database is imported from an Excel file and stored in df.

其中一列名为"Target",它是网络的目标变量.我如何使用此数据框作为PyTorch神经网络的输入?

One of the columns is named "Target", and it is the target variable of the network. How can i use this data frame as an input for the PyTorch neural network?

我尝试了此操作,但没有用:

I tried this, but it doesn't work:

target = pd.DataFrame(data = df['Target'])
train = data_utils.TensorDataset(df, target)
train_loader = data_utils.DataLoader(train, batch_size = 10, shuffle = True)

推荐答案

我指的是标题中的问题,因为您实际上并未在文本中指定其他任何内容,因此只需将DataFrame转换为PyTorch张量即可.

I'm referring to the question in the title as you haven't really specified anything else in the text, so just converting the DataFrame into a PyTorch tensor.

在没有有关您的数据的信息的情况下,我仅以浮点值作为示例目标.

Without information about your data, I'm just taking float values as example targets here.

将Pandas数据框转换为PyTorch张量吗?

import pandas as pd
import torch
import random

# creating dummy targets (float values)
targets_data = [random.random() for i in range(10)]

# creating DataFrame from targets_data
targets_df = pd.DataFrame(data=targets_data)
targets_df.columns = ['targets']

# creating tensor from targets_df 
torch_tensor = torch.tensor(targets_df['targets'].values)

# printing out result
print(torch_tensor)

输出:

tensor([ 0.5827,  0.5881,  0.1543,  0.6815,  0.9400,  0.8683,  0.4289,
         0.5940,  0.6438,  0.7514], dtype=torch.float64)

使用Pytorch 0.4.0进行了测试.

如果您还有其他问题,我希望这会有所帮助-请问一下. :)

I hope this helps, if you have any further questions - just ask. :)

这篇关于将Pandas数据框转换为PyTorch张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆