pywt 没有set_level怎么办
时间: 2023-10-16 13:11:07 浏览: 52
如果你想设置小波变换的分解层数,可以使用pywt的wavenames函数来获取支持的小波族(family)和小波(wavelet),然后使用pywt的wavedec函数来进行分解,并设置分解层数。例如,如果要使用db2小波将信号分解为3层,请使用以下代码:
```
import pywt
# 获取db2小波
wavelet = pywt.Wavelet('db2')
# 将信号x进行小波分解,分解3层
coeffs = pywt.wavedec(x, wavelet, level=3)
```
这样就可以将信号分解为3层,并使用db2小波进行分解。
相关问题
import pandas as pd import matplotlib.pyplot as plt import numpy as np import pywt file_name = 'E:/liuyuan/ceshi/zhongyao/Subject_1_0cmH20_norm_breaths.csv' data = pd.read_csv(file_name, skiprows=1, usecols=[0, 2], names=['Time', 'Flow']) x = list() y = list() for i in range(len(data)): x.append(float(data.values[i][0])) y.append(float(data.values[i][1])) start_index = 0 end_index = 5372 time = np.arange(start_index, end_index) flow = np.arange(start_index, end_index) time = data['Time'][start_index:end_index] flow = data['Flow'] def wavelet_filter(data): wavelet = 'db4' # 选择小波基函数 level = 5 # 小波变换的层数 # 小波变换 coeffs = pywt.wavedec(data, wavelet, level=level) threshold = np.std(coeffs[-level]) * np.sqrt(2 * np.log(len(data))) coeffs[1:] = (pywt.threshold(c, threshold, mode='soft') for c in coeffs[1:]) filtered_data = pywt.waverec(coeffs, wavelet) return filtered_data 对Flow进行小波变换滤波 filtered_flow = wavelet_filter(flow) fig, ax = plt.subplots(figsize=(10, 5)) plt.xlim(0, 60) ax.set_ylim(-0.7, 0.7) ax.set_xlabel('Time(s)', fontsize=10) ax.set_ylabel('Flow(L/s)', fontsize=10) ax.plot(time, filtered_flow, label='Filtered Flow') ax.legend() ax.grid(True, linewidth=0.3, alpha=0.5, color='gray') plt.tight_layout() # 自动调整子图的布局 plt.show()import pandas as pd import matplotlib.pyplot as plt import numpy as np import pywt file_name = 'E:/liuyuan/ceshi/zhongyao/Subject_1_0cmH20_norm_breaths.csv' data = pd.read_csv(file_name, skiprows=1, usecols=[0, 2], names=['Time', 'Flow']) x = list() y = list() for i in range(len(data)): x.append(float(data.values[i][0])) y.append(float(data.values[i][1])) start_index = 0 end_index = 5372 time = np.arange(start_index, end_index) flow = np.arange(start_index, end_index) time = data['Time'][start_index:end_index] flow = data['Flow'] def wavelet_filter(data): wavelet = 'db4' # 选择小波基函数 level = 5 # 小波变换的层数 coeffs = pywt.wavedec(data, wavelet, level=level) threshold = np.std(coeffs[-level]) * np.sqrt(2 * np.log(len(data))) coeffs[1:] = (pywt.threshold(c, threshold, mode='soft') for c in coeffs[1:]) # 逆小波变换 filtered_data = pywt.waverec(coeffs, wavelet) return filtered_data filtered_flow = wavelet_filter(flow) fig, ax = plt.subplots(figsize=(10, 5)) plt.xlim(0, 60) ax.set_ylim(-0.7, 0.7) ax.set_xlabel('Time(s)', fontsize=10) ax.set_ylabel('Flow(L/s)', fontsize=10) ax.plot(time, filtered_flow, label='Filtered Flow') ax.legend() ax.grid(True, linewidth=0.3, alpha=0.5, color='gray') plt.tight_layout() plt.show()在此代码上添加切分代码,并按照合适窗口大小切分完准确显示
你可以在代码中添加以下切分代码,来按照合适的窗口大小进行切分并准确显示:
```python
window_size = 100 # 窗口大小
# 切分数据
num_windows = len(filtered_flow) // window_size
flow_windows = np.array_split(filtered_flow, num_windows)
# 绘制切分后的数据
fig, axs = plt.subplots(num_windows, figsize=(10, 5*num_windows), sharex=True)
for i, ax in enumerate(axs):
ax.plot(time[i*window_size:(i+1)*window_size], flow_windows[i])
ax.set_ylim(-0.7, 0.7)
ax.set_xlabel('Time(s)', fontsize=10)
ax.set_ylabel('Flow(L/s)', fontsize=10)
ax.grid(True, linewidth=0.3, alpha=0.5, color='gray')
plt.tight_layout()
plt.show()
```
这段代码将数据按照窗口大小切分,并在多个子图中分别绘制每个窗口的数据。你可以根据窗口大小调整`window_size`的值来适应你的需求。
wavelet_df.loc[i] = energy_values发生报错:发生异常: ValueError cannot set a row with mismatched columns File "/Users/dingfengyan/工作/项目开发/哈理工/批量导出功能/binzcsv+feature.py", line 150, in <module> wavelet_df.loc[i] = energy_values ~~~~~~~~~~~~~~^^^ ValueError: cannot set a row with mismatched columns
这个报错是因为在设置`wavelet_df.loc[i]`的时候,`energy_values`的长度与DataFrame的列数不匹配。可能是因为`energy_values`的长度与窗口数量不一致导致的。请确保`energy_values`的长度与窗口数量相同,并且DataFrame的列数已经正确初始化。你可以尝试以下修改:
```python
import os
import struct
import pandas as pd
import numpy as np
import pywt
# 定义窗口大小和步长
window_size = 100
step_size = 50
# 获取当前目录路径
current_dir = os.getcwd()
# 创建原始csv目录
raw_csv_dir = os.path.join(current_dir, '原始csv')
if not os.path.exists(raw_csv_dir):
os.makedirs(raw_csv_dir)
# 创建时频域特征csv目录
feature_csv_dir = os.path.join(current_dir, '时频域特征csv目录')
if not os.path.exists(feature_csv_dir):
os.makedirs(feature_csv_dir)
def read_bin_file(file_path):
# 打开bin文件并读取数据
with open(file_path, 'rb') as f:
data = f.read()
return data
def convert_to_float(data):
# 将每8个字节转为浮点数
floats = []
for i in range(0, len(data), 8):
float_val = struct.unpack('f', data[i:i+4])[0]
floats.append(float_val)
return floats
def calculate_statistics(window_data):
# 计算统计指标和时频域参数
mean_value = np.mean(window_data)
var_value = np.var(window_data)
rms_value = np.sqrt(np.mean(np.square(window_data)))
skewness = pd.Series(window_data).skew()
kurtosis = pd.Series(window_data).kurt()
crest_factor = np.max(np.abs(window_data)) / rms_value
peak_factor = np.max(window_data) / rms_value
impulse_factor = np.max(np.abs(window_data)) / np.mean(np.abs(window_data))
margin_factor = np.max(np.abs(window_data)) / np.std(window_data)
return mean_value, var_value, rms_value, skewness, kurtosis, crest_factor, peak_factor, impulse_factor, margin_factor
def calculate_wavelet_energy(window_data):
# 计算小波能量值
coeffs = pywt.wavedec(window_data, 'db4', level=16)
energy_values = [np.sum(np.square(coeff)) for coeff in coeffs]
return energy_values
# 遍历当前目录及子目录下的所有bin文件
for root, dirs, files in os.walk(current_dir):
for file in files:
if file.endswith('.bin'):
bin_file_path = os.path.join(root, file)
# 读取bin文件
bin_data = read_bin_file(bin_file_path)
# 转换为浮点数
floats = convert_to_float(bin_data)
# 创建DataFrame用于存储数据
df = pd.DataFrame(columns=['1', '2', '3'])
# 将数据按顺序写入DataFrame的列中
df['1'] = floats[::3]
df['2'] = floats[1::3]
df['3'] = floats[2::3]
# 将DataFrame保存为原始csv文件
csv_file_path = os.path.join(raw_csv_dir, f'{file}.csv')
df.to_csv(csv_file_path, index=False)
# 创建新的DataFrame用于存储时频域特征数据
feature_df = pd.DataFrame(columns=[f'{file}_mean', f'{file}_var', f'{file}_rms',
f'{file}_skew', f'{file}_kurtosis', f'{file}_crest',
f'{file}_peak', f'{file}_impulse', f'{file}_margin'])
# 创建新的DataFrame用于存储小波特征数据
wavelet_df = pd.DataFrame(columns=[f'{file}_energy_{i}' for i in range(1, 17)])
# 对每列进行窗口切片,并计算统计指标和时频域参数
for col in df.columns:
col_data = df[col]
num_windows = (len(col_data) - window_size) // step_size + 1
for i in range(num_windows):
window_data = col_data[i*step_size : i*step_size + window_size]
# 计算统计指标和时频域参数
result = calculate_statistics(window_data)
# 将结果添加到时频域特征DataFrame
feature_df.loc[i] = result
# 计算小波能量值
energy_values = calculate_wavelet_energy(window_data)
# 将结果添加到小波特征DataFrame
wavelet_df.loc[i, [f'{file}_energy_{j+1}' for j in range(len(energy_values))]] = energy_values
# 将时频域特征数据保存为新的csv文件
feature_csv_file_path = os.path.join(feature_csv_dir, f'{file}.csv')
feature_df.to_csv(feature_csv_file_path, index=False)
# 将小波特征数据保存为新的csv文件
wavelet_csv_file_path = os.path.join(feature_csv_dir, f'{file}_wavelet.csv')
wavelet_df.to_csv(wavelet_csv_file_path, index=False)
print("时频域特征csv文件和小波特征csv文件生成完成")
```
在上述代码中,我修改了计算小波能量值的部分,使用`wavelet_df.loc[i, [f'{file}_energy_{j+1}' for j in range(len(energy_values))]]`来设置每行的值。这样可以确保`energy_values`的长度与DataFrame的列数匹配。请注意在保存小波特征数据的csv文件时,我将文件名命名为`{file}_wavelet.csv`,以区分时频域特征数据的csv文件。
阅读全文