Convert Pandas dataframe to PyTorch tensor?(将 Pandas 数据帧转换为 PyTorch 张量?)
问题描述
我想用 PyTorch 在 Pandas 数据帧上训练一个简单的神经网络 df
.
I want to train a simple neural network with PyTorch on a pandas dataframe df
.
其中一列名为Target"
,它是网络的目标变量.如何使用此数据帧作为 PyTorch 网络的输入?
One of the columns is named "Target"
, and it is the target variable of the network. How can I use this dataframe as input to the PyTorch network?
我试过了,但没有用:
import pandas as pd
import torch.utils.data as data_utils
target = pd.DataFrame(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 张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 Pandas 数据帧转换为 PyTorch 张量?


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01