ttvnet / test_save.py
RRFRRF's picture
修改钩子机制 修改训练文件保存格式
d5dac94
import os
import numpy as np
import torch
from pathlib import Path
def test_saved_files(content_path, num_epochs=3):
"""测试保存的文件是否符合要求
Args:
content_path: 训练过程的根目录
num_epochs: 要测试的epoch数量
"""
# 检查目录结构
required_dirs = [
'model',
'dataset/representation',
'dataset/prediction',
'dataset/label'
]
for dir_path in required_dirs:
full_path = os.path.join(content_path, dir_path)
if not os.path.exists(full_path):
print(f"错误: 目录不存在: {full_path}")
return False
# 检查模型文件
print("\n检查模型文件...")
for epoch in range(1, num_epochs + 1):
model_path = os.path.join(content_path, 'model', f'{epoch}.pth')
if not os.path.exists(model_path):
print(f"错误: 模型文件不存在: {model_path}")
return False
try:
# 尝试加载模型文件以验证其有效性
state_dict = torch.load(model_path, map_location='cpu')
print(f"✓ {epoch}.pth 格式正确")
except Exception as e:
print(f"错误: 无法加载模型文件 {model_path}: {str(e)}")
return False
# 检查特征向量文件
print("\n检查特征向量文件...")
prev_samples = None
for epoch in range(1, num_epochs + 1):
repr_path = os.path.join(content_path, 'dataset', 'representation', f'{epoch}.npy')
if not os.path.exists(repr_path):
print(f"错误: 特征向量文件不存在: {repr_path}")
return False
try:
features = np.load(repr_path)
samples, dim = features.shape
if not (512 <= dim <= 1024):
print(f"警告: 特征维度 {dim} 不在预期范围[512, 1024]内")
if prev_samples is not None and samples != prev_samples:
print(f"错误: epoch {epoch} 的样本数量与之前不一致")
return False
prev_samples = samples
print(f"✓ {epoch}.npy 格式正确 [样本数: {samples}, 特征维度: {dim}]")
except Exception as e:
print(f"错误: 无法加载特征向量文件 {repr_path}: {str(e)}")
return False
# 检查预测结果文件
print("\n检查预测结果文件...")
for epoch in range(1, num_epochs + 1):
pred_path = os.path.join(content_path, 'dataset', 'prediction', f'{epoch}.npy')
if not os.path.exists(pred_path):
print(f"错误: 预测结果文件不存在: {pred_path}")
return False
try:
predictions = np.load(pred_path)
samples, classes = predictions.shape
if samples != prev_samples:
print(f"错误: 预测结果的样本数量与特征向量不一致")
return False
if classes != 10: # CIFAR-10 有10个类别
print(f"警告: 类别数量 {classes} 不等于10")
print(f"✓ {epoch}.npy 格式正确 [样本数: {samples}, 类别数: {classes}]")
except Exception as e:
print(f"错误: 无法加载预测结果文件 {pred_path}: {str(e)}")
return False
# 检查标签文件
print("\n检查标签文件...")
label_path = os.path.join(content_path, 'dataset', 'label', 'labels.npy')
if not os.path.exists(label_path):
print(f"错误: 标签文件不存在: {label_path}")
return False
try:
labels = np.load(label_path)
if len(labels.shape) != 1:
print(f"错误: 标签文件维度不正确,应为1维数组,实际为{len(labels.shape)}维")
return False
if labels.shape[0] != prev_samples:
print(f"错误: 标签数量与样本数量不一致")
return False
if not np.all((labels >= 0) & (labels < 10)): # CIFAR-10 的标签范围是0-9
print("错误: 存在超出范围的标签值")
return False
print(f"✓ labels.npy 格式正确 [样本数: {labels.shape[0]}]")
except Exception as e:
print(f"错误: 无法加载标签文件 {label_path}: {str(e)}")
return False
print("\n✓ 所有文件格式检查通过!")
return True
if __name__ == "__main__":
# 设置要测试的目录路径
content_path = "/home/ruofei/RRF/ttvnet/Image/AlexNet/model/0"
# 运行测试
test_saved_files(content_path, num_epochs=44)