【sklearn | 3】时间序列分析与自然语言处理

在前几篇教程中,我们介绍了 sklearn 的基础、高级功能,以及异常检测与降维。本篇教程将探讨两个进一步的应用领域:时间序列分析和自然语言处理(NLP)。

时间序列分析

时间序列数据是按时间顺序排列的数据,广泛应用于金融、经济、气象等领域。sklearn 中虽然没有专门的时间序列模块,但可以通过一些技巧和现有工具来处理时间序列数据。

时间序列特征提取

时间序列分析的一个重要步骤是特征提取。可以从时间序列中提取统计特征,如均值、标准差、最大值、最小值等。

python 复制代码
import numpy as np
import pandas as pd

# 生成模拟时间序列数据
np.random.seed(42)
time_series = np.random.randn(100)

# 提取统计特征
features = {
    'mean': np.mean(time_series),
    'std': np.std(time_series),
    'max': np.max(time_series),
    'min': np.min(time_series)
}

print(features)

时间序列拆分

将时间序列数据分为训练集和测试集时,需要确保数据的时间顺序不会被打乱。可以使用 TimeSeriesSplit 进行交叉验证。

python 复制代码
from sklearn.model_selection import TimeSeriesSplit

# 创建时间序列数据
data = np.arange(100).reshape(-1, 1)
labels = np.arange(100)

# 创建时间序列拆分器
tscv = TimeSeriesSplit(n_splits=5)

# 进行拆分
for train_index, test_index in tscv.split(data):
    X_train, X_test = data[train_index], data[test_index]
    y_train, y_test = labels[train_index], labels[test_index]
    print("TRAIN:", train_index, "TEST:", test_index)

示例:时间序列预测

我们将使用线性回归模型对时间序列进行简单的预测。

python 复制代码
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# 生成模拟时间序列数据
time = np.arange(100).reshape(-1, 1)
values = 2 * time + 1 + np.random.randn(100, 1)

# 划分训练集和测试集
X_train, X_test = time[:80], time[80:]
y_train, y_test = values[:80], values[80:]

# 训练线性回归模型
model = LinearRegression()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

自然语言处理(NLP)

NLP 是处理和分析自然语言文本的技术,广泛应用于文本分类、情感分析、机器翻译等领域。sklearn 提供了一些工具用于文本数据的处理和建模。

文本特征提取

将文本数据转换为数值特征是 NLP 的关键步骤。常用的方法包括词袋模型(Bag-of-Words)和 TF-IDF(Term Frequency-Inverse Document Frequency)。

词袋模型
python 复制代码
from sklearn.feature_extraction.text import CountVectorizer

# 生成文本数据
texts = ["I love machine learning", "Machine learning is fascinating", "I enjoy learning new things"]

# 词袋模型
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)

print("Vocabulary:", vectorizer.vocabulary_)
print("Feature Matrix:\n", X.toarray())
TF-IDF
python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer

# 生成文本数据
texts = ["I love machine learning", "Machine learning is fascinating", "I enjoy learning new things"]

# TF-IDF
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)

print("Vocabulary:", vectorizer.vocabulary_)
print("TF-IDF Matrix:\n", X.toarray())

文本分类

文本分类是 NLP 中的一个重要任务,常见应用包括垃圾邮件检测和情感分析。我们将使用朴素贝叶斯分类器进行文本分类。

python 复制代码
from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report

# 加载数据集
categories = ['alt.atheism', 'sci.space']
newsgroups = fetch_20newsgroups(subset='train', categories=categories)

# 特征提取
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(newsgroups.data)
y = newsgroups.target

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练朴素贝叶斯分类器
model = MultinomialNB()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
print(classification_report(y_test, y_pred, target_names=newsgroups.target_names))

综合示例项目:股票价格预测与新闻分类

步骤1:股票价格预测

我们将使用时间序列数据预测股票价格。

python 复制代码
import numpy as np
import pandas as pd
from sklearn.model_selection import TimeSeriesSplit
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# 生成模拟股票价格数据
np.random.seed(42)
dates = pd.date_range('2020-01-01', periods=100)
prices = np.cumsum(np.random.randn(100)) + 100

# 创建 DataFrame
data = pd.DataFrame({'Date': dates, 'Price': prices})
data.set_index('Date', inplace=True)

# 特征提取
data['Price_diff'] = data['Price'].diff()
data.dropna(inplace=True)

# 特征和标签
X = data[['Price_diff']].values
y = data['Price'].values[1:]

# 时间序列拆分
tscv = TimeSeriesSplit(n_splits=5)
for train_index, test_index in tscv.split(X):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    
    # 训练线性回归模型
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # 预测
    y_pred = model.predict(X_test)
    
    # 评估
    mse = mean_squared_error(y_test, y_pred)
    print(f"Mean Squared Error: {mse}")

步骤2:新闻分类

我们将使用朴素贝叶斯分类器对新闻进行分类。

python 复制代码
from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report

# 加载数据集
categories = ['rec.autos', 'rec.sport.baseball']
newsgroups = fetch_20newsgroups(subset='train', categories=categories)

# 特征提取
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(newsgroups.data)
y = newsgroups.target

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练朴素贝叶斯分类器
model = MultinomialNB()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
print(classification_report(y_test, y_pred, target_names=newsgroups.target_names))

总结

通过本篇进阶教程,我们学习了 sklearn 中的时间序列分析和自然语言处理的基本方法。时间序列分析包括特征提取、时间序列拆分和预测模型,而自然语言处理涵盖了文本特征提取和文本分类。希望这些知识能在你的实际项目中有所帮助,并激发你进一步探索更复杂的时间序列和自然语言处理技术。

相关推荐
linzᅟᅠ1 分钟前
README
人工智能·python
小猴子下山1238 分钟前
2026年无锡细胞存储市场格局观察:四家企业的传承脉络与业务分野
大数据·人工智能·精选
Database_Cool_11 分钟前
数据库慢查询优化首选方案:阿里云 RDS 性能洞察+自动诊断
数据库·人工智能·阿里云
北邮刘老师19 分钟前
国标配套开源实现再升级!AIP智能体互联开源项目v2.1.0正式发布
人工智能·开源·大模型·智能体·智能体互联网
zhoupenghui16822 分钟前
【AI大模型应用开发】【项目实战】13.RAG智慧问答项目-(一)项目介绍&项目架构&项目环境配置
人工智能·docker·ai·milvus·rag·attu·rag智慧问答项目
神奇小汤圆31 分钟前
AI Coding 不只靠 Prompt:Agent 工程闭环如何接入 DevOps
人工智能
hongmai66688834 分钟前
ESP32-S2-MINI-2U-N4R2:一款为灵活部署而生的Wi-Fi MCU模组
人工智能·单片机·嵌入式硬件·物联网·智能家居
神奇小汤圆37 分钟前
AI Agent 替你写代码没问题,但这 3 类后端任务让它当场翻车
人工智能
lyy-独立开发者1 小时前
主动推理-人工海马
人工智能
云栖梦泽在1 小时前
Claude Code / Codex 使用卡顿怎么办?AI 编程 Agent 连接失败与网络排查思路
网络·人工智能·网络协议·chatgpt·性能优化