【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 中的时间序列分析和自然语言处理的基本方法。时间序列分析包括特征提取、时间序列拆分和预测模型,而自然语言处理涵盖了文本特征提取和文本分类。希望这些知识能在你的实际项目中有所帮助,并激发你进一步探索更复杂的时间序列和自然语言处理技术。

相关推荐
骚戴11 分钟前
2025 Python AI 实战:零基础调用 LLM API 开发指南
人工智能·python·大模型·llm·api·ai gateway
Cherry的跨界思维13 分钟前
【AI测试全栈:质量模型】4、新AI测试金字塔:从单元到社会的四层测试策略落地指南
人工智能·单元测试·集成测试·ai测试·全栈ai·全栈ai测试·社会测试
亚马逊云开发者30 分钟前
使用Amazon Nova模型实现自动化视频高光剪辑
人工智能
Tony Bai36 分钟前
Go 的 AI 时代宣言:我们如何用“老”原则,解决“新”问题?
开发语言·人工智能·后端·golang
卤代烃1 小时前
🦾 可为与不可为:CDP 视角下的 Browser 控制边界
前端·人工智能·浏览器
ggabb1 小时前
海南封关:锚定中国制造2025,破解产业转移生死局
大数据·人工智能
_XU1 小时前
AI工具如何重塑我的开发日常
前端·人工智能·深度学习
Blossom.1182 小时前
Prompt工程与思维链优化实战:从零构建动态Few-Shot与CoT推理引擎
人工智能·分布式·python·智能手机·django·prompt·边缘计算
zxsz_com_cn2 小时前
设备预测性维护典型案例:中讯烛龙赋能高端制造降本增效
人工智能
人工智能培训3 小时前
图神经网络初探(1)
人工智能·深度学习·知识图谱·群体智能·智能体