python - 创建一个 pyTorch 测试数据集(无标签)
问题描述
我为我的训练数据创建了一个 pyTorch 数据集,该数据集由特征和标签组成,以便能够使用本教程使用 pyTorch DataLoader。这对我的训练数据很有效,但KeyError: "['label'] not found in axis"
在加载测试 csv 文件时出现错误 (),除了没有“标签”列之外,它是相同的。
如果有帮助,预期的输入 csv 文件是 csv 文件中的 MNIST 数据,它具有 28*28 特征列。
import torch
class mnist(torch.utils.data.Dataset):
def __init__(self, csv_file):
self.train = pd.read_csv(csv_file)
self.train_x = self.train.drop("label", axis=1)
def __len__(self):
return len(self.train)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
if isinstance(idx, list):
idx_len = len(idx)
else:
idx_len = 1
X = np.asarray(self.train_x.iloc[idx], dtype=np.float32)
X = np.reshape(X, (1,28,28))
y = np.asarray(self.train.iloc[idx]['label'])
sample = {'X': X, 'y':y}
return torch.from_numpy(sample['X']), torch.from_numpy(sample['y'])
解决方案
您应该能够使用这两个数据:
import torch
class mnist(torch.utils.data.Dataset):
def __init__(self, csv_file):
self.train = pd.read_csv(csv_file)
self.training = "label" in self.train.columns
self.train_x = self.train if not self.training else self.train.drop("label", axis=1)
def __len__(self):
return len(self.train)
def __getitem__(self, idx):
...
X = np.asarray(self.train_x.iloc[idx], dtype=np.float32)
X = np.reshape(X, (1,28,28))
if not self.training:
return torch.from_numpy(X])
y = np.asarray(self.train.iloc[idx]['label'])
sample = {'X': X, 'y':y}
return torch.from_numpy(sample['X']), torch.from_numpy(sample['y'])
推荐阅读
- sas - SAS:计算(加、减、乘、除)数据集中的值
- django - 如何遍历两个模型以获取 django 模板中的属性差异?
- flutter - NoSuchMethodError:在 null 上调用了方法“isBefore”
- c++ - 快速逆平方根算法是否比 C++ 的标准库 sqrt() 函数更快?
- delphi - 如何将 IPWorks 与自签名 SSL 证书一起使用?
- javascript - Puppeteer 中的 jsHandle 和 elementHandle 有什么区别?
- asp.net-core - .Net Core 5 中的自定义授权属性
- python - 通过在列表之间映射值来创建列表
- amazon-web-services - 有什么方法可以像 Microsoft Learn 中那样使用 AWS/Azure 创建限时 Windows 沙盒?
- html - 每当单击按钮时如何阻止页面向上滚动?