我正在做一个桥梁温致挠度去除与预测的算法,在主要方案不变的情况下,为了在实际应用中表现优异,请改进以下代码(尤其是自适应选择参数,如EMD中心频率阈值与滑动窗口大小)import…
- User
我正在做一个桥梁温致挠度去除与预测的算法,在主要方案不变的情况下,为了在实际应用中表现优异,请改进以下代码(尤其是自适应选择参数,如EMD中心频率阈值与滑动窗口大小)import os import json import pandas as pd import numpy as np import matplotlib.pyplot as plt from PyEMD import EMD from sklearn.ensemble import IsolationForest from scipy.signal import savgol_filter from scipy.fft import fft, fftfreq from sklearn.metrics import mean_squared_error import warnings
忽略不必要的警告
warnings.filterwarnings("ignore")
解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用黑体显示中文 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
参数文件路径
PARAM_FILE = 'best_params.json'
def calculate_dominant_frequency(imf, sampling_rate): """ 计算IMF的主频率 :param imf: 一维信号 :param sampling_rate: 采样率(Hz) :return: 主频率(Hz) """ N = len(imf) yf = fft(imf) xf = fftfreq(N, d=1/sampling_rate)
# 只考虑正频率部分 positive_freqs = xf[:N//2] positive_yf = np.abs(yf[:N//2]) if len(positive_yf) == 0: return 0.0 # 找到主频率 idx = np.argmax(positive_yf) dominant_freq = positive_freqs[idx] return dominant_freqdef emd_spectral_decomposition(signal, time_seconds, frequency_threshold=None): """ 使用EMD分解并通过频谱分析自动去除低频IMF :param signal: 一维信号 :param time_seconds: 时间序列,单位为秒 :param frequency_threshold: 频率阈值,低于该值的IMF将被去除。如果为None,则自动确定 :return: 去除低频IMF后的信号, 低频IMF编号列表, 所有IMF, frequency_threshold """ emd = EMD() IMFs = emd.emd(S=signal, T=time_seconds) num_IMFs = IMFs.shape[0] print(f"分解得到的IMF数量: {num_IMFs}")
# 估计采样率 time_deltas = np.diff(time_seconds) avg_time_delta = np.mean(time_deltas) if avg_time_delta == 0: raise ValueError("时间序列的平均时间间隔为0,无法计算采样率。") sampling_rate = 1 / avg_time_delta print(f"估计采样率: {sampling_rate:.4f} Hz") # 计算每个IMF的主频率 dominant_freqs = [] for i, imf in enumerate(IMFs): dom_freq = calculate_dominant_frequency(imf, sampling_rate) dominant_freqs.append(dom_freq) print(f"IMF {i+1}: 主频率 = {dom_freq:.4f} Hz") # 如果未指定频率阈值,则自动确定(例如,使用主频率的中位数) if frequency_threshold is None: frequency_threshold = np.median(dominant_freqs) print(f"自动确定的频率阈值为IMF主频率的中位数: {frequency_threshold:.4f} Hz") # 选择低频IMF low_freq_IMF_indices = [i for i, freq in enumerate(dominant_freqs) if freq < frequency_threshold] print(f"需要去除的低频IMF编号: {low_freq_IMF_indices}") # 去除低频IMF if low_freq_IMF_indices: removed_signal = np.sum(IMFs[low_freq_IMF_indices, :], axis=0) cleaned_signal = signal - removed_signal else: cleaned_signal = signal return cleaned_signal, low_freq_IMF_indices, IMFs, frequency_thresholddef moving_average_forecast(series, window_size): """移动平均预测""" forecast = [] for t in range(len(series) - window_size + 1): forecast.append(series[t:t + window_size].mean()) return np.array(forecast)
def plot_imfs(time, IMFs, low_freq_indices): """ 绘制所有IMF,并标注低频IMF :param time: 时间序列 :param IMFs: 所有IMF :param low_freq_indices: 低频IMF的索引列表 """ num_IMFs = IMFs.shape[0] plt.figure(figsize=(12, 3*num_IMFs))
for i in range(num_IMFs): plt.subplot(num_IMFs, 1, i + 1) plt.plot(time, IMFs[i], label=f'IMF {i+1}', color='b' if i not in low_freq_indices else 'r') if i in low_freq_indices: plt.legend(loc='upper right') plt.title(f'IMF {i+1} (低频, 温度影响)') else: plt.legend(loc='upper right') plt.title(f'IMF {i+1}') plt.xlabel('时间') plt.ylabel('挠度') plt.tight_layout() plt.show() - Assistant
为了提高桥梁温致挠度去除与预测算法的实际应用表现,您可以对代码进行以下改进,尤其是在自适应选择参数方面:
-
自适应的EMD中心频率阈值:使用数据驱动方法来确定EMD中低频IMF的频率阈值。可以使用如小波变换得到频谱密集区,从而调整阈值。
-
动态滑动窗口大小:根据数据的特性,如信号的自相关性,动态调整滑动窗口的大小。使用蒙特卡罗方法或者交叉验证来估计最佳窗口大小。
-
增加异常处理鲁棒性:结合多种异常检测算法(如LOF、DBSCAN)来提高对噪音和异常值处理的准确性。
以下是改进代码的关键部分:
from scipy.signal import find_peaks def adaptive_frequency_threshold(dominant_freqs): """ 自适应地确定频率阈值,使用直方图密集区域分析 """ # 使用KDE或直方图的密集区域 hist, bin_edges = np.histogram(dominant_freqs, bins='auto', density=True) threshold_idx = np.argmax(hist) frequency_threshold = (bin_edges[threshold_idx] + bin_edges[threshold_idx + 1]) / 2 return frequency_threshold def dynamic_window_size(cleaned_signal): """ 动态调整滑动窗口大小,考虑信号自相关性 """ # 计算自相关 autocorrelation = np.correlate(cleaned_signal, cleaned_signal, mode='full') autocorrelation = autocorrelation[autocorrelation.size // 2:] # 选择一个减少50%自动相关性的点作为窗口大小 half_max = autocorrelation[0] * 0.5 peaks, _ = find_peaks(-autocorrelation, height=-half_max) if len(peaks) > 0: window_size = peaks[0] else: window_size = min(24, len(cleaned_signal) // 2) return max(12, window_size) -
- User
写出改进后的完整代码
- Assistant
- User
(test) PS D:\kurzcraft\PycharmProjects\mid_span_deflection_trend_analysis> & D:/kurzcraft/anaconda3/envs/test/python.exe d:/kurzcraft/PycharmProjects/mid_span_deflection_trend_analysis/VMD分解移动平均预测.py
请选择操作模式:
- 自适应选择参数 (自动参数优化)
- 使用上次的参数
- 退出 请输入选项 (1/2/3): 1
您选择了自适应选择参数 (自动参数优化)。 Excel文件读取成功。 数据总行数: 83557 列名: ['时间', '挠度', '温度'] 自动估计的异常比例(contamination): 0.0100 检测到的异常值数量: 822 分解得到的IMF数量: 5 估计采样率: 0.9576 Hz IMF 1: 主频率 = 0.0000 Hz IMF 2: 主频率 = 0.0339 Hz IMF 3: 主频率 = 0.0526 Hz IMF 4: 主频率 = 0.2846 Hz IMF 5: 主频率 = 0.3790 Hz 自动确定的频率阈值为: 0.0474 Hz 需要去除的低频IMF编号: [0, 1] VMD分解过程中出错: operands could not be broadcast together with shapes (82735,) (82734,)
- Assistant
在代码的执行过程中,您遇到了一个广播错误,这通常与数组的长度不匹配有关。这个错误可能是由于在去除低频IMF时,信号的大小不匹配,导致了数组操作问题。这里我们可以检查和修正信号长度来解决此问题。
首先,确认所有IMF和信号的长度是一致的。我们可以在
emd_spectral_decomposition函数内进行检查并确保长度匹配。以下是一些可能的步骤,以确保信号和IMF在处理之前大小一致:
def emd_spectral_decomposition(signal, time_seconds, frequency_threshold=None): emd = EMD() IMFs = emd.emd(S=signal, T=time_seconds) # 确保IMFs长度与信号长度一致 if IMFs.shape[1] != len(signal): print(f"警告: IMF长度 {IMFs.shape[1]} 与信号长度 {len(signal)} 不一致,进行截断处理。") min_length = min(IMFs.shape[1], len(signal)) IMFs = IMFs[:, :min_length] signal = signal[:min_length] num_IMFs = IMFs.shape[0] print(f"分解得到的IMF数量: {num_IMFs}") time_deltas = np.diff(time_seconds) avg_time_delta = np.mean(time_deltas) if avg_time_delta == 0: raise ValueError("时间序列的平均时间间隔为0,无法计算采样率。") sampling_rate = 1 / avg_time_delta print(f"估计采样率: {sampling_rate:.4f} Hz") dominant_freqs = [] for i, imf in enumerate(IMFs): dom_freq = calculate_dominant_frequency(imf, sampling_rate) dominant_freqs.append(dom_freq) print(f"IMF {i+1}: 主频率 = {dom_freq:.4f} Hz") if frequency_threshold is None: frequency_threshold = adaptive_frequency_threshold(dominant_freqs) print(f"自动确定的频率阈值为: {frequency_threshold:.4f} Hz") low_freq_IMF_indices = [i for i, freq in enumerate(dominant_freqs) if freq < frequency_threshold] print(f"需要去除的低频IMF编号: {low_freq_IMF_indices}") if low_freq_IMF_indices: removed_signal = np.sum(IMFs[low_freq_IMF_indices, :], axis=0) cleaned_signal = signal - removed_signal else: cleaned_signal = signal return cleaned_signal, low_freq_IMF_indices, IMFs, frequency_threshold