时间序列中的6大类10种异常值处理方法(从根源上提高预测精度)

2023-11-21 22:04

本文主要是介绍时间序列中的6大类10种异常值处理方法(从根源上提高预测精度),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

一、本文介绍

本文介绍的内容是在时间序列中异常值处理的方法,当我进行时间序列分析建模收集数据的过程中,往往都存在着一些特数据情况导致数据中存在着一些异常值,这些异常值往往会导致模型识别到不正常的模式从而无法准确的预测, (我试验过一个数据集清楚之后MAE的精度甚至能提升0.1左右),所以对于异常值的检测和处理对于时间序列来说是十分重要的,本篇文章需要配合我的另一篇文章配合阅读,另一篇文章介绍了如何进行异常值检测所以本文篇文章下面来介绍当我们检测出异常值之后如何进行异常值处理。

前文回顾:时间序列预测:深度学习、机器学习、融合模型、创新模型实战案例

目录

一、本文介绍

 二、异常值处理的方法

三、数据集介绍 

四、异常值处理

4.1 删除法

4.2 替换法 

4.2.1 平均值替换

4.2.2 中位数替换

4.2.3 众数替换

4.2.4 移动平滑替换

4.3 变换法

4.3.1 Box-Cox变化

4.3.2 对数变化

4.4 分箱法 

4.5 使用机器学习模型 

4.6 基于规则的方法 

五、全文总结


 二、异常值处理的方法

处理异常值,主要有以下几种方法:

  1. 删除法:直接删除含有异常值的数据。这种方法简单直接,但可能会丢失其他有用信息。

  2. 替换法

    • 平均值替换:用整个数据集的平均值替换异常值。
    • 中位数替换:用中位数来替换异常值,尤其适用于数据不对称分布的情况。
    • 众数替换:对于分类数据,可以使用众数来替换异常值。
    • 平滑窗口替换:用异常值附近的平均值替换,需要设定一个窗口大小
  3. 变换法

    • 对数变换:适用于右偏数据,可以减少数据的偏斜。
    • Box-Cox变换:一种通用的转换方法,可以处理各种类型的偏态分布。
  4. 分箱法:将数据分成几个区间(箱子),然后用箱子的边界值或中值来替换异常值。

  5. 使用机器学习模型:通过构建模型预测异常值并替换。这种方法通常在数据量较大且复杂时使用。

  6. 基于规则的方法:根据领域知识或特定规则来确定和处理异常值。

总结:选择哪种方法取决于异常值的性质和分析的目标。在某些情况下,结合使用多种方法可能会更有效。例如,可以先通过替换或修正方法处理异常值,然后使用变换或鲁棒性较强的模型进行分析。重要的是要理解异常值的来源和它们对分析结果可能产生的影响,从而做出恰当的处理。

三、数据集介绍 

我们本文用到的数据集是官方的ETTh1.csv ,数据集是一个用于时间序列预测的电力负荷数据集,它是 ETTh 数据集系列中的一个。ETTh 数据集系列通常用于测试和评估时间序列预测模型。以下是 ETTh1.csv 数据集的一些内容:

数据内容:该数据集通常包含有关电力系统的多种变量,如电力负荷、天气情况等。这些变量可以用于预测未来的电力需求或价格。

时间范围和分辨率:数据通常按小时或天记录,涵盖了数月或数年的时间跨度。具体的时间范围和分辨率可能会根据数据集的版本而异。 

以下是该数据集的部分截图->

 

四、异常值处理

4.1 删除法

删除法:直接删除含有异常值的数据。这种方法简单直接,但可能会丢失其他有用信息。

推荐指数:

import pandas as pd
from scipy.stats import zscore
import matplotlib.pyplot as plt# Load the data
file_path = 'ETTh1.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Filter out rows where the Z-Score is greater than 2
outliers_removed = data[data['OT_ZScore'].abs() <= 2]# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the cleaned data in the second subplot
axes[1].plot(outliers_removed['OT'].reset_index(drop=True), label='Data After Removing Outliers', color='green', alpha=0.7)
axes[1].set_title('Cleaned "OT" Data')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

可以明显的看到当我们使用将异常值删除之后我们的数据范围从(40,-5)来到了(30,-5)数据范围变得更窄,起到了一定数据平缓的作用,让数据的波动性变小从而提高模型的预测精度(当然在实际中及其不推荐使用这种方法,因为这会破坏数据的周期性)

 

4.2 替换法 

4.2.1 平均值替换

平均值替换:用整个数据集的平均值替换异常值。

推荐指数:⭐⭐⭐

import pandas as pd
from scipy.stats import zscore
import matplotlib.pyplot as plt# Load the data
file_path = 'ETTh1.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Filter out rows where the Z-Score is greater than 2
outliers_removed = data[data['OT_ZScore'].abs() <= 2]# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the cleaned data in the second subplot
axes[1].plot(outliers_removed['OT'].reset_index(drop=True), label='Mean Value Replacement', color='green', alpha=0.7)
axes[1].set_title('Cleaned "OT" Data')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

可以看到这种方法的效果和上面的删除差多,在实际使用中平均值使用替换可以算做一种保守的方法。 

4.2.2 中位数替换

中位数替换用中位数来替换异常值,尤其适用于数据不对称分布的情况。

推荐指数:⭐⭐⭐⭐

import pandas as pd
from scipy.stats import zscore
import matplotlib.pyplot as plt# Load the data
file_path = 'ETTh1.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Filter out rows where the Z-Score is greater than 2
outliers_removed = data[data['OT_ZScore'].abs() <= 2]# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the cleaned data in the second subplot
axes[1].plot(outliers_removed['OT'].reset_index(drop=True), label='Median Value Replacement', color='green', alpha=0.7)
axes[1].set_title('Cleaned "OT" Data')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

大家由这两张图片可以看出替换法的效果都差不多。 

4.2.3 众数替换

众数替换:对于分类数据,可以使用众数来替换异常值。

推荐指数:⭐⭐⭐⭐

import pandas as pd
from scipy.stats import zscore
import matplotlib.pyplot as plt# Load the data
file_path = 'ETTh1.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Filter out rows where the Z-Score is greater than 2
outliers_removed = data[data['OT_ZScore'].abs() <= 2]# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the cleaned data in the second subplot
axes[1].plot(outliers_removed['OT'].reset_index(drop=True), label='Mode Value Replacement', color='green', alpha=0.7)
axes[1].set_title('Cleaned "OT" Data')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

4.2.4 移动平滑替换

移动平滑替换:用异常值附近的平均值替换,需要设定一个窗口大小

推荐指数:⭐⭐⭐⭐⭐

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import zscore# Load the data
file_path = 'your_file_path_here.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Setting a default window size for rolling mean
window_size = 5# Calculate the rolling mean
rolling_mean = data['OT'].rolling(window=window_size, center=True).mean()# Replace outliers (Z-Score > 2) with the rolling mean
data['OT_RollingMean'] = data.apply(lambda row: rolling_mean[row.name] if abs(row['OT_ZScore']) > 2 else row['OT'], axis=1)# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the data after replacing outliers with rolling mean in the second subplot
axes[1].plot(data['OT_RollingMean'], label='Data After Rolling Mean Replacement', color='green', alpha=0.7)
axes[1].set_title('Data After Rolling Mean Replacement of Outliers')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

 

4.3 变换法

4.3.1 Box-Cox变化

Box-Cox变换一种通用的转换方法,可以处理各种类型的偏态分布。

推荐指数:⭐⭐⭐

大家再用这种方法的时候需要注意数据中不能包含负值

import pandas as pd
from scipy.stats import zscore, boxcox
import matplotlib.pyplot as plt# Load the data
file_path = 'ETTh1.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Filter out rows where the Z-Score is greater than 2
outliers_removed = data[data['OT_ZScore'].abs() <= 2]# Applying Box-Cox transformation
data['OT_BoxCox'], _ = boxcox(data['OT'])# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the Box-Cox transformed data in the second subplot
axes[1].plot(data['OT_BoxCox'], label='Box-Cox Transformed Data', color='green', alpha=0.7)
axes[1].set_title('Box-Cox Transformed "OT" Data')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('Transformed OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

 

4.3.2 对数变化

对数变换适用于右偏数据,可以减少数据的偏斜。

推荐指数:

这个方法同理也不能输入负数,同时这个方法在我们输入到模型之后,输出结果之后还要将结果转换回来,实际是不推荐大家使用的。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt# Load the data
file_path = 'ETTh1.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Replace values in 'OT' column that are less than 0 with the mean of the column
ot_mean = data['OT'].mean()
data['OT'] = data['OT'].apply(lambda x: ot_mean if x < 0 else x)# Applying logarithmic transformation
data['OT_Log'] = np.log(data['OT'])# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the logarithmically transformed data in the second subplot
axes[1].plot(data['OT_Log'], label='Logarithmically Transformed Data', color='green', alpha=0.7)
axes[1].set_title('Logarithmically Transformed "OT" Data')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('Transformed OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

 

 

4.4 分箱法 

分箱法:将数据分成几个区间(箱子),然后用箱子的边界值或中值来替换异常值。

推荐指数:⭐⭐⭐

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import zscore# Load the data
file_path = 'your_file_path_here.csv'  # Replace with your file path
data = pd.read_csv(file_path)# Calculate Z-Scores for the 'OT' column
data['OT_ZScore'] = zscore(data['OT'])# Performing equal-width binning
num_bins = 10
data['OT_Binned'] = pd.cut(data['OT'], bins=num_bins)# Calculating the median of each bin
binned_median = data.groupby('OT_Binned')['OT'].median()# Replacing outliers with the median of the corresponding bin
data['OT_Replaced'] = data['OT'].copy()  # Creating a copy of the 'OT' column for replacements
for bin_interval, median_value in binned_median.items():# Find indices of outliers in this binindices = data[(data['OT_Binned'] == bin_interval) & (data['OT_ZScore'].abs() > 2)].index# Replace these outliers with the median value of the bindata.loc[indices, 'OT_Replaced'] = median_value# Creating a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))# Plotting the original data in the first subplot
axes[0].plot(data['OT'], label='Original Data', color='blue', alpha=0.7)
axes[0].set_title('Original "OT" Data')
axes[0].set_xlabel('Index')
axes[0].set_ylabel('OT Values')
axes[0].grid(True)# Plotting the data after replacing outliers in the second subplot
axes[1].plot(data['OT_Replaced'], label='Data After Replacing Outliers', color='green', alpha=0.7)
axes[1].set_title('Data After Replacing Outliers with Bin Medians')
axes[1].set_xlabel('Index')
axes[1].set_ylabel('OT Values')
axes[1].grid(True)# Adjusting layout and displaying the plot
plt.tight_layout()
plt.show()

 

4.5 使用机器学习模型 

这种方法暂时不给大家介绍了,因为这就是时间序列预测,通过预测值来替换这个值,所以想用这种方法可以看我专栏里的其它内容。 

推荐指数:⭐⭐

 

4.6 基于规则的方法 

这种方法就是需要你有特定的知识,当我们用异常值检测方法检测出异常值之后去手动修改文件,其实这种是最合理的但是需要费时。

推荐指数:⭐⭐⭐⭐

 

五、全文总结

到此本文已经全部讲解完成了,希望能够帮助到大家,在这里也给大家推荐一些我其它的博客的时间序列实战案例讲解,其中有数据分析的讲解就是我前面提到的如何设置参数的分析博客,最后希望大家订阅我的专栏,本专栏均分文章均分98,并且免费阅读。

专栏回顾->时间序列预测专栏——包含上百种时间序列模型带你从入门到精通时间序列预测

这篇关于时间序列中的6大类10种异常值处理方法(从根源上提高预测精度)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/405403

相关文章

使用Python获取JS加载的数据的多种实现方法

《使用Python获取JS加载的数据的多种实现方法》在当今的互联网时代,网页数据的动态加载已经成为一种常见的技术手段,许多现代网站通过JavaScript(JS)动态加载内容,这使得传统的静态网页爬取... 目录引言一、动态 网页与js加载数据的原理二、python爬取JS加载数据的方法(一)分析网络请求1

MySQL查看表的最后一个ID的常见方法

《MySQL查看表的最后一个ID的常见方法》在使用MySQL数据库时,我们经常会遇到需要查看表中最后一个id值的场景,无论是为了调试、数据分析还是其他用途,了解如何快速获取最后一个id都是非常实用的技... 目录背景介绍方法一:使用MAX()函数示例代码解释适用场景方法二:按id降序排序并取第一条示例代码解

Python中合并列表(list)的六种方法小结

《Python中合并列表(list)的六种方法小结》本文主要介绍了Python中合并列表(list)的六种方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录一、直接用 + 合并列表二、用 extend() js方法三、用 zip() 函数交叉合并四、用

Java 中的跨域问题解决方法

《Java中的跨域问题解决方法》跨域问题本质上是浏览器的一种安全机制,与Java本身无关,但Java后端开发者需要理解其来源以便正确解决,下面给大家介绍Java中的跨域问题解决方法,感兴趣的朋友一起... 目录1、Java 中跨域问题的来源1.1. 浏览器同源策略(Same-Origin Policy)1.

Python处理大量Excel文件的十个技巧分享

《Python处理大量Excel文件的十个技巧分享》每天被大量Excel文件折磨的你看过来!这是一份Python程序员整理的实用技巧,不说废话,直接上干货,文章通过代码示例讲解的非常详细,需要的朋友可... 目录一、批量读取多个Excel文件二、选择性读取工作表和列三、自动调整格式和样式四、智能数据清洗五、

Java Stream.reduce()方法操作实际案例讲解

《JavaStream.reduce()方法操作实际案例讲解》reduce是JavaStreamAPI中的一个核心操作,用于将流中的元素组合起来产生单个结果,:本文主要介绍JavaStream.... 目录一、reduce的基本概念1. 什么是reduce操作2. reduce方法的三种形式二、reduce

利用Python实现时间序列动量策略

《利用Python实现时间序列动量策略》时间序列动量策略作为量化交易领域中最为持久且被深入研究的策略类型之一,其核心理念相对简明:对于显示上升趋势的资产建立多头头寸,对于呈现下降趋势的资产建立空头头寸... 目录引言传统策略面临的风险管理挑战波动率调整机制:实现风险标准化策略实施的技术细节波动率调整的战略价

MybatisX快速生成增删改查的方法示例

《MybatisX快速生成增删改查的方法示例》MybatisX是基于IDEA的MyBatis/MyBatis-Plus开发插件,本文主要介绍了MybatisX快速生成增删改查的方法示例,文中通过示例代... 目录1 安装2 基本功能2.1 XML跳转2.2 代码生成2.2.1 生成.xml中的sql语句头2

SpringBoot如何对密码等敏感信息进行脱敏处理

《SpringBoot如何对密码等敏感信息进行脱敏处理》这篇文章主要为大家详细介绍了SpringBoot对密码等敏感信息进行脱敏处理的几个常用方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录​1. 配置文件敏感信息脱敏​​2. 日志脱敏​​3. API响应脱敏​​4. 其他注意事项​​总结

Python使用python-docx实现自动化处理Word文档

《Python使用python-docx实现自动化处理Word文档》这篇文章主要为大家展示了Python如何通过代码实现段落样式复制,HTML表格转Word表格以及动态生成可定制化模板的功能,感兴趣的... 目录一、引言二、核心功能模块解析1. 段落样式与图片复制2. html表格转Word表格3. 模板生