简单的基于深度学习的时间序列异常检测(Python)

184 篇文章 1 订阅
164 篇文章 34 订阅
#importing required libraries


import pandas as pd
import numpy as np
import tensorflow as tf 
import matplotlib.pyplot as plt
from keras.layers import Input, Dense 
from keras.models import Model 
from sklearn.metrics import precision_recall_fscore_support 


#Load data and perform required operations to clean data ready for further processing


data= pd.read_csv('ambient_temperature_system_failure.csv')


#Exclude datatime column
data_values= data.drop('timestamp' , axis=1).values


#convert data to float type
data_values= data_values.astype('float32')


#create new dataframe with converted values 
data_converted= pd.DataFrame(data_values, columns=data.columns[1:])


#Add back datetime column
data_converted.insert(0, 'timestamp', data['timestamp'])


#Remove NAN values from dataset
data_converted= data_converted.dropna()


# Exclude datetime column again 
data_tensor = tf.convert_to_tensor(data_converted.drop('timestamp', axis=1).values, dtype=tf.float32) 
  
# Define the autoencoder model 
input_dim = data_converted.shape[1] - 1 
encoding_dim = 10
  
input_layer = Input(shape=(input_dim,)) 
encoder = Dense(encoding_dim, activation='relu')(input_layer) 
decoder = Dense(input_dim, activation='relu')(encoder) 
autoencoder = Model(inputs=input_layer, outputs=decoder) 
  
# Compile and fit the model 
autoencoder.compile(optimizer='adam', loss='mse') 
autoencoder.fit(data_tensor, data_tensor, epochs=100, batch_size=32, shuffle=True) 
  
# Calculate the reconstruction error for each data point 
reconstructions = autoencoder.predict(data_tensor) 
mse = tf.reduce_mean(tf.square(data_tensor - reconstructions), axis=1) 
anomaly_scores = pd.Series(mse.numpy(), name='anomaly_scores') 
anomaly_scores.index = data_converted.index 


#define anomaly detection threshold & assess the model’s effectiveness using precision
threshold = anomaly_scores.quantile(0.99) 
anomalous = anomaly_scores > threshold 
binary_labels = anomalous.astype(int) 
precision, recall,f1_score, _ = precision_recall_fscore_support(binary_labels, anomalous, average='binary') 


test= data_converted['value'].values
predictions = anomaly_scores.values


print("Precision: " , precision)
print("Recall: " , recall)
print("F1 Score: " , f1_score)


#Visualizing Anomaly results


# Plot the data with anomalies marked in red 
plt.figure(figsize=(8, 8)) 
plt.plot(data_converted['timestamp'], data_converted['value']) 
plt.plot(data_converted['timestamp'][anomalous], data_converted['value'][anomalous], 'ro') 
plt.title('Anomaly Detection') 
plt.xlabel('Time') 
plt.ylabel('Value') 
plt.show()

知乎学术咨询:https://www.zhihu.com/consult/people/792359672131756032?isMe=1

担任《Mechanical System and Signal Processing》等审稿专家,擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
时间序列异常点检测是指通过对时间序列数据进行分析,识别出其中的异常点,即与正常数据波动规律有显著差异的数据点。对于时间序列异常点检测任务,Python提供了多种库和算法。 一种常用的Python库是`statsmodels`,它是一个强大的统计分析库,可以用于时间序列的建模和分析。其中的`outliers_influence`模块提供了许多用于异常点检测的统计方法和函数,例如`OLSInfluence`类可以通过计算残差、杠杆值和学生化残差等指标来检测异常点。 另一个常用的Python库是`pyculiarity`,它是基于R语言遗留的`anomalize`库开发的,用于时间序列异常检测和异常值替换。`pyculiarity`包含了一系列的异常检测算法,例如`esd_test`可以基于指数平滑分解(Exponential Smoothing Decomposition)检测异常点。 此外,还有一些用于时间序列异常点检测的专用库,如`anomaly_detection`和`pyod`。`anomaly_detection`库提供了多种统计和机器学习方法,如基于均值和标准差的Z分数法、基于百分位数的箱线图法和基于自动编码器的深度学习方法等。`pyod`库是一个专门用于异常检测的库,提供了多种经典和先进的异常检测算法,包括基于聚类的LOF算法、基于距离的KNN算法和基于孤立森林(Isolation Forest)的算法等。 总之,Python提供了多种用于时间序列异常点检测的库和算法,可以根据具体需求选择合适的方法进行异常点检测和分析。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哥廷根数学学派

码字不易,且行且珍惜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值