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

相关推荐
胡耀超2 分钟前
知识图谱入门——3:工具分类与对比(知识建模工具:Protégé、 知识抽取工具:DeepDive、知识存储工具:Neo4j)
人工智能·知识图谱
陈苏同学10 分钟前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
吾名招财28 分钟前
yolov5-7.0模型DNN加载函数及参数详解(重要)
c++·人工智能·yolo·dnn
鼠鼠龙年发大财1 小时前
【鼠鼠学AI代码合集#7】概率
人工智能
龙的爹23331 小时前
论文 | Model-tuning Via Prompts Makes NLP Models Adversarially Robust
人工智能·gpt·深度学习·语言模型·自然语言处理·prompt
工业机器视觉设计和实现1 小时前
cnn突破四(生成卷积核与固定核对比)
人工智能·深度学习·cnn
我算是程序猿2 小时前
用AI做电子萌宠,快速涨粉变现
人工智能·stable diffusion·aigc
萱仔学习自我记录2 小时前
微调大语言模型——超详细步骤
人工智能·深度学习·机器学习
湘大小菜鸡3 小时前
NLP进阶(一)
人工智能·自然语言处理
XiaoLiuLB3 小时前
最佳语音识别 Whisper-large-v3-turbo 上线,速度更快(本地安装 )
人工智能·whisper·语音识别