明白了,您希望采用一种不同的参数自适应方法,以更好地处理所有被标记为温度的模态,并确保代码能够顺利运行。当前的代码使用网格搜索(Grid Search)来优化参数组合,但这可能在所有模态都受温度影响的情况下效果不佳。
以下是一个改进后的版本,采用基于数据统计特性的自适应参数选择方法,避免了预定义的参数网格搜索。这种方法能够根据数据的特性动态调整参数,从而更好地适应温度对所有模态的影响。
关键改进点:
- 动态确定
contamination参数:通过统计数据中异常值的分布,自动估计异常比例。
- 动态确定
frequency_threshold参数:根据分解后的IMF主频率的统计特性(如中位数或特定百分位数)来设置频率阈值。
- 动态确定
window_size_forecast参数:基于数据的采样率和时间序列长度,自动选择合适的窗口大小。
改进后的代码:
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_freq
def 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_threshold
def 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()
def save_best_params(params):
"""保存最佳参数到JSON文件"""
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():
"""从JSON文件加载最佳参数"""
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):
"""
基于统计特性自动估计异常值比例
:param series: 一维数值序列
:return: estimated contamination
"""
# 使用3-sigma原则估计异常比例
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)
# 确保 contamination 在合理范围内
contamination = min(max(contamination, 0.01), 0.05) # 限制在1%到5%之间
print(f"自动估计的异常比例(contamination): {contamination:.4f}")
return contamination
def main_automated_process(file_path):
"""
主自动化处理流程,采用自适应参数选择
:param file_path: Excel文件路径
:return: 处理后的DataFrame, 使用的参数字典
"""
# 读取数据
try:
df = pd.read_excel(file_path)
except Exception as e:
print(f"读取Excel文件时出错: {e}")
return None, None
print("Excel文件读取成功。")
print(f"数据总行数: {len(df)}")
print(f"列名: {df.columns.tolist()}")
# 检查列名是否包含 '时间' 和 '挠度'
required_columns = ['时间', '挠度']
for col in required_columns:
if col not in df.columns:
print(f"Excel文件中缺少 '{col}' 列,请检查列名。")
return None, None
# 将“时间”列转换为datetime格式
try:
df['时间'] = pd.to_datetime(df['时间'])
except Exception as e:
print(f"转换 '时间' 列为 datetime 格式时出错: {e}")
return None, None
# 使用 Savitzky-Golay 滤波器进行平滑
window_size = 11
poly_order = 3
if window_size % 2 == 0:
window_size += 1
print(f"window_size为偶数,已调整为 {window_size}")
try:
df['平滑挠度'] = savgol_filter(df['挠度'], window_size, poly_order)
except Exception as e:
print(f"Savgol 滤波器应用时出错: {e}")
return None, None
# 自动估计参数
contamination = estimate_contamination(df['平滑挠度'].values)
# 使用孤立森林检测异常值
iso_forest = IsolationForest(contamination=contamination, random_state=42)
try:
anomalies = iso_forest.fit_predict(df[['平滑挠度']])
except Exception as e:
print(f"孤立森林异常检测时出错: {e}")
return None, None
df['挠度_去除异常'] = df['平滑挠度']
df.loc[anomalies == -1, '挠度_去除异常'] = np.nan
num_anomalies = (anomalies == -1).sum()
print(f"检测到的异常值数量: {num_anomalies}")
# 获取去除异常后的数据
cleaned_data = df[['时间', '挠度_去除异常']].dropna()
if cleaned_data.empty:
print("所有数据点都被标记为异常,无法继续处理。")
return df, None
# 将时间列转换为秒数
try:
time_seconds = (cleaned_data['时间'] - cleaned_data['时间'].iloc[0]).dt.total_seconds().values
except Exception as e:
print(f"转换时间列为秒数时出错: {e}")
return None, None
# EMD分解并去除低频IMF,自动确定频率阈值
try:
cleaned_signal, removed_IMFs, IMFs, frequency_threshold = emd_spectral_decomposition(
signal=cleaned_data['挠度_去除异常'].values,
time_seconds=time_seconds
)
except Exception as e:
print(f"EMD分解过程中出错: {e}")
return df, None
# 绘制所有IMF并标注低频IMF
plot_imfs(cleaned_data['时间'], IMFs, removed_IMFs)
# 添加去除温致挠度后的信号到DataFrame
df.loc[cleaned_data.index, '去除温致挠度'] = cleaned_signal
# 动态确定移动平均的窗口大小
# 例如,可以设置为采样率的一定比例
sampling_interval = np.mean(np.diff(time_seconds)) # 平均时间间隔
sampling_rate = 1 / sampling_interval # 采样率 (Hz)
window_size_forecast = int(sampling_rate * 10) # 例如,10秒的窗口
window_size_forecast = max(12, window_size_forecast) # 确保至少12
print(f"动态确定的移动平均窗口大小 (window_size_forecast): {window_size_forecast}")
# 移动平均预测
try:
forecast = moving_average_forecast(cleaned_signal, window_size_forecast)
if len(forecast) == 0:
# 预测结果为空
print("移动平均预测生成的预测数据为空。")
forecast_series = np.array([])
else:
actual = cleaned_signal[window_size_forecast -1 :]
predicted = forecast
# 计算RMSE
rmse = np.sqrt(mean_squared_error(actual, predicted))
print(f"移动平均预测的RMSE: {rmse:.4f}")
# 对于最终预测结果,直接与实际数据对齐
forecast_series = np.concatenate([cleaned_signal[:len(cleaned_signal) - len(forecast)], forecast])
df.loc[cleaned_data.index, '预测'] = forecast_series
except Exception as e:
print(f"移动平均预测过程中出错: {e}")
forecast_series = np.array([])
# 保存使用的参数
used_params = {
'contamination': contamination,
'frequency_threshold': frequency_threshold,
'window_size_forecast': window_size_forecast
}
save_best_params(used_params)
# 绘制最终结果
try:
plt.figure(figsize=(14, 8))
# 原始信号 vs 去除低频IMF后的信号
plt.subplot(2, 1, 1)
plt.plot(cleaned_data['时间'], cleaned_data['挠度_去除异常'], label='原始信号', color='b', alpha=0.5)
plt.plot(cleaned_data['时间'], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.legend(loc='upper right')
plt.title('原始信号 vs 去除低频IMF后的信号')
plt.xlabel('时间')
plt.ylabel('挠度')
# 信号及预测
if forecast_series.size > 0:
plt.subplot(2, 1, 2)
plt.plot(cleaned_data['时间'], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.plot(cleaned_data['时间'], forecast_series, label='移动平均预测', color='r')
plt.legend(loc='upper right')
plt.title('去除低频IMF后的信号及其预测')
plt.xlabel('时间')
plt.ylabel('挠度')
else:
plt.subplot(2, 1, 2)
plt.plot(cleaned_data['时间'], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.legend(loc='upper right')
plt.title('去除低频IMF后的信号')
plt.xlabel('时间')
plt.ylabel('挠度')
plt.tight_layout()
plt.show()
except Exception as e:
print(f"可视化过程中出错: {e}")
return df, used_params
def load_and_process_with_best_params(file_path, best_params):
"""
使用加载的最佳参数进行处理
:param file_path: Excel文件路径
:param best_params: 最佳参数字典
:return: 处理后的DataFrame
"""
contamination = best_params.get('contamination', 0.02)
frequency_threshold = best_params.get('frequency_threshold', 0.1)
window_size_forecast = best_params.get('window_size_forecast', 24)
# 读取数据
try:
df = pd.read_excel(file_path)
except Exception as e:
print(f"读取Excel文件时出错: {e}")
return None
print("Excel文件读取成功。")
print(f"数据总行数: {len(df)}")
print(f"列名: {df.columns.tolist()}")
# 检查列名是否包含 '时间' 和 '挠度'
required_columns = ['时间', '挠度']
for col in required_columns:
if col not in df.columns:
print(f"Excel文件中缺少 '{col}' 列,请检查列名。")
return None
# 将“时间”列转换为datetime格式
try:
df['时间'] = pd.to_datetime(df['时间'])
except Exception as e:
print(f"转换 '时间' 列为 datetime 格式时出错: {e}")
return None
# 使用 Savitzky-Golay 滤波器进行平滑
window_size = 11
poly_order = 3
if window_size % 2 == 0:
window_size += 1
print(f"window_size为偶数,已调整为 {window_size}")
try:
df['平滑挠度'] = savgol_filter(df['挠度'], window_size, poly_order)
except Exception as e:
print(f"Savgol 滤波器应用时出错: {e}")
return None
# 使用孤立森林检测异常值
iso_forest = IsolationForest(contamination=contamination, random_state=42)
try:
anomalies = iso_forest.fit_predict(df[['平滑挠度']])
except Exception as e:
print(f"孤立森林异常检测时出错: {e}")
return None
df['挠度_去除异常'] = df['平滑挠度']
df.loc[anomalies == -1, '挠度_去除异常'] = np.nan
num_anomalies = (anomalies == -1).sum()
print(f"检测到的异常值数量: {num_anomalies}")
# 获取去除异常后的数据
cleaned_data = df[['时间', '挠度_去除异常']].dropna()
if cleaned_data.empty:
print("所有数据点都被标记为异常,无法继续处理。")
return df
# 将时间列转换为秒数
try:
time_seconds = (cleaned_data['时间'] - cleaned_data['时间'].iloc[0]).dt.total_seconds().values
except Exception as e:
print(f"转换时间列为秒数时出错: {e}")
return None
# EMD分解并去除低频IMF,使用指定的频率阈值
try:
cleaned_signal, removed_IMFs, IMFs, _ = emd_spectral_decomposition(
signal=cleaned_data['挠度_去除异常'].values,
time_seconds=time_seconds,
frequency_threshold=frequency_threshold
)
except Exception as e:
print(f"EMD分解过程中出错: {e}")
return df
# 绘制所有IMF并标注低频IMF
plot_imfs(cleaned_data['时间'], IMFs, removed_IMFs)
# 添加去除温致挠度后的信号到DataFrame
df.loc[cleaned_data.index, '去除温致挠度'] = cleaned_signal
# 移动平均预测
try:
forecast = moving_average_forecast(cleaned_signal, window_size_forecast)
if len(forecast) == 0:
# 预测结果为空
print("移动平均预测生成的预测数据为空。")
forecast_series = np.array([])
else:
actual = cleaned_signal[window_size_forecast -1 :]
predicted = forecast
# 计算RMSE
rmse = np.sqrt(mean_squared_error(actual, predicted))
print(f"移动平均预测的RMSE: {rmse:.4f}")
# 对于最终预测结果,直接与实际数据对齐
forecast_series = np.concatenate([cleaned_signal[:len(cleaned_signal) - len(forecast)], forecast])
df.loc[cleaned_data.index, '预测'] = forecast_series
except Exception as e:
print(f"移动平均预测过程中出错: {e}")
forecast_series = np.array([])
# 绘制最终结果
try:
plt.figure(figsize=(14, 8))
# 原始信号 vs 去除低频IMF后的信号
plt.subplot(2, 1, 1)
plt.plot(cleaned_data['时间'], cleaned_data['挠度_去除异常'], label='原始信号', color='b', alpha=0.5)
plt.plot(cleaned_data['时间'], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.legend(loc='upper right')
plt.title('原始信号 vs 去除低频IMF后的信号')
plt.xlabel('时间')
plt.ylabel('挠度')
# 信号及预测
if forecast_series.size > 0:
plt.subplot(2, 1, 2)
plt.plot(cleaned_data['时间'], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.plot(cleaned_data['时间'], forecast_series, label='移动平均预测', color='r')
plt.legend(loc='upper right')
plt.title('去除低频IMF后的信号及其预测')
plt.xlabel('时间')
plt.ylabel('挠度')
else:
plt.subplot(2, 1, 2)
plt.plot(cleaned_data['时间'], cleaned_signal, label='去除低频IMF后的信号', color='g')
plt.legend(loc='upper right')
plt.title('去除低频IMF后的信号')
plt.xlabel('时间')
plt.ylabel('挠度')
plt.tight_layout()
plt.show()
except Exception as e:
print(f"可视化过程中出错: {e}")
return df, best_params
def display_menu():
"""显示菜单选项"""
print("\n请选择操作模式:")
print("1. 自适应选择参数 (自动参数优化)")
print("2. 使用上次的参数")
print("3. 退出")
choice = input("请输入选项 (1/2/3): ").strip()
return choice
def main():
file_path = './挠度数据910.xlsx' # 替换为实际文件路径
while True:
choice = display_menu()
if choice == '1':
print("\n您选择了自适应选择参数 (自动参数优化)。")
df_result, optimal_params = main_automated_process(file_path)
if optimal_params:
print("\n自动化处理完成。")
print(f"使用的参数组合: {optimal_params}")
elif choice == '2':
print("\n您选择了使用上次的参数。")
best_params = load_best_params()
if best_params is None:
print("未找到上次的参数,请先进行自适应选择参数 (选项1)。")
continue
df_result, _ = load_and_process_with_best_params(file_path, best_params)
if df_result is not None:
print("\n使用上次的参数处理完成。")
elif choice == '3':
print("退出程序。")
break
else:
print("无效的选项,请重新选择。")
if __name__ == "__main__":
main()
详细说明:
-
自动估计contamination参数:
- 采用3-sigma原则(即数据中超出均值±3倍标准差的点被视为异常)来估计异常值的比例。
- 该比例被限制在1%到5%之间,以避免将过多或过少的数据点标记为异常。
def estimate_contamination(series):
"""
基于统计特性自动估计异常值比例
:param series: 一维数值序列
:return: estimated contamination
"""
# 使用3-sigma原则估计异常比例
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)
# 确保 contamination 在合理范围内
contamination = min(max(contamination, 0.01), 0.05) # 限制在1%到5%之间
print(f"自动估计的异常比例(contamination): {contamination:.4f}")
return contamination
-
自动确定frequency_threshold参数:
- 如果用户未指定频率阈值,则通过计算所有IMF的主频率,并采用中位数作为阈值来区分低频和高频IMF。
- 这样可以根据数据的实际频率分布自适应地设置阈值。
if frequency_threshold is None:
frequency_threshold = np.median(dominant_freqs)
print(f"自动确定的频率阈值为IMF主频率的中位数: {frequency_threshold:.4f} Hz")
-
自动确定window_size_forecast参数:
- 根据数据的采样率和预期的预测范围(例如10秒)动态计算窗口大小。
- 确保窗口大小至少为12,以避免窗口过小。
# 动态确定移动平均的窗口大小
# 例如,可以设置为采样率的一定比例
sampling_interval = np.mean(np.diff(time_seconds)) # 平均时间间隔
sampling_rate = 1 / sampling_interval # 采样率 (Hz)
window_size_forecast = int(sampling_rate * 10) # 例如,10秒的窗口
window_size_forecast = max(12, window_size_forecast) # 确保至少12
print(f"动态确定的移动平均窗口大小 (window_size_forecast): {window_size_forecast}")
-
代码结构调整:
- 移除了重复定义的
load_and_process_with_best_params函数,确保代码的可读性和可维护性。
- 将参数自适应方法集成到主处理流程中,避免了预定义的网格搜索,提高了处理效率和适应性。
-
处理过程:
- 模式1:自适应选择参数,通过统计特性自动确定参数,然后进行数据处理。
- 模式2:使用上次保存的最佳参数,直接进行数据处理。
-
可视化:
- 绘制所有IMF,并用红色标注低频IMF(受温度影响)。
- 绘制去除低频IMF后的信号与移动平均预测结果。
-
参数保存与加载:
- 自动保存使用的最佳参数到
best_params.json文件,以便后续使用。
- 提供加载参数的功能,允许用户选择使用上次的参数进行处理。
使用说明:
-
确保必要的库已安装:
-
准备数据:
- 确保Excel文件中包含
时间和挠度两列,且时间列为可解析的日期时间格式。
-
运行脚本:
- 确保脚本中的
file_path指向实际的数据文件。
- 运行脚本后,按照提示选择操作模式:
- 选项1:自适应选择参数并进行数据处理。
- 选项2:使用上次保存的参数进行数据处理。
- 选项3:退出程序。
-
结果:
- 处理完成后,Excel文件会包含新的列
平滑挠度、挠度_去除异常、去除温致挠度和预测。
- 生成的图表将展示IMF分解、信号去噪和预测结果。
注意事项:
- 异常点处理:自动估计的
contamination比例基于3-sigma原则,适用于大多数符合正态分布的数据。如果数据分布明显偏离正态分布,可以根据实际情况调整估计算法。
- 频率阈值:采用IMF主频率的中位数作为阈值,这在大多数情况下效果较好。如果您的数据具有特定频率特性,可以根据需求调整阈值确定方法。
- 窗口大小:移动平均窗口大小基于采样率和预期的预测时间范围动态确定,您可以根据具体需求调整相关计算公式。
通过上述修改,参数选择过程更加自适应,能够更好地处理受到温度影响的所有模态,同时确保代码的可运行性和稳定性。