详解 Scikit-learn 的 datasets.fetch_rcv1函数:加载新闻数据集

  • Post category:Python

Scikit-learn 的 sklearn.datasets.fetch_rcv1 函数用于从 Reuters Corpus Volume I 数据集(RCV1)中加载文本数据集。RCV1 是由 Reuters News Limited 和 RCv1 Consortium 集体创建的机器学习数据集,包含大量新闻文章的多标签分类。该函数的作用是将 RCV1 数据集下载到本地,并返回一个 Python 字典,其中包含该数据集的信息。下面是该函数的完整使用方法:

from sklearn.datasets import fetch_rcv1

rcv1 = fetch_rcv1(data_home=None, subset='all', dtype=None, download_if_missing=True)

参数说明:

  • data_home: (默认为 None)数据集文件默认存储路径。如果为 None,则会将数据集下载到 ~/scikit_learn_data 目录下。
  • subset: (默认为 'all')数据集子集名称。目前只有一个子集 'all'
  • dtype: (默认为 None)要加载的数据类型。如果为 None,则返回数据集副本。
  • download_if_missing: (默认为 True)如果数据集文件不存在,则是否下载该文件。

该函数返回一个 Python 字典,其中包含以下键值:

  • data: {array-like, sparse matrix} 数据集的特征矩阵,由csr_matrix格式的稀疏矩阵表示的文本文档。
  • target: {array-like, sparse matrix} 数据集的标签矩阵,由 CSR 矩阵表示的多标签设置。
  • sample_id: {array-like} 数据集文档标识符和标签矩阵的索引,按数量遍历文档和标签。
  • target_names: {list} 数据集中的目标变量名称。
  • DESCR: {str} 数据集的描述。

下面是两个实际使用的示例:

示例 1:加载整个 RCV1 数据集

from sklearn.datasets import fetch_rcv1

rcv1 = fetch_rcv1(subset='all', download_if_missing=True)
print(rcv1.DESCR)

输出:

Reuters Corpus Volume I (RCV1)  Subset of Reuters Articles, 1996
----------------------------------------------------------------------
Data Set Information:

    This is a collection of Reuters News articles, consisting of   articles extracted from the newswire articles classified into 103 topics, described in the file topics.txt, including World News, Industry News, and Sports. The total number of articles is 804414, in training set of 23149 documents and 781265 for testing set.

[...]

我们用 fetch_rcv1 函数加载了整个 RCV1 数据集,并打印出数据集的描述。

示例 2:加载 RCV1 小数据子集

from sklearn.datasets import fetch_rcv1

rcv1 = fetch_rcv1(subset='train', download_if_missing=True)
print(f"The dataset contains {rcv1.data.shape[0]} articles with {rcv1.data.shape[1]} features.")

输出:

The dataset contains 23149 articles with 47237 features.

我们用 fetch_rcv1 函数加载 RCV1 的小数据子集,并打印出数据集的大小信息。