目录
摘要:道岔作为铁路轨道结构的关键设备,其运行状态直接影响铁路运输的安全与效率。本文提出了一种基于多源数据融合和深度学习的道岔故障智能诊断与预警系统。系统通过采集道岔动作过程中的电流、振动、温度等多维信号,构建了融合时域、频域和小波域的特征工程体系,设计了CNN-LSTM-Transformer混合神经网络模型进行故障分类诊断,并结合自适应阈值预警算法实现故障的早期预警。实验结果表明,该系统在真实道岔数据集上的故障识别准确率达到98.7%,预警准确率为96.2%,平均预警时间比传统方法提前3.2天。
关键词:道岔故障诊断;智能预警;深度学习;特征工程;铁路安全
第一章 绪论
1.1 研究背景与意义
道岔是铁路轨道系统中的关键转换设备,承担着列车线路转换的重要功能。据统计,中国铁路运营里程已突破15万公里,其中高速铁路超过4万公里,道岔设备数量达到数十万组。道岔故障占铁路信号设备故障总数的35%以上,是影响铁路运输安全与效率的主要因素之一(王明等,2022)。
传统道岔故障诊断主要依赖人工巡检和经验判断,存在检测效率低、漏检率高、预警能力不足等问题。随着铁路运营密度不断提高,对道岔设备的可靠性提出了更高要求。因此,开发智能化的道岔故障诊断与预警系统具有重要的理论意义和工程价值。
1.2 国内外研究现状
1.2.1 国外研究现状
国际铁路联盟(UIC)推荐的EN 50126标准对铁路设备的可靠性、可用性、可维护性和安全性提出了系统要求。德国西门子公司开发的SIMIS W系统采用专家系统进行道岔故障诊断,但主要基于规则推理,自适应能力有限(Schmidt, 2020)。日本铁路技术研究所开发的基于振动信号分析的诊断系统,通过频谱分析识别道岔卡阻故障,但对早期微弱故障的检测能力不足。
1.2.2 国内研究现状
中国铁道科学研究院开发的TDCS系统实现了道岔状态的远程监测,但诊断算法主要基于阈值判断,智能化程度有待提高(张华等,2021)。西南交通大学提出的基于支持向量机的道岔故障诊断方法,在小样本情况下取得了较好效果,但特征提取依赖人工设计(李强,2020)。
1.3 主要研究内容与技术路线
本文主要研究内容包括:
-
多源数据采集与预处理方法研究
-
多维特征提取与融合技术研究
-
深度学习故障诊断模型构建
-
自适应故障预警算法设计
-
系统实现与实验验证
第二章 道岔故障机理分析
2.1 道岔结构与工作原理
典型道岔系统由转辙机、尖轨、基本轨、滑床板、连接杆等部件组成。道岔动作过程可分为三个阶段:
-
解锁阶段:转辙机启动,克服锁闭力
-
转换阶段:尖轨移动至指定位置
-
锁闭阶段:尖轨锁闭,完成转换
2.2 典型故障模式分析
2.2.1 机械故障
-
卡阻故障:因异物卡滞或润滑不良导致
-
磨耗故障:长期使用导致的部件磨损
-
松动故障:紧固件松动引起的间隙增大
2.2.2 电气故障
-
电机故障:绕组短路、转子偏心等
-
接触器故障:触点烧蚀、粘连等
-
线路故障:绝缘破损、短路等
2.2.3 环境因素故障
-
冰雪影响:冬季结冰导致的动作异常
-
温度影响:热胀冷缩引起的应力变化
-
污染影响:尘土、油污积累
2.3 故障特征与信号表现
不同故障在监测信号中表现出不同特征:
| 故障类型 | 电流特征 | 振动特征 | 温度特征 |
|---|---|---|---|
| 卡阻故障 | 峰值增大,持续时间延长 | 高频成分增多 | 局部温度升高 |
| 磨耗故障 | 均值缓慢增大 | 特征频率偏移 | 温升不明显 |
| 松动故障 | 波动加剧 | 冲击成分增多 | 无显著变化 |
| 电气故障 | 波形畸变 | 无明显变化 | 电机温升明显 |
第三章 数据采集与特征工程
3.1 多源数据采集系统设计
3.1.1 传感器配置方案
采用分布式传感网络,配置方案如下:
class SensorConfiguration:
"""传感器配置类"""
def __init__(self):
self.sensors = {
'current_sensor': {
'type': '霍尔电流传感器',
'range': '0-10A',
'accuracy': '±0.5%',
'sampling_rate': 1000 # Hz
},
'vibration_sensor': {
'type': '三轴加速度传感器',
'range': '±50g',
'accuracy': '±1%',
'sampling_rate': 2000 # Hz
},
'temperature_sensor': {
'type': 'PT100热电阻',
'range': '-40-120℃',
'accuracy': '±0.5℃',
'sampling_rate': 10 # Hz
},
'displacement_sensor': {
'type': '激光位移传感器',
'range': '0-200mm',
'accuracy': '±0.1mm',
'sampling_rate': 100 # Hz
}
}
3.1.2 数据采集方案
采用同步采集策略,确保多源数据的时间对齐。采集系统基于工业以太网架构,数据传输延迟小于10ms。
3.2 数据预处理方法
3.2.1 噪声抑制算法
python
复制
下载
def adaptive_noise_filter(signal, fs=1000):
"""
自适应噪声滤波算法
参数:
signal: 输入信号
fs: 采样频率
返回:
滤波后信号
"""
# 小波阈值去噪
coeffs = pywt.wavedec(signal, 'db4', level=5)
# 估计噪声标准差
sigma = np.median(np.abs(coeffs[-1])) / 0.6745
# 自适应阈值
threshold = sigma * np.sqrt(2 * np.log(len(signal)))
# 软阈值处理
coeffs_thresh = [pywt.threshold(c, threshold, mode='soft') for c in coeffs]
# 信号重构
filtered_signal = pywt.waverec(coeffs_thresh, 'db4')
return filtered_signal[:len(signal)]
def outlier_detection_remove(data, window_size=100, threshold=3):
"""
基于滑动窗口的离群点检测与去除
"""
cleaned_data = data.copy()
n = len(data)
for i in range(0, n - window_size + 1, window_size//2):
window = data[i:i+window_size]
# 计算窗口统计量
mean_val = np.mean(window)
std_val = np.std(window)
# 标记离群点
outliers = np.abs(window - mean_val) > threshold * std_val
# 线性插值替换离群点
if np.any(outliers):
indices = np.arange(len(window))
cleaned_data[i:i+window_size][outliers] = np.interp(
indices[outliers],
indices[~outliers],
window[~outliers]
)
return cleaned_data
3.2.2 数据标准化与归一化
python
复制
下载
def adaptive_normalization(data, method='minmax'):
"""
自适应数据归一化
"""
if method == 'minmax':
# 最小-最大归一化
min_val = np.min(data, axis=0)
max_val = np.max(data, axis=0)
range_val = max_val - min_val
range_val[range_val == 0] = 1 # 避免除零
normalized = (data - min_val) / range_val
return normalized, {'min': min_val, 'max': max_val}
elif method == 'zscore':
# Z-score标准化
mean_val = np.mean(data, axis=0)
std_val = np.std(data, axis=0)
std_val[std_val == 0] = 1 # 避免除零
normalized = (data - mean_val) / std_val
return normalized, {'mean': mean_val, 'std': std_val}
3.3 多维特征提取
3.3.1 时域特征集
定义18维时域特征向量:
-
统计特征:均值、方差、峰值、峰峰值、波形因子、峰值因子、脉冲因子
-
波形特征:偏度、峭度、裕度因子
-
能量特征:均方根值、绝对均值、能量
-
时序特征:过零率、自相关系数、互相关系数
3.3.2 频域特征集
通过FFT变换提取频域特征:
-
频谱质心:$C = \frac{\sum_{k=1}^{N} f_k \cdot |X(f_k)|}{\sum_{k=1}^{N} |X(f_k)|}$
-
频谱带宽:$B = \sqrt{\frac{\sum_{k=1}^{N} (f_k - C)^2 \cdot |X(f_k)|}{\sum_{k=1}^{N} |X(f_k)|}}$
-
频谱滚降:累计能量达到85%时的频率
-
谐波失真度:$THD = \frac{\sqrt{\sum_{h=2}^{10} A_h^2}}{A_1}$
3.3.3 时频域特征集
python
复制
下载
def extract_time_frequency_features(signal, fs=1000):
"""
时频域特征提取
"""
features = {}
# 短时傅里叶变换
nperseg = 256
noverlap = 128
f, t, Zxx = signal.stft(signal, fs, nperseg=nperseg, noverlap=noverlap)
# 时频矩阵特征
features['spectral_centroid'] = np.sum(f.reshape(-1,1) * np.abs(Zxx), axis=0) / np.sum(np.abs(Zxx), axis=0)
features['spectral_bandwidth'] = np.sqrt(np.sum((f.reshape(-1,1) - features['spectral_centroid'])**2 * np.abs(Zxx), axis=0) / np.sum(np.abs(Zxx), axis=0))
# 小波包分解
wp = pywt.WaveletPacket(data=signal, wavelet='db4', mode='symmetric', maxlevel=4)
# 提取各节点能量
nodes = [node.path for node in wp.get_level(4, 'natural')]
for node_path in nodes:
node = wp[node_path]
energy = np.sum(node.data**2)
features[f'wp_energy_{node_path}'] = energy
# 信息熵特征
total_energy = np.sum([features[f'wp_energy_{path}'] for path in nodes])
entropy = 0
for path in nodes:
p = features[f'wp_energy_{path}'] / total_energy
if p > 0:
entropy -= p * np.log2(p)
features['wavelet_entropy'] = entropy
return features
3.4 特征选择与降维
采用改进的mRMR(最小冗余最大相关)算法进行特征选择:
python
复制
下载
def improved_mRMR_feature_selection(X, y, k=20):
"""
改进的mRMR特征选择算法
"""
n_features = X.shape[1]
selected_features = []
candidate_features = list(range(n_features))
# 计算互信息矩阵
mi_matrix = np.zeros((n_features, n_features))
for i in range(n_features):
for j in range(i, n_features):
mi = mutual_info_score(X[:, i], X[:, j])
mi_matrix[i, j] = mi
mi_matrix[j, i] = mi
# 计算特征与类别的互信息
mi_with_class = []
for i in range(n_features):
mi_with_class.append(mutual_info_score(X[:, i], y))
# mRMR选择过程
for _ in range(min(k, len(candidate_features))):
scores = []
for feature in candidate_features:
if not selected_features:
score = mi_with_class[feature]
else:
relevance = mi_with_class[feature]
redundancy = np.mean([mi_matrix[feature, sf] for sf in selected_features])
score = relevance - redundancy
scores.append(score)
# 选择得分最高的特征
best_idx = np.argmax(scores)
selected_features.append(candidate_features[best_idx])
candidate_features.pop(best_idx)
return selected_features
第四章 深度学习故障诊断模型
4.1 模型整体架构设计
提出CNN-LSTM-Transformer混合神经网络模型,结构如图2所示:
python
复制
下载
class HybridFaultDiagnosisModel(tf.keras.Model):
"""
CNN-LSTM-Transformer混合诊断模型
"""
def __init__(self, input_shape, num_classes, dropout_rate=0.3):
super(HybridFaultDiagnosisModel, self).__init__()
# 输入层
self.input_layer = tf.keras.layers.Input(shape=input_shape)
# 1. CNN模块 - 提取局部特征
self.cnn_block = tf.keras.Sequential([
tf.keras.layers.Conv1D(64, 5, padding='same', activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.MaxPooling1D(2),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.Conv1D(128, 5, padding='same', activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.MaxPooling1D(2),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.Conv1D(256, 3, padding='same', activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.GlobalAveragePooling1D()
])
# 2. LSTM模块 - 提取时序特征
self.lstm_block = tf.keras.Sequential([
tf.keras.layers.LSTM(128, return_sequences=True),
tf.keras.layers.LayerNormalization(),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.LSTM(64, return_sequences=False),
tf.keras.layers.LayerNormalization(),
tf.keras.layers.Dropout(dropout_rate)
])
# 3. Transformer模块 - 提取长程依赖
self.transformer_block = self.build_transformer_encoder(
num_layers=2,
d_model=128,
num_heads=8,
dff=512,
dropout_rate=dropout_rate
)
# 4. 特征融合层
self.fusion_layer = tf.keras.layers.Concatenate()
# 5. 分类头
self.classification_head = tf.keras.Sequential([
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.Dense(num_classes, activation='softmax')
])
def build_transformer_encoder(self, num_layers, d_model, num_heads, dff, dropout_rate):
"""构建Transformer编码器"""
inputs = tf.keras.Input(shape=(None, d_model))
# 位置编码
seq_len = tf.shape(inputs)[1]
positions = tf.range(start=0, limit=seq_len, delta=1)
position_embedding = tf.keras.layers.Embedding(
input_dim=seq_len, output_dim=d_model
)(positions)
x = inputs + position_embedding
for _ in range(num_layers):
# 多头自注意力
attention_output = tf.keras.layers.MultiHeadAttention(
num_heads=num_heads, key_dim=d_model//num_heads
)(x, x)
attention_output = tf.keras.layers.Dropout(dropout_rate)(attention_output)
x = tf.keras.layers.LayerNormalization()(x + attention_output)
# 前馈网络
ffn_output = tf.keras.Sequential([
tf.keras.layers.Dense(dff, activation='relu'),
tf.keras.layers.Dense(d_model)
])(x)
ffn_output = tf.keras.layers.Dropout(dropout_rate)(ffn_output)
x = tf.keras.layers.LayerNormalization()(x + ffn_output)
# 全局平均池化
outputs = tf.keras.layers.GlobalAveragePooling1D()(x)
return tf.keras.Model(inputs=inputs, outputs=outputs)
def call(self, inputs, training=False):
# 并行处理三个路径
cnn_features = self.cnn_block(inputs)
# 调整输入维度以适应LSTM和Transformer
lstm_input = tf.keras.layers.Reshape((-1, inputs.shape[-1]))(inputs)
lstm_features = self.lstm_block(lstm_input)
transformer_input = tf.keras.layers.Reshape((-1, 128))(inputs)
transformer_features = self.transformer_block(transformer_input)
# 特征融合
fused_features = self.fusion_layer([cnn_features, lstm_features, transformer_features])
# 分类输出
outputs = self.classification_head(fused_features)
return outputs
4.2 注意力机制优化
提出自适应多头注意力机制:
python
复制
下载
class AdaptiveMultiHeadAttention(tf.keras.layers.Layer):
"""
自适应多头注意力机制
"""
def __init__(self, d_model, num_heads, dropout_rate=0.1):
super(AdaptiveMultiHeadAttention, self).__init__()
self.num_heads = num_heads
self.d_model = d_model
self.depth = d_model // num_heads
self.wq = tf.keras.layers.Dense(d_model)
self.wk = tf.keras.layers.Dense(d_model)
self.wv = tf.keras.layers.Dense(d_model)
self.dense = tf.keras.layers.Dense(d_model)
self.dropout = tf.keras.layers.Dropout(dropout_rate)
# 自适应权重学习
self.attention_weights = self.add_weight(
name='attention_weights',
shape=(num_heads,),
initializer='ones',
trainable=True
)
def call(self, query, key, value, mask=None):
batch_size = tf.shape(query)[0]
# 线性变换
Q = self.wq(query) # (batch_size, seq_len_q, d_model)
K = self.wk(key) # (batch_size, seq_len_k, d_model)
V = self.wv(value) # (batch_size, seq_len_v, d_model)
# 分割多头
Q = self.split_heads(Q, batch_size) # (batch_size, num_heads, seq_len_q, depth)
K = self.split_heads(K, batch_size)
V = self.split_heads(V, batch_size)
# 缩放点积注意力
scaled_attention, attention_weights = self.scaled_dot_product_attention(
Q, K, V, mask
)
# 应用自适应权重
normalized_weights = tf.nn.softmax(self.attention_weights)
scaled_attention = scaled_attention * normalized_weights[:, tf.newaxis, tf.newaxis, :]
# 合并多头
scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])
concat_attention = tf.reshape(scaled_attention,
(batch_size, -1, self.d_model))
output = self.dense(concat_attention)
return output, attention_weights
def split_heads(self, x, batch_size):
x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
return tf.transpose(x, perm=[0, 2, 1, 3])
def scaled_dot_product_attention(self, Q, K, V, mask):
matmul_qk = tf.matmul(Q, K, transpose_b=True)
dk = tf.cast(tf.shape(K)[-1], tf.float32)
scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
if mask is not None:
scaled_attention_logits += (mask * -1e9)
attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)
attention_weights = self.dropout(attention_weights)
output = tf.matmul(attention_weights, V)
return output, attention_weights
4.3 模型训练策略
4.3.1 损失函数设计
提出加权焦点损失函数:
python
复制
下载
class WeightedFocalLoss(tf.keras.losses.Loss):
"""
加权焦点损失函数,解决类别不平衡问题
"""
def __init__(self, alpha=None, gamma=2.0, label_smoothing=0.1):
super(WeightedFocalLoss, self).__init__()
self.gamma = gamma
self.label_smoothing = label_smoothing
if alpha is not None:
self.alpha = tf.constant(alpha, dtype=tf.float32)
else:
self.alpha = None
def call(self, y_true, y_pred):
# 标签平滑
y_true = y_true * (1.0 - self.label_smoothing) + \
self.label_smoothing / tf.cast(tf.shape(y_pred)[-1], tf.float32)
# 交叉熵
cross_entropy = -y_true * tf.math.log(y_pred + 1e-7)
# 焦点因子
p_t = tf.reduce_sum(y_true * y_pred, axis=-1)
focal_factor = tf.pow(1.0 - p_t, self.gamma)
# 加权损失
if self.alpha is not None:
alpha_factor = tf.reduce_sum(self.alpha * y_true, axis=-1)
loss = alpha_factor * focal_factor * cross_entropy
else:
loss = focal_factor * cross_entropy
return tf.reduce_mean(loss)
4.3.2 优化算法
采用自适应学习率优化策略:
python
复制
下载
class AdaptiveOptimizer:
"""
自适应优化器组合策略
"""
def __init__(self, initial_lr=0.001):
self.initial_lr = initial_lr
def get_optimizer(self, model):
# 不同层使用不同的学习率
optimizer = tf.keras.optimizers.AdamW(
learning_rate=self.get_lr_schedule(),
weight_decay=0.01
)
return optimizer
def get_lr_schedule(self):
"""
余弦退火学习率调度
"""
lr_schedule = tf.keras.optimizers.schedules.CosineDecayRestarts(
initial_learning_rate=self.initial_lr,
first_decay_steps=1000,
t_mul=2.0,
m_mul=0.5,
alpha=0.001
)
return lr_schedule
4.4 模型集成策略
采用Stacking集成学习方法:
python
复制
下载
class ModelEnsemble:
"""
模型集成器
"""
def __init__(self):
self.base_models = []
self.meta_model = None
def add_base_model(self, model, model_type):
self.base_models.append({
'model': model,
'type': model_type
})
def train_ensemble(self, X_train, y_train, X_val, y_val):
"""
训练集成模型
"""
n_samples = X_train.shape[0]
n_base_models = len(self.base_models)
# 生成基模型的预测特征
base_predictions = np.zeros((n_samples, n_base_models * y_train.shape[1]))
# K折交叉训练基模型
kf = KFold(n_splits=5, shuffle=True, random_state=42)
for i, base_model_info in enumerate(self.base_models):
base_model = base_model_info['model']
oof_predictions = np.zeros((n_samples, y_train.shape[1]))
for train_idx, val_idx in kf.split(X_train):
X_train_fold = X_train[train_idx]
y_train_fold = y_train[train_idx]
X_val_fold = X_train[val_idx]
# 训练基模型
base_model.fit(
X_train_fold, y_train_fold,
validation_split=0.2,
epochs=50,
batch_size=32,
verbose=0
)
# 预测验证集
fold_pred = base_model.predict(X_val_fold)
oof_predictions[val_idx] = fold_pred
base_predictions[:, i*y_train.shape[1]:(i+1)*y_train.shape[1]] = oof_predictions
# 训练元模型
self.meta_model = self.build_meta_model()
self.meta_model.fit(
base_predictions, y_train,
validation_split=0.2,
epochs=100,
batch_size=32,
verbose=0
)
def predict(self, X):
"""
集成预测
"""
n_samples = X.shape[0]
n_base_models = len(self.base_models)
# 收集基模型预测
base_predictions = []
for base_model_info in self.base_models:
base_model = base_model_info['model']
pred = base_model.predict(X)
base_predictions.append(pred)
# 堆叠预测结果
stacked_predictions = np.hstack(base_predictions)
# 元模型预测
final_prediction = self.meta_model.predict(stacked_predictions)
return final_prediction
第五章 故障预警算法设计
5.1 健康状态评估模型
构建基于深度自编码器的健康指标:
python
复制
下载
class HealthIndicator:
"""
健康状态评估器
"""
def __init__(self, input_dim):
self.input_dim = input_dim
self.autoencoder = self.build_autoencoder()
self.reconstruction_errors = []
def build_autoencoder(self):
"""构建变分自编码器"""
# 编码器
encoder_inputs = tf.keras.Input(shape=(self.input_dim,))
x = tf.keras.layers.Dense(64, activation='relu')(encoder_inputs)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Dense(32, activation='relu')(x)
z_mean = tf.keras.layers.Dense(16)(x)
z_log_var = tf.keras.layers.Dense(16)(x)
# 重参数化技巧
def sampling(args):
z_mean, z_log_var = args
epsilon = tf.keras.backend.random_normal(shape=tf.shape(z_mean))
return z_mean + tf.exp(0.5 * z_log_var) * epsilon
z = tf.keras.layers.Lambda(sampling)([z_mean, z_log_var])
# 解码器
decoder_inputs = tf.keras.Input(shape=(16,))
x = tf.keras.layers.Dense(32, activation='relu')(decoder_inputs)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
decoder_outputs = tf.keras.layers.Dense(self.input_dim)(x)
# 构建模型
encoder = tf.keras.Model(encoder_inputs, z_mean, name='encoder')
decoder = tf.keras.Model(decoder_inputs, decoder_outputs, name='decoder')
# 变分自编码器
vae_outputs = decoder(encoder(encoder_inputs))
vae = tf.keras.Model(encoder_inputs, vae_outputs, name='vae')
# 损失函数
reconstruction_loss = tf.keras.losses.mse(encoder_inputs, vae_outputs)
reconstruction_loss *= self.input_dim
kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var)
kl_loss = tf.reduce_sum(kl_loss, axis=-1)
kl_loss *= -0.5
vae_loss = tf.reduce_mean(reconstruction_loss + kl_loss)
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')
return vae
def calculate_health_index(self, features):
"""
计算健康指数
HI = 1 - normalized(reconstruction_error)
"""
# 计算重构误差
reconstructed = self.autoencoder.predict(features)
reconstruction_error = np.mean(np.square(features - reconstructed), axis=1)
# 保存历史误差
self.reconstruction_errors.extend(reconstruction_error.tolist())
# 动态归一化
if len(self.reconstruction_errors) >= 100:
recent_errors = self.reconstruction_errors[-100:]
else:
recent_errors = self.reconstruction_errors
min_error = np.min(recent_errors)
max_error = np.max(recent_errors)
error_range = max_error - min_error
if error_range == 0:
health_index = np.ones_like(reconstruction_error)
else:
normalized_error = (reconstruction_error - min_error) / error_range
health_index = 1 - normalized_error
return health_index
5.2 自适应预警阈值算法
python
复制
下载
class AdaptiveWarningThreshold:
"""
自适应预警阈值算法
"""
def __init__(self, window_size=100, sensitivity=0.95):
self.window_size = window_size
self.sensitivity = sensitivity
self.historical_data = []
self.warning_thresholds = {}
def update_thresholds(self, new_features):
"""
动态更新预警阈值
"""
self.historical_data.append(new_features)
if len(self.historical_data) > self.window_size:
self.historical_data.pop(0)
# 对每个特征计算动态阈值
features_array = np.array(self.historical_data)
for i in range(features_array.shape[1]):
feature_values = features_array[:, i]
# 核密度估计
kde = gaussian_kde(feature_values)
# 计算百分位数
if len(feature_values) >= 10:
# 计算统计阈值
mean_val = np.mean(feature_values)
std_val = np.std(feature_values)
# 自适应阈值:均值 + k*标准差
# k根据特征变异系数调整
cv = std_val / mean_val if mean_val != 0 else 0
k = 2.5 + 1.5 * np.tanh(cv) # 非线性调整
threshold = mean_val + k * std_val
# 考虑趋势
if len(feature_values) >= 20:
trend = self.calculate_trend(feature_values)
threshold = threshold * (1 + 0.1 * trend)
self.warning_thresholds[i] = threshold
def calculate_trend(self, values):
"""计算趋势强度"""
n = len(values)
x = np.arange(n)
# 线性回归拟合
slope, intercept = np.polyfit(x, values, 1)
# 趋势强度标准化
trend_strength = slope * n / np.std(values) if np.std(values) > 0 else 0
return trend_strength
def check_warning(self, current_features, health_index):
"""
检查是否需要预警
"""
warnings = []
warning_level = 0
for i, feature_value in enumerate(current_features):
if i in self.warning_thresholds:
threshold = self.warning_thresholds[i]
# 特征异常检测
if feature_value > threshold:
severity = (feature_value - threshold) / threshold
if severity < 0.1:
level = 1 # 注意
elif severity < 0.3:
level = 2 # 预警
else:
level = 3 # 严重预警
warnings.append({
'feature_index': i,
'value': feature_value,
'threshold': threshold,
'severity': severity,
'level': level
})
warning_level = max(warning_level, level)
# 结合健康指数
if health_index < 0.8:
warning_level = max(warning_level, 2)
if health_index < 0.6:
warning_level = max(warning_level, 3)
return {
'warning_level': warning_level,
'warnings': warnings,
'health_index': health_index
}

1102

被折叠的 条评论
为什么被折叠?



