40行报错:ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part.
时间: 2023-07-24 20:04:30 浏览: 272
非常抱歉,我之前给出的修正代码仍然存在问题。在计算特征向量时,我们需要使用一个空的列表来存储特征值。以下是修正后的代码:
```python
import os
import csv
import struct
import numpy as np
import pywt
def calculate_features(data):
features = []
for i in range(3):
features.append(np.mean(data[:, i]))
features.append(np.var(data[:, i]))
for i in range(1, 17):
coeffs = pywt.wavedec(data[:, i % 3], "db4", level=i)
energy = np.sum(np.square(coeffs))
features.append(energy)
return features
# 创建保存CSV文件的文件夹
csv_folder = "csv"
if not os.path.exists(csv_folder):
os.makedirs(csv_folder)
# 遍历文件夹及子文件夹中的二进制bin文件
for root, dirs, files in os.walk(".", topdown=True):
for filename in files:
if filename.endswith(".bin"):
# 构建CSV文件路径
bin_filepath = os.path.join(root, filename)
csv_filename = f"{os.path.splitext(filename)[0]}_原始文件.csv"
csv_filepath = os.path.join(csv_folder, csv_filename)
# 打开二进制bin文件并读取数据
with open(bin_filepath, "rb") as bin_file:
bin_data = bin_file.read()
# 解析二进制数据并转换为浮点数
floats = []
for i in range(0, len(bin_data), 8):
float_value = struct.unpack("d", bin_data[i:i + 8])[0]
floats.append(float_value)
# 将数据按顺序分别放到1、2、3列并保存到CSV文件
data = np.array(floats).reshape(-1, 3)
with open(csv_filepath, "w", newline="") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["1", "2", "3"])
writer.writerows(data)
# 计算特征并保存到特征文件
feature_filename = f"{os.path.splitext(filename)[0]}_特征文件.csv"
feature_filepath = os.path.join(csv_folder, feature_filename)
with open(feature_filepath, "w", newline="") as feature_file:
writer = csv.writer(feature_file)
header = []
for i in range(1, 17):
header.append(f"均值{i}")
header.append(f"方差{i}")
header.append(f"能量{i}")
writer.writerow(header)
# 按窗口大小计算特征
window_size = 100
step_size = 50
num_windows = (len(data) - window_size) // step_size + 1
for i in range(num_windows):
start_idx = i * step_size
end_idx = start_idx + window_size
window_data = data[start_idx:end_idx]
features = calculate_features(window_data)
writer.writerow(features)
```
这次的代码会按照窗口大小和步长对数据进行切片,并在每个窗口上计算特征。然后,它将这些特征保存到特征文件中。非常抱歉之前的错误带来的困扰,希望这次的回答能够满足你的需求。
阅读全文