152 lines
5.5 KiB
Python
152 lines
5.5 KiB
Python
import os
|
|
import pickle
|
|
import argparse
|
|
from tqdm import tqdm
|
|
import numpy as np
|
|
|
|
|
|
def get_args_parser():
|
|
"""
|
|
解析命令行参数。
|
|
"""
|
|
parser = argparse.ArgumentParser(
|
|
'Finetune Data Preprocessing Script', add_help=False)
|
|
|
|
parser.add_argument('--input_dir', required=True, type=str,
|
|
help='Path to the directory containing the original .pkl sample files (e.g., sample_for_downstream).')
|
|
|
|
parser.add_argument('--output_dir', required=True, type=str,
|
|
help='Path to the directory where the processed .pkl files will be saved.')
|
|
|
|
parser.add_argument('--target_len', type=int, default=387,
|
|
help='The target sequence length to pad or truncate to.')
|
|
|
|
parser.add_argument('--pad_mode', type=str, default='zero', choices=['zero', 'reflect', 'edge'],
|
|
help="Padding mode. 'zero' for zero-padding, 'reflect' for reflection, 'edge' for edge value replication.")
|
|
|
|
parser.add_argument('--pad_location', type=str, default='front', choices=['front', 'back'],
|
|
help="Location to add padding. 'front' pads at the beginning, 'back' pads at the end.")
|
|
|
|
return parser
|
|
|
|
|
|
def process_file(input_path, output_path, target_len, pad_mode, pad_location):
|
|
"""
|
|
加载单个.pkl文件,处理其内部'data'字段的长度,并保存到新位置。
|
|
"""
|
|
try:
|
|
# 1. 加载原始数据
|
|
with open(input_path, 'rb') as f:
|
|
data_dict = pickle.load(f)
|
|
|
|
# 确保'data'字段存在
|
|
if 'data' not in data_dict:
|
|
print(f"Warning: 'data' key not found in {input_path}. Skipping.")
|
|
return
|
|
|
|
signal = data_dict['data']
|
|
|
|
# 确保数据是numpy数组
|
|
if not isinstance(signal, np.ndarray):
|
|
signal = np.array(signal)
|
|
|
|
# 确保数据是二维的 [n_vars, length]
|
|
if signal.ndim == 1:
|
|
signal = np.expand_dims(signal, axis=0)
|
|
|
|
current_len = signal.shape[1]
|
|
|
|
# 2. 根据长度进行处理
|
|
if current_len == target_len:
|
|
# 长度已经匹配,直接复制
|
|
processed_signal = signal
|
|
elif current_len > target_len:
|
|
# 长度过长,从末尾裁剪
|
|
processed_signal = signal[:, -target_len:]
|
|
else: # current_len < target_len
|
|
# 长度过短,进行填充
|
|
pad_size = target_len - current_len
|
|
n_vars = signal.shape[0]
|
|
|
|
if pad_mode == 'zero':
|
|
pad_values = np.zeros((n_vars, pad_size), dtype=signal.dtype)
|
|
elif pad_mode == 'edge':
|
|
# 复制边缘值
|
|
if pad_location == 'front':
|
|
edge_values = signal[:, 0:1] # 取第一个时间点的值
|
|
else: # back
|
|
edge_values = signal[:, -1:] # 取最后一个时间点的值
|
|
pad_values = np.repeat(edge_values, pad_size, axis=1)
|
|
elif pad_mode == 'reflect':
|
|
# 反射填充是一种更平滑的方式,但实现稍复杂
|
|
# 这里我们使用numpy内置的pad函数
|
|
if pad_location == 'front':
|
|
pad_width = ((0, 0), (pad_size, 0)) # 只在前面填充
|
|
else: # back
|
|
pad_width = ((0, 0), (0, pad_size)) # 只在后面填充
|
|
processed_signal = np.pad(signal, pad_width, mode='reflect')
|
|
# np.pad会返回完整数组,所以我们直接进入下一步
|
|
|
|
# 对于非'reflect'模式,手动拼接
|
|
if pad_mode != 'reflect':
|
|
if pad_location == 'front':
|
|
processed_signal = np.concatenate(
|
|
[pad_values, signal], axis=1)
|
|
else: # back
|
|
processed_signal = np.concatenate(
|
|
[signal, pad_values], axis=1)
|
|
|
|
# 3. 更新字典并保存
|
|
data_dict['data'] = processed_signal
|
|
|
|
with open(output_path, 'wb') as f:
|
|
pickle.dump(data_dict, f)
|
|
|
|
except Exception as e:
|
|
print(f"Error processing file {input_path}: {e}")
|
|
|
|
|
|
def main(args):
|
|
"""
|
|
主执行函数。
|
|
"""
|
|
print("--- Starting Finetune Data Preprocessing ---")
|
|
print(f"Input directory: {args.input_dir}")
|
|
print(f"Output directory: {args.output_dir}")
|
|
print(f"Target sequence length: {args.target_len}")
|
|
print(f"Padding mode: {args.pad_mode}")
|
|
print(f"Padding location: {args.pad_location}")
|
|
print("-" * 40)
|
|
|
|
# 1. 确保输出目录存在
|
|
os.makedirs(args.output_dir, exist_ok=True)
|
|
|
|
# 2. 获取所有输入文件
|
|
try:
|
|
file_list = [f for f in os.listdir(
|
|
args.input_dir) if f.endswith('.pkl')]
|
|
if not file_list:
|
|
print(f"Error: No .pkl files found in {args.input_dir}")
|
|
return
|
|
print(f"Found {len(file_list)} files to process.")
|
|
except FileNotFoundError:
|
|
print(f"Error: Input directory not found at {args.input_dir}")
|
|
return
|
|
|
|
# 3. 遍历并处理每个文件
|
|
for filename in tqdm(file_list, desc="Processing files"):
|
|
input_path = os.path.join(args.input_dir, filename)
|
|
output_path = os.path.join(args.output_dir, filename)
|
|
|
|
process_file(input_path, output_path, args.target_len,
|
|
args.pad_mode, args.pad_location)
|
|
|
|
print("-" * 40)
|
|
print("Preprocessing finished successfully!")
|
|
print(f"Processed data saved to: {args.output_dir}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
args = get_args_parser().parse_args()
|
|
main(args)
|