Python 使用 sklearn 的 MNIST 数据集,select 特定数字

Python MNIST dataset using sklearn, select specific digits

我正在使用 Sklearn 在 MNIST 数据集上训练几个模型,如何仅使用 MNIST 数据集中的两个数字 4 和 9(两个 类)来训练线性模型?

所以您只想使用数字 4 和 9 的图像。

您需要像 X[np.logical_or(y == 4, y == 9)] 这样的索引:

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits

digits = load_digits()

X = digits.data
y = digits.target

#Select only the digit 4 and 9 images
X = X[np.logical_or(y == 4, y == 9)]
y = y[np.logical_or(y == 4, y == 9)]

# verify selection
np.unique(y)
#array([4, 9])

# Now split them
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=200, test_size=100)

只使用数字 4:

X = digits.data
y = digits.target

#Select only the digit 4 and 9 images
X = X[y == 4]
y = y[y == 4]