250 lines
10 KiB
Python
250 lines
10 KiB
Python
import os
|
|
import pickle
|
|
import argparse
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn.functional as F
|
|
from torch.utils.data import Dataset, DataLoader
|
|
from tqdm import tqdm
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sns
|
|
from sklearn.manifold import TSNE
|
|
# 如果您安装了 umap-learn,UMAP通常更快且效果更好
|
|
# from umap import UMAP
|
|
# from torch.serialization import add_safe_globals # 导入安全列表函数
|
|
# -----------------------------------------------------------------------------
|
|
# 重要:从您的项目中复制必要的模块定义
|
|
# 为了让此脚本独立运行,我们需要NormWear和MoCo的类定义。
|
|
# 请确保这些类的代码与您训练时使用的版本完全一致。
|
|
# -----------------------------------------------------------------------------
|
|
from NormWear.modules.normwear import NormWear
|
|
from NormWear.modules.patch_embed import HybridPatchEmbed
|
|
from NormWear.modules.custom_blocks import OneD_CNN_Extractor, ConvEnhancedBlock
|
|
|
|
from NormWear.modules.normwear import NormWear, MoCo
|
|
# 确保 patch_embed 的导入也是最新的
|
|
from NormWear.modules.patch_embed import PatchEmbed_new, HybridPatchEmbed
|
|
import sys
|
|
# 这是一个小技巧,确保argparse被正确加载
|
|
# sys.modules['argparse'] = argparse
|
|
# add_safe_globals([argparse.Namespace])
|
|
# -----------------------------------------------------------------------------
|
|
# 复制CWT辅助函数
|
|
# 因为数据预处理需要在加载时实时进行
|
|
# -----------------------------------------------------------------------------
|
|
def ricker_wavelet(points, scale):
|
|
A = 2 / (torch.sqrt(3 * scale) * (np.pi**0.25))
|
|
wsq = scale**2
|
|
device = scale.device if isinstance(scale, torch.Tensor) else 'cpu'
|
|
vec = torch.arange(0, points, device=device) - (points - 1.0) / 2
|
|
xsq = vec**2
|
|
mod = (1 - xsq / wsq)
|
|
gauss = torch.exp(-xsq / (2 * wsq))
|
|
return A * mod * gauss
|
|
|
|
def cwt_ricker(x, scales, wavelet_len):
|
|
batch_size, sequence_length = x.shape
|
|
x = x.unsqueeze(1)
|
|
num_scales = scales.shape[0]
|
|
scales = scales.to(x.device)
|
|
effective_wavelet_len = min(wavelet_len, sequence_length)
|
|
wavelets = torch.stack([ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
|
wavelets = wavelets.view(num_scales, 1, -1)
|
|
cwt_output = F.conv1d(x, wavelets, padding='same')
|
|
return cwt_output
|
|
|
|
def cwt_wrap(x, scales):
|
|
n_var, L = x.shape
|
|
d1 = x[:, 1:] - x[:, :-1]
|
|
d2 = d1[:, 1:] - d1[:, :-1]
|
|
original_x = x
|
|
d1_padded = F.pad(d1, (1, 0), 'replicate')
|
|
d2_padded = F.pad(d2, (2, 0), 'replicate')
|
|
stacked_x = torch.stack([original_x, d1_padded, d2_padded], dim=1)
|
|
n_var, n_channels, L_stacked = stacked_x.shape
|
|
flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
|
|
wavelet_len = 257
|
|
cwt_res = cwt_ricker(flat_x, scales, wavelet_len)
|
|
_, n_scales, _ = cwt_res.shape
|
|
final_cwt = cwt_res.reshape(n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
|
return final_cwt
|
|
|
|
# -----------------------------------------------------------------------------
|
|
# 专门用于可视化的数据集类
|
|
# -----------------------------------------------------------------------------
|
|
class VisualizationDataset(Dataset):
|
|
def __init__(self, data_dir, n_samples=None, img_size=(387, 65)):
|
|
self.data_dir = data_dir
|
|
self.file_list = sorted([f for f in os.listdir(data_dir) if f.endswith('.pkl')])
|
|
|
|
if n_samples is not None and n_samples < len(self.file_list):
|
|
import random
|
|
random.seed(42)
|
|
self.file_list = random.sample(self.file_list, n_samples)
|
|
|
|
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
|
print(f"Found {len(self.file_list)} pre-windowed samples in {data_dir}")
|
|
|
|
def __len__(self):
|
|
return len(self.file_list)
|
|
|
|
def __getitem__(self, idx):
|
|
file_path = os.path.join(self.data_dir, self.file_list[idx])
|
|
with open(file_path, 'rb') as f:
|
|
data = pickle.load(f)
|
|
|
|
# 1. 加载并标准化1D信号
|
|
signal_1d = torch.from_numpy(data['data']).float()
|
|
signal_1d = torch.nan_to_num(signal_1d, 0.0)
|
|
mean = torch.mean(signal_1d, dim=1, keepdim=True)
|
|
std = torch.std(signal_1d, dim=1, keepdim=True)
|
|
std[std == 0] = 1.0 # 增加保护
|
|
processed_signal_1d = (signal_1d - mean) / (std + 1e-8)
|
|
|
|
# 2. 进行CWT变换
|
|
cwt_image = cwt_wrap(processed_signal_1d, self.cwt_scales)
|
|
|
|
# 3. 提取标签
|
|
try:
|
|
label = data['label'][0]['class']
|
|
except (TypeError, KeyError):
|
|
label = data.get('label', 0)
|
|
|
|
# [修改] 返回两种模态的数据
|
|
return {
|
|
'input_cwt': cwt_image,
|
|
'input_1d': processed_signal_1d,
|
|
'label': label
|
|
}
|
|
|
|
# -----------------------------------------------------------------------------
|
|
# 主函数
|
|
# -----------------------------------------------------------------------------
|
|
def get_args_parser():
|
|
parser = argparse.ArgumentParser('NormWear MAE Embedding Visualization', add_help=False)
|
|
|
|
# --- 核心参数 ---
|
|
parser.add_argument('--checkpoint_path', required=True, type=str, help='Path to the pre-trained MAE model checkpoint (.pth file)')
|
|
parser.add_argument('--data_dir', required=True, type=str, help='Path to the directory containing pre-windowed .pkl files for visualization')
|
|
parser.add_argument('--output_path', required=True, type=str, help='Path to save the output visualization image (e.g., plot.png)')
|
|
|
|
# --- 模型架构参数 (必须与检查点中的模型一致) ---
|
|
parser.add_argument('--n_vars', type=int, required=True, help='Number of variables in the data.')
|
|
parser.add_argument('--max_len', type=int, default=387, help='Length of the time series window.')
|
|
parser.add_argument('--embed_dim', type=int, default=768)
|
|
parser.add_argument('--depth', type=int, default=12)
|
|
parser.add_argument('--num_heads', type=int, default=12)
|
|
parser.add_argument('--decoder_embed_dim', type=int, default=512)
|
|
parser.add_argument('--decoder_depth', type=int, default=8)
|
|
parser.add_argument('--decoder_num_heads', type=int, default=16)
|
|
parser.add_argument('--use_hybrid_embed', action='store_true', help='Set this flag if the model was trained with HybridPatchEmbed')
|
|
|
|
# --- 可视化控制参数 ---
|
|
parser.add_argument('--batch_size', type=int, default=128, help='Batch size for feature extraction')
|
|
parser.add_argument('--n_samples', type=int, default=2000, help='Number of samples to use for visualization.')
|
|
parser.add_argument('--title', type=str, default='t-SNE Visualization of MAE Pre-trained Embeddings', help='Title for the plot')
|
|
|
|
return parser
|
|
|
|
def main(args):
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
print(f"Using device: {device}")
|
|
|
|
# --- [核心修改] 1. 直接实例化 NormWear 模型 ---
|
|
print("Instantiating MAE model...")
|
|
# 我们不再需要MoCo,直接使用NormWear
|
|
feature_extractor = NormWear(
|
|
img_size=(args.max_len, 65),
|
|
patch_size=(9, 5),
|
|
in_chans=3,
|
|
embed_dim=args.embed_dim,
|
|
depth=args.depth,
|
|
num_heads=args.num_heads,
|
|
decoder_embed_dim=args.decoder_embed_dim,
|
|
decoder_depth=args.decoder_depth,
|
|
decoder_num_heads=args.decoder_num_heads,
|
|
use_hybrid_embed=args.use_hybrid_embed,
|
|
nvar=args.n_vars,
|
|
target_len=args.max_len
|
|
).to(device)
|
|
|
|
# --- [核心修改] 2. 加载 MAE 检查点 ---
|
|
print(f"Loading checkpoint from: {args.checkpoint_path}")
|
|
# 使用 weights_only=True 更安全
|
|
checkpoint = torch.load(args.checkpoint_path, map_location='cpu', weights_only=False)
|
|
|
|
# MAE检查点通常直接保存模型state_dict在'model'键下
|
|
state_dict = checkpoint['model']
|
|
|
|
# 使用 strict=False 更稳健,可以忽略解码器等无关部分的权重
|
|
msg = feature_extractor.load_state_dict(state_dict, strict=False)
|
|
print("Model loading message:", msg)
|
|
|
|
feature_extractor.eval() # 设置为评估模式
|
|
|
|
# --- 3. 准备数据 (不变) ---
|
|
dataset = VisualizationDataset(args.data_dir, n_samples=args.n_samples, img_size=(args.max_len, 65))
|
|
data_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=4)
|
|
|
|
# --- 4. 提取所有样本的特征 ---
|
|
print("Extracting features from all samples...")
|
|
all_embeddings = []
|
|
all_labels = []
|
|
|
|
# [修改] 推理时禁用梯度
|
|
with torch.no_grad():
|
|
for batch in tqdm(data_loader, desc="Feature Extraction"):
|
|
inputs_cwt = batch['input_cwt'].to(device, non_blocking=True)
|
|
inputs_1d = batch['input_1d'].to(device, non_blocking=True)
|
|
labels = batch['label']
|
|
|
|
# [核心修改] 调用我们为推理设计的、统一的 get_signal_embedding 接口
|
|
features = feature_extractor.get_signal_embedding(
|
|
x_cwt=inputs_cwt,
|
|
x_1d=inputs_1d
|
|
)
|
|
|
|
# 聚合特征:使用CLS token
|
|
# features 形状: [bs, n_vars, num_patches+1, embed_dim]
|
|
cls_tokens = features[:, :, 0, :] # [bs, n_vars, embed_dim]
|
|
|
|
# 将所有变量的CLS token取平均,作为最终的样本表示
|
|
embedding = torch.mean(cls_tokens, dim=1)
|
|
|
|
all_embeddings.append(embedding.cpu().numpy())
|
|
all_labels.extend(labels.numpy())
|
|
|
|
all_embeddings = np.concatenate(all_embeddings, axis=0)
|
|
all_labels = np.array(all_labels)
|
|
print(f"Extracted {all_embeddings.shape[0]} embeddings of dimension {all_embeddings.shape[1]}")
|
|
|
|
# --- 5. 使用t-SNE进行降维 (不变) ---
|
|
print("Performing dimensionality reduction using t-SNE...")
|
|
tsne = TSNE(n_components=2, verbose=1, perplexity=40, max_iter=1000, random_state=42)
|
|
reduced_embeddings = tsne.fit_transform(all_embeddings)
|
|
print("t-SNE finished.")
|
|
|
|
# 6. 绘制并保存图像
|
|
print(f"Plotting results and saving to {args.output_path}")
|
|
plt.figure(figsize=(12, 10))
|
|
sns.scatterplot(
|
|
x=reduced_embeddings[:, 0],
|
|
y=reduced_embeddings[:, 1],
|
|
hue=all_labels,
|
|
palette=sns.color_palette("hsv", len(np.unique(all_labels))),
|
|
legend="full",
|
|
alpha=0.8
|
|
)
|
|
plt.title(args.title)
|
|
plt.xlabel("t-SNE Component 1")
|
|
plt.ylabel("t-SNE Component 2")
|
|
plt.legend(title="Classes")
|
|
plt.grid(True)
|
|
|
|
plt.savefig(args.output_path, dpi=300)
|
|
print("Visualization saved successfully!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
args = get_args_parser().parse_args()
|
|
main(args) |