第3章回帰のための線形ニューラルネットワーク
3.3.3. Concise Implementation of the Data Loader3.3.3 データローダーの簡潔な実装
Rather than writing our own iterator, we can call the existing API in a framework to load data. As before, we need a dataset with features
X and labels y. Beyond that, we set batch_size in the built-in data loader and let it take care of shuffling examples efficiently.英語のヒント
自分でイテレータを書く代わりに、フレームワークの既存のAPIを呼び出してデータを読み込める。前と同じく、特徴量
Xとラベルyをもつデータセットが必要である。それに加えて、組み込みのデータローダーにbatch_sizeを設定し、事例のシャッフルを効率よく任せる。@d2l.add_to_class(d2l.DataModule) #@save
def get_tensorloader(self, tensors, train, indices=slice(0, None)):
tensors = tuple(a[indices] for a in tensors)
dataset = torch.utils.data.TensorDataset(*tensors)
return torch.utils.data.DataLoader(dataset, self.batch_size,
shuffle=train)
@d2l.add_to_class(SyntheticRegressionData) #@save
def get_dataloader(self, train):
i = slice(0, self.num_train) if train else slice(self.num_train, None)
return self.get_tensorloader((self.X, self.y), train, i)The new data loader behaves just like the previous one, except that it is more efficient and has some added functionality.
英語のヒント
新しいデータローダーは前のものとまったく同じように振る舞うが、より効率がよく、いくつかの機能が加わっている。
X, y = next(iter(data.train_dataloader()))
print('X shape:', X.shape, '\ny shape:', y.shape)X shape: torch.Size([32, 2])
y shape: torch.Size([32, 1])For instance, the data loader provided by the framework API supports the built-in
__len__ method, so we can query its length, i.e., the number of batches.英語のヒント
たとえば、フレームワークのAPIが提供するデータローダーは組み込みの
__len__メソッドに対応しているので、その長さ、つまりバッチの数を問い合わせられる。len(data.train_dataloader())32