为了帮助您解决IMF绘图时出现的时间序列与IMF长度不匹配问题,我们需要确保分解后的IMFs形状与时间序列的长度一致。我将在代码中添加一些调试输出,并调整代码以确保IMFs和时间序列长度匹配。以下是改进后的代码:
python Copy code
import os
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
from scipy.signal import savgol_filter, find_peaks
from scipy.fft import fft, fftfreq
from sklearn.metrics import mean_squared_error
from vmdpy import VMD
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):
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_freq
def vmd_spectral_decomposition(signal, time_seconds, alpha=2000, tau=0, K=5, DC=0, init=1):
fs = 1 / np.mean(np.diff(time_seconds))
imfs, u_hat, omega = VMD(signal, alpha, tau, K, DC, init, fs)
num_IMFs = imfs.shape[0]
print(f"分解得到的IMF数量: {num_IMFs}")
sampling_rate = fs
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")
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}")
removed_signal = np.sum(imfs[low_freq_IMF_indices, :], axis=0)
# 确保 removed_signal 和 signal 的长度相同
if len(signal) > len(removed_signal):
removed_signal = np.pad(removed_signal, (0, len(signal) - len(removed_signal)), mode='edge')
cleaned_signal = signal - removed_signal
# 打印信号长度确认它们匹配
print(f"Original signal length: {len(signal)}")
print(f"Removed signal length: {len(removed_signal)}")
print(f"Cleaned signal length: {len(cleaned_signal)}")
return cleaned_signal, low_freq_IMF_indices, imfs, frequency_threshold
def adaptive_frequency_threshold(dominant_freqs):
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:]
half_max = autocorrelation[0] * 0.5
peaks, _ = find_peaks(-autocorrelation, height=-half_max)
return peaks[0] if len(peaks) > 0 else min(24, len(cleaned_signal) // 2)
def moving_average_forecast(series, window_size):
forecast = [series[t:t + window_size].mean() for t in range(len(series) - window_size + 1)]
return np.array(forecast)
def plot_imfs(time, IMFs, low_freq_indices):
num_IMFs = IMFs.shape[0]
plt.figure(figsize=(12, 3*num_IMFs))
# 确保时间列和IMFs长度匹配
time = time[:IMFs.shape[1]]
for i in range(num_IMFs):
plt.subplot(num_IMFs, 1, i + 1)
color = 'b' if i not in low_freq_indices else 'r'
plt.plot(time, IMFs[i], label=f'IMF {i+1}', color=color)
title_suffix = ' (低频, 温度影响)' if i in low_freq_indices else ''
plt.legend(loc='upper right')
plt.title(f'IMF {i+1}{title_suffix}')
plt.xlabel('时间')
plt.ylabel('挠度')
plt.tight_layout()
plt.show()
def save_best_params(params):
with open(PARAM_FILE, 'w', encoding='utf-8') as f:
json.dump(params, f, ensure_ascii=False, indent=4)
print(f"最佳参数已保存到 {PARAM_FILE}。")
def load_best_params():
if not os.path.exists(PARAM_FILE):
print(f"参数文件 {PARAM_FILE} 不存在。")
return None
with open(PARAM_FILE, 'r', encoding='utf-8') as f:
params = json.load(f)
print(f"已加载最佳参数: {params}")
return params
def estimate_contamination(series):
mean = np.mean(series)
std = np.std(series)
threshold_upper = mean + 3 * std
threshold_lower = mean - 3 * std
num_anomalies = np.sum((series > threshold_upper) | (series < threshold_lower))
contamination = num_anomalies / len(series)
return min(max(contamination, 0.01), 0.05)
def main_automated_process(file_path):
try:
df = pd.read_excel(file_path)
except Exception as e:
print(f"读取Excel文件时出错: {e}")
return None, None
required_columns = ['时间', '挠度']
if not all(col in df.columns for col in required_columns):
print("Excel文件中缺少必要的列,请检查列名('时间'和'挠度'必须存在)。")
return None, None
df['时间'] = pd.to_datetime(df['时间'])
# Apply Savitzky-Golay filter for smoothing
window_size = 11
poly_order = 3
df['平滑挠度'] = savgol_filter(df['挠度'], window_size, poly_order)
contamination = estimate_contamination(df['平滑挠度'].values)
iso_forest = IsolationForest(contamination=contamination, random_state=42)
anomalies = iso_forest.fit_predict(df[['平滑挠度']])
df['挠度_去除异常'] = df['平滑挠度']
df.loc[anomalies == -1, '挠度_去除异常'] = np.nan
num_anomalies = (anomalies == -1).sum()
cleaned_data = df[['时间', '挠度_去除异常']].dropna()
time_seconds = (cleaned_data['时间'] - cleaned_data['时间'].iloc[0]).dt.total_seconds().values
cleaned_signal, removed_IMFs, IMFs, frequency_threshold = vmd_spectral_decomposition(
signal=cleaned_data['挠度_去除异常'].values,
time_seconds=time_seconds
)
df.loc[cleaned_data.index[:len(cleaned_signal)], '去除温致挠度'] = cleaned_signal
plot_imfs(cleaned_data['时间'].values[:len(cleaned_signal)], IMFs, removed_IMFs)
window_size_forecast = dynamic_window_size(cleaned_signal)
forecast = moving_average_forecast(cleaned_signal, window_size_forecast)
if len(forecast) > 0:
actual = cleaned_signal[window_size_forecast - 1:]
predicted = forecast[:len(actual)]
rmse = np.sqrt(mean_squared_error(actual, predicted))
forecast_series = np.concatenate([cleaned_signal[:window_size_forecast - 1], forecast])
df.loc[cleaned_data.index[:len(forecast_series)], '预测'] = forecast_series
used_params = {
'contamination': contamination,
'frequency_threshold': frequency_threshold,
'window_size_forecast': window_size_forecast
}
save_best_params(used_params)
plt.figure(figsize=(14, 8))
plt.subplot(2, 1, 1)
plt.plot(cleaned_data['时间'].iloc[:len(cleaned_signal)], cleaned_data['挠度_去除异常'].iloc[:len(cleaned_signal)], label='原始信号', color='b', alpha=0.5)
plt.plot(cleaned_data['时间'].iloc[:len(cleaned_signal)], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.legend(loc='upper right')
plt.title('原始信号 vs 去除低频IMF后的信号')
plt.xlabel('时间')
plt.ylabel('挠度')
if '预测' in df.columns:
plt.subplot(2, 1, 2)
plt.plot(cleaned_data['时间'].iloc[:len(forecast_series)], cleaned_signal[:len(forecast_series)], label='去除低频IMF后的信号', color='g')
plt.plot(cleaned_data['时间'].iloc[:len(forecast_series)], forecast_series, label='移动平均预测', color='r')
plt.legend(loc='upper right')
plt.title('去除低频IMF后的信号及其预测')
plt.xlabel('时间')
plt.ylabel('挠度')
plt.tight_layout()
plt.show()
return df, used_params
def main():
file_path = './挠度数据910.xlsx' # Replace with your actual file path
df_result, optimal_params = main_automated_process(file_path)
if optimal_params:
print("\n自动化处理完成。")
print(f"使用的参数组合: {optimal_params}")
if __name__ == "__main__":
main()