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


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

    时间序列分析

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

    时间序列特征提取

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

    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 进行交叉验证。

    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)
    

    示例:时间序列预测

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

    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)。

    词袋模型
    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
    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 中的一个重要任务,常见应用包括垃圾邮件检测和情感分析。我们将使用朴素贝叶斯分类器进行文本分类。

    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:股票价格预测

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

    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:新闻分类

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

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

  • 相关阅读:
    QT CmakeLists配置python
    基于STM32F103ZET6库函数独立看门狗(IWDG)实验
    vue.config 同时配置 chainWebpack和关闭eslint检查多个配置项目共存
    【Linux】进程间通信 -- 管道
    把握现在,热爱生活
    Cpp浅析系列-STL之priority_queue
    第八章 接口
    SIP会话发起协议 - 先知道是什么(一)
    window mysql-8.0.34 zip解压包安装
    Bean作用域和生命周期-------JavaEE(Spring)
  • 原文地址:https://blog.csdn.net/weixin_36755535/article/details/139346266