使用 Scikit-Learn 进行特征提取

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何使用 scikit-learn 库进行特征提取。特征提取是将原始数据转换为机器学习算法可以使用的数值特征的过程。它涉及从不同类型的数据(如文本和图像)中提取相关信息。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn(("Sklearn")) -.-> sklearn/DataPreprocessingandFeatureEngineeringGroup(["Data Preprocessing and Feature Engineering"]) sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/feature_extraction("Feature Extraction") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/feature_extraction -.-> lab-71129{{"使用 Scikit-Learn 进行特征提取"}} ml/sklearn -.-> lab-71129{{"使用 Scikit-Learn 进行特征提取"}} end

从字典中加载特征

在这一步中,我们将学习如何使用 scikit-learn 中的DictVectorizer类从字典中加载特征。

from sklearn.feature_extraction import DictVectorizer

measurements = [
    {'city': 'Dubai', 'temperature': 33.},
    {'city': 'London', 'temperature': 12.},
    {'city': 'San Francisco', 'temperature': 18.},
]

vec = DictVectorizer()
features = vec.fit_transform(measurements).toarray()
feature_names = vec.get_feature_names_out()

print(features)
print(feature_names)

特征哈希

在这一步中,我们将学习如何使用 scikit-learn 中的FeatureHasher类执行特征哈希。特征哈希是一种使用哈希函数将特征映射到固定长度向量的技术。

from sklearn.feature_extraction import FeatureHasher

movies = [
    {'category': ['thriller', 'drama'], 'year': 2003},
    {'category': ['animation', 'family'], 'year': 2011},
    {'year': 1974},
]

hasher = FeatureHasher(input_type='string')
hashed_features = hasher.transform(movies).toarray()

print(hashed_features)

文本特征提取

在这一步中,我们将学习如何使用 scikit-learn 中的CountVectorizerTfidfVectorizer类来执行文本特征提取。这些类可用于将文本数据转换为数值特征。

from sklearn.feature_extraction.text import CountVectorizer

corpus = [
    'This is the first document.',
    'This is the second second document.',
    'And the third one.',
    'Is this the first document?'
]

vectorizer = CountVectorizer()
features = vectorizer.fit_transform(corpus).toarray()
feature_names = vectorizer.get_feature_names_out()

print(features)
print(feature_names)

自定义向量化器类

在这一步中,我们将学习如何通过向向量化器类传递可调用函数来定制它们的行为。

def my_tokenizer(s):
    return s.split()

vectorizer = CountVectorizer(tokenizer=my_tokenizer)
features = vectorizer.fit_transform(corpus).toarray()

print(features)

总结

在这个实验中,我们学习了如何使用 scikit-learn 库进行特征提取。我们探索了各种技术,如从字典中加载特征、特征哈希和文本特征提取。我们还学习了如何定制向量化器类的行为以满足我们的特定需求。特征提取是机器学习中的一个重要步骤,因为它有助于将原始数据转换为算法可以用来进行预测或对数据进行分类的格式。