sklearn.datasets.fetch_openml()
fetch_openml()
是 sklearn.datasets
提供的 开放数据集接口,可从 OpenML 平台下载 真实世界数据集,适用于 机器学习研究和模型测试。
1. fetch_openml()
作用
- 访问 OpenML 平台上的数据集,无需手动下载 CSV 文件。
- 数据可直接用于 Pandas 或 NumPy,兼容
scikit-learn
。 - 适用于分类、回归、聚类任务,数据量大且丰富。
2. fetch_openml()
代码示例
(1) 下载 MNIST
数据集
from sklearn.datasets import fetch_openml
# 下载 MNIST 数据集
mnist = fetch_openml("mnist_784", version=1, as_frame=False)
# 获取特征矩阵和目标变量
X, y = mnist.data, mnist.target
print("特征矩阵形状:", X.shape)
print("目标变量形状:", y.shape)
输出
特征矩阵形状: (70000, 784)
目标变量形状: (70000,)
解释
X.shape = (70000, 784)
:包含70,000
张28×28
手写数字图片,每个样本展平成784
个像素。y.shape = (70000,)
:每个样本的数字标签 (0-9
)。
(2) 可视化 MNIST
数据
import matplotlib.pyplot as plt
import numpy as np
# 随机选取一张图片
index = np.random.randint(0, 70000)
image = X[index].reshape(28, 28) # 变回 28×28 图片
label = y[index]
# 显示手写数字
plt.imshow(image, cmap="gray")
plt.title(f"Label: {label}")
plt.show()
解释
X[index].reshape(28, 28)
:从784
维数据恢复28×28
图片。plt.imshow()
可视化手写数字。
3. fetch_openml()
数据格式
print(type(mnist))
输出
<class 'sklearn.utils._bunch.Bunch'>
解释
fetch_openml()
返回Bunch
对象,类似于字典,可通过.data
、.target
访问数据。
(3) 转换为 Pandas DataFrame
import pandas as pd
# 下载 Titanic 数据集
titanic = fetch_openml("titanic", version=1, as_frame=True)
# 转换为 DataFrame
df = titanic.frame
print(df.head())
输出
pclass survived name sex age sibsp parch ticket fare cabin embarked boat body home.dest
0 1 1 Allen, Mr female 29.0 0 0 24160 211.3375 B5 S 2 NaN NaN
1 1 1 Allison, female 2.0 1 2 113781 151.5500 C22 C26 S 11 NaN Montreal
2 1 0 Allison, male 30.0 1 2 113781 151.5500 C22 C26 S NaN 135.0 Montreal
3 1 0 Allison, male 25.0 1 2 113781 151.5500 C22 C26 S NaN NaN Montreal
4 1 0 Allison, male 48.0 1 2 113781 151.5500 C22 C26 S NaN NaN Montreal
解释
as_frame=True
返回 Pandas DataFrame,适用于数据分析。
4. fetch_openml()
参数
fetch_openml(data_id=None, name=None, version="active", as_frame=False, parser="auto", cache=True)
参数 | 说明 |
---|---|
data_id | OpenML 数据集 ID(如 mnist_784 ) |
name | OpenML 数据集名称 |
version | 选择数据集的版本 |
as_frame | 是否返回 Pandas DataFrame(默认 False ) |
cache | 是否缓存数据(默认 True ) |
5. 适用场景
- 获取真实世界数据集,用于分类、回归、聚类任务。
- 避免手动下载数据,提高实验效率。
- 可直接用于
scikit-learn
模型训练。
6. fetch_openml()
vs. 其他数据集
方法 | 适用情况 | 作用 |
---|---|---|
fetch_openml() | 获取真实数据集 | 访问 OpenML 数据库 |
fetch_california_housing() | 房价预测 | 回归任务 |
load_digits() | 手写数字 | 多分类任务 |
load_diabetes() | 糖尿病预测 | 回归任务 |
7. 结论
fetch_openml()
用于访问 OpenML 平台的数据集,适用于 机器学习研究 和 真实世界数据分析。- 可以 下载分类、回归、文本等各种类型的数据集,并 转换为 Pandas 进行分析。