# from sentence_transformers import SentenceTransformer from sklearn.decomposition import PCA import matplotlib.pyplot as plt from matplotlib import font_manager as fm from matplotlib.font_manager import FontProperties import json import numpy as np from tqdm import tqdm import os # 字体设置 font_path = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf' font_bold_path = '/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf' fm.fontManager.addfont(font_path) fm.fontManager.addfont(font_bold_path) plt.rcParams['font.family'] = 'Arial' plt.rcParams['font.weight'] = 'bold' # 全局设置字体加粗 plt.rcParams['axes.labelweight'] = 'bold' # 坐标轴标签加粗 plt.rcParams['axes.titleweight'] = 'bold' # 标题加粗 bold_font = FontProperties(fname=font_bold_path, weight='bold') # 2. 文本数据 data_path = "/cpfs/user/chenziyang/LongBenchmark/eval/dataset/longbench_pro_final.json" data = json.load(open(data_path, "r", encoding="utf-8")) en_data = [] for item in data: if item["language"] == "English": en_data.append(item) data = en_data print(len(data)) # 提取文本和类别 texts = [item["question_nonthinking"] + "\n" + "\n".join(item["answer"]) for item in data] labels = [item["primary_task"].split(".")[0] for item in data] languages = [item["language"] for item in data] label_array = np.array(labels) # 3. 编码文本 → embedding(逐个编码,显示进度条) embeddings_path = "/cpfs/user/chenziyang/LongBenchmark/draw/images/similarity_embeddings_en.npy" if os.path.exists(embeddings_path): embeddings = np.load(embeddings_path) print(f"Loaded embeddings from {embeddings_path}") else: # 1. 加载模型 model = SentenceTransformer( "/cpfs/user/chenziyang/LongBenchmark/eval/model/Qwen3-Embedding-8B", tokenizer_kwargs={"padding_side": "left"}, ) os.makedirs(os.path.dirname(embeddings_path), exist_ok=True) embeddings = [] for text in tqdm(texts, desc="Encoding texts"): embedding = model.encode(text, convert_to_numpy=True) embeddings.append(embedding) embeddings = np.array(embeddings) np.save(embeddings_path, embeddings) print(f"Saved embeddings to {embeddings_path}") print("Embedding shape:", embeddings.shape) # 4. 计算类别中心并剔除离群点 unique_labels = np.unique(label_array) class_centers = {} keep_mask = np.ones(len(embeddings), dtype=bool) outlier_percentile = 50 for label in unique_labels: idx = np.where(label_array == label)[0] if len(idx) == 0: continue class_embeddings = embeddings[idx] center = class_embeddings.mean(axis=0) class_centers[label] = center if len(idx) < 5: continue # 样本太少,不做离群点剔除 distances = np.linalg.norm(class_embeddings - center, axis=1) threshold = np.percentile(distances, outlier_percentile) outliers = idx[distances > threshold] keep_mask[outliers] = False removed_ratio = (~keep_mask).sum() / len(embeddings) print(f"Removed {(~keep_mask).sum()} outliers ({removed_ratio:.2%}) using {100 - outlier_percentile}% tail cutoff.") print("Sample class centers (first 3 dims):") for label in unique_labels: preview = class_centers[label][:3] if label in class_centers else [] print(f" {label}: {preview}") embeddings_filtered = embeddings[keep_mask] label_array_filtered = label_array[keep_mask] print("Filtered embedding shape:", embeddings_filtered.shape) # 5. PCA 降维:仅 3D pca_3d = PCA(n_components=3) points_3d = pca_3d.fit_transform(embeddings_filtered) # 6. 获取所有唯一的类别,并按T1, T2, ..., T11排序 filtered_unique_labels = list(set(label_array_filtered)) # 按照T1, T2, ..., T11的顺序排序 def sort_key(label): if label.startswith('T') and label[1:].isdigit(): return int(label[1:]) return 999 # 非T开头的标签排在最后 filtered_unique_labels = sorted(filtered_unique_labels, key=sort_key) num_classes = len(filtered_unique_labels) # 7. 为每个类别分配颜色 colors = plt.cm.tab20(np.linspace(0, 1, num_classes)) label_to_color = {label: colors[i] for i, label in enumerate(filtered_unique_labels)} # 为T11指定特定颜色 if "T11" in label_to_color: label_to_color["T11"] = "#FF6B6B" # 使用红色系颜色 # 8. 创建三个2D平面投影图:XY, XZ, YZ # 计算数据点的实际范围 x_min, x_max = points_3d[:, 0].min(), points_3d[:, 0].max() y_min, y_max = points_3d[:, 1].min(), points_3d[:, 1].max() z_min, z_max = points_3d[:, 2].min(), points_3d[:, 2].max() # 计算范围的中心和大小 x_center, y_center, z_center = (x_min + x_max) / 2, (y_min + y_max) / 2, (z_min + z_max) / 2 x_range, y_range, z_range = x_max - x_min, y_max - y_min, z_max - z_min # 使用最大范围来保持等比例,并添加5%的边距 max_range = max(x_range, y_range, z_range) * 1.05 half_range = max_range / 2 # 创建图形,1行3列,横向排列 fig = plt.figure(figsize=(16, 6)) axes = [] # 定义三个平面的投影 projections = [ ("XY", 0, 1, "X", "Y"), # XY平面 ("XZ", 0, 2, "X", "Z"), # XZ平面 ("YZ", 1, 2, "Y", "Z"), # YZ平面 ] # 创建三个子图 for i, (plane_name, dim1, dim2, label1, label2) in enumerate(projections, 1): ax = fig.add_subplot(1, 3, i) axes.append(ax) # 绘制散点图 for label in filtered_unique_labels: mask = label_array_filtered == label ax.scatter( points_3d[mask, dim1], points_3d[mask, dim2], s=10, c=[label_to_color[label]], alpha=0.7, label=label, ) # 设置坐标轴范围 if dim1 == 0: # X轴 ax.set_xlim(x_center - half_range, x_center + half_range) elif dim1 == 1: # Y轴 ax.set_xlim(y_center - half_range, y_center + half_range) else: # Z轴 ax.set_xlim(z_center - half_range, z_center + half_range) if dim2 == 0: # X轴 ax.set_ylim(x_center - half_range, x_center + half_range) elif dim2 == 1: # Y轴 ax.set_ylim(y_center - half_range, y_center + half_range) else: # Z轴 ax.set_ylim(z_center - half_range, z_center + half_range) ax.set_xlabel(label1, fontsize=12, fontweight='bold', fontfamily='Arial') ax.set_ylabel(label2, fontsize=12, fontweight='bold', fontfamily='Arial') ax.tick_params(axis='both', which='both', labelsize=10, direction='out', length=4) ax.grid(True, alpha=0.3, linestyle='--') # 为每个子图添加标题 ax.set_title(f"{plane_name} Plane", fontsize=12, pad=10, fontweight='bold', fontfamily='Arial') # 创建共享图例 legend_handles = [ plt.Line2D( [0], [0], marker="o", color="w", label=label, markerfacecolor=label_to_color[label], markersize=8, ) for label in filtered_unique_labels ] legend = fig.legend( handles=legend_handles, loc="center left", bbox_to_anchor=(0.06, 0.5), ncol=1, fontsize=10, prop={'weight': 'bold', 'family': 'Arial'} ) legend.get_frame().set_edgecolor('#b0b0b0') legend.get_frame().set_linewidth(1.0) plt.tight_layout(rect=(0.12, 0, 1, 1)) plt.subplots_adjust(wspace=0.4) plt.savefig( "/cpfs/user/chenziyang/LongBenchmark/draw/images/similarity_scatter_3d_en.png", dpi=400, bbox_inches="tight", ) plt.close()