Help us understand the problem. What is going on with this article?

Create Pytorch DataLoader from numpy.array

More than 1 year has passed since last update.

scikit-learnのデータセット(ndarray) からPyTorchのDataLoaderを作るのにすこし躓いた.


# データ作成
from sklearn.datasets import fetch_mldata
from sklearn.model_selection import train_test_split

mnist = fetch_mldata("MNIST original")
X =  # shape(70000, 784)
y =  # shape(70000)

# ndarrayからインスタンスを一つずつ取り出してtorch.Tensorに変換してリストに入れる
tensor_X = torch.stack([torch.from_numpy(np.array(i)) for i in X])
tensor_y = torch.stack([torch.from_numpy(np.array(i)) for i in y])

# trainとtestで分ける
train_size = 60000
X_train = tensor_X[:train_size]
y_train = tensor_y[:train_size]
X_test = tensor_X[train_size:]
y_test = tensor_y[train_size:]

# DataLoaderを作る
train_dataset =, y_train)
train_loader =

test_dataset =, y_test)
test_loader =
X =
y =


やってみた系とメモはこっち。 何か制作した系はブログ。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away