load_files#

sklearn.datasets.load_files(container_path, *, description=None, categories=None, load_content=True, shuffle=True, encoding=None, decode_error='strict', random_state=0, allowed_extensions=None)[source]#

加载子文件夹名称为类别的文本文件。

假设单个样本是存储在两级文件夹结构中的文件,例如以下结构

container_folder/
    category_1_folder/
        file_1.txt
        file_2.txt
        ...
        file_42.txt
    category_2_folder/
        file_43.txt
        file_44.txt
        ...

文件夹名称用作监督信号标签名称。单个文件名并不重要。

此函数不尝试将特征提取到 numpy 数组或 scipy 稀疏矩阵中。此外,如果 load_content 为 false,它不尝试将文件加载到内存中。

要在 scikit-learn 分类或聚类算法中使用文本文件,您需要使用 text 模块来构建适合您问题的特征提取转换器。

如果您设置 load_content=True,您还应该使用“encoding”参数指定文本的编码。对于许多现代文本文件,“utf-8”将是正确的编码。如果您将编码保留为 None,则内容将由字节而不是 Unicode 组成,并且您将无法使用 text 中的大多数函数。

应为其他类型的非结构化数据输入(例如图像、音频、视频等)构建类似的特征提取器。

如果您需要具有特定文件扩展名(例如 .txt)的文件,则可以将这些文件扩展名的列表传递给 allowed_extensions

用户指南 中阅读更多内容。

参数:
container_pathstr

指向主文件夹的路径,每个类别包含一个子文件夹。

descriptionstr, default=None

描述数据集特征的段落:其来源、引用等。

categorieslist of str, default=None

如果为 None(默认),则加载所有类别。如果不为 None,则为要加载的类别名称列表(忽略其他类别)。

load_contentbool, default=True

是否加载不同文件的内容。如果为 True,则返回的数据结构中存在包含文本信息的“data”属性。如果不是,则 filenames 属性提供文件的路径。

shufflebool, default=True

是否打乱数据:对于假设样本独立同分布 (i.i.d.) 的模型(例如随机梯度下降)可能很重要。

encodingstr, default=None

如果为 None,则不尝试解码文件的内容(例如图像或其他非文本内容)。如果不为 None,则在 load_content 为 True 时用于将文本文件解码为 Unicode 的编码。

decode_error{‘strict’, ‘ignore’, ‘replace’}, default=’strict’

关于如何处理给定用于分析的字节序列包含不在给定 encoding 中的字符的说明。作为关键字参数“errors”传递给 bytes.decode。

random_stateint, RandomState instance or None, default=0

Determines random number generation for dataset shuffling. Pass an int for reproducible output across multiple function calls. See Glossary.

allowed_extensionslist of str, default=None

所需文件扩展名的列表,用于过滤要加载的文件。

返回:
dataBunch

Dictionary-like object, with the following attributes.

datalist of str

仅当 load_content=True 时才存在。用于学习的原始文本数据。

targetndarray

目标标签(整数索引)。

target_nameslist

The names of target classes.

DESCRstr

The full description of the dataset.

filenames: ndarray

保存数据集的文件名。

示例

>>> from sklearn.datasets import load_files
>>> container_path = "./"
>>> load_files(container_path)