DAY 39 图像数据与显存

知识点回顾

  1. 图像数据的格式:灰度和彩色数据
  2. 模型的定义
  3. 显存占用的4种地方
    1. 模型参数+梯度参数
    2. 优化器参数
    3. 数据批量所占显存
    4. 神经元输出中间状态

在这里,我对之前复现的项目进行了改进

复制代码
# 导入必要库:文件操作、随机数、数值计算、TensorFlow
import glob
import os.path
import random
import numpy as np
import tensorflow as tf
from tensorflow.io.gfile import GFile

# -------------------------- 常量定义 --------------------------
BOTTLENECK_TENSOR_SIZE = 2048
BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'
JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'

MODEL_DIR = r"E:\项目学习内容\迁移学习\time1数据集\inception-2015-12-05 (1)\\"
os.makedirs(MODEL_DIR, exist_ok=True)
MODEL_FILE = 'tensorflow_inception_graph.pb'
CACHE_DIR = './images/tmp/bottleneck/'
os.makedirs(CACHE_DIR, exist_ok=True)
INPUT_DATA = r"E:\项目学习内容\迁移学习\time1数据集\time11\GC10-DET\data"

VALIDATION_PERCENTAGE = 10
TEST_PERCENTAGE = 10

LEARNING_RATE = 0.01
STEPS = 4000
BATCH = 100

# 焦点损失参数
GAMMA = 2.0  # 调节因子
ALPHA = 0.25  # 平衡因子

# -------------------------- 数据预处理函数(添加过采样) --------------------------
def create_image_lists(testing_percentage, validation_percentage):
    """功能:读取数据集并按比例划分,添加过采样解决不平衡问题"""
    result = {}
    sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]
    is_root_dir = True
    for sub_dir in sub_dirs:
        if is_root_dir:
            is_root_dir = False
            continue
        
        extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']
        file_list = []
        dir_name = os.path.basename(sub_dir)
        for extension in extensions:
            file_glob = os.path.join(INPUT_DATA, dir_name, f'*.{extension}')
            file_list.extend(glob.glob(file_glob))
        if not file_list:
            continue
            
        label_name = dir_name.lower()
        training_images = []
        testing_images = []
        validation_images = []
        for file_name in file_list:
            base_name = os.path.basename(file_name)
            chance = np.random.randint(100)
            if chance < validation_percentage:
                validation_images.append(base_name)
            elif chance < (testing_percentage + validation_percentage):
                testing_images.append(base_name)
            else:
                training_images.append(base_name)
                
        result[label_name] = {
            'dir': dir_name,
            'training': training_images,
            'testing': testing_images,
            'validation': validation_images
        }
    
    # 添加过采样:平衡训练集
    max_training_count = max(len(v['training']) for v in result.values())
    
    for label_name, data in result.items():
        training_count = len(data['training'])
        if training_count < max_training_count:
            # 计算需要过采样的数量
            oversample_count = max_training_count - training_count
            # 随机复制现有样本(过采样)
            data['training'].extend(random.choices(data['training'], k=oversample_count))
    
    # 打印各类别样本数(调试用)
    print("\n数据集类别分布(过采样后):")
    for label, data in result.items():
        print(f"类别 {label}: 训练集={len(data['training'])}张, 验证集={len(data['validation'])}张, 测试集={len(data['testing'])}张")
    
    return result

def get_image_path(image_lists, image_dir, label_name, index, category):
    label_lists = image_lists[label_name]
    category_list = label_lists[category]
    mod_index = index % len(category_list)
    base_name = category_list[mod_index]
    sub_dir = label_lists['dir']
    return os.path.join(image_dir, sub_dir, base_name)

def get_bottleneck_path(image_lists, label_name, index, category):
    return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt'

# -------------------------- 迁移学习核心 --------------------------
def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor):
    bottleneck_values = sess.run(bottleneck_tensor, feed_dict={image_data_tensor: image_data})
    return np.squeeze(bottleneck_values)

def get_or_create_bottleneck(sess, image_lists, label_name, index, category, jpeg_data_tensor, bottleneck_tensor):
    label_lists = image_lists[label_name]
    sub_dir = label_lists['dir']
    sub_dir_path = os.path.join(CACHE_DIR, sub_dir)
    os.makedirs(sub_dir_path, exist_ok=True)
    
    bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)
    if os.path.exists(bottleneck_path):
        with open(bottleneck_path, 'r') as f:
            bottleneck_string = f.read()
        return [float(x) for x in bottleneck_string.split(',')]
    
    image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category)
    with GFile(image_path, 'rb') as f:
        image_data = f.read()
    
    bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)
    
    bottleneck_string = ','.join(str(x) for x in bottleneck_values)
    with open(bottleneck_path, 'w') as f:
        f.write(bottleneck_string)
        
    return bottleneck_values

def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category, jpeg_data_tensor, bottleneck_tensor):
    bottlenecks = []
    ground_truths = []
    for _ in range(how_many):
        label_index = random.randrange(n_classes)
        label_name = list(image_lists.keys())[label_index]
        image_index = random.randrange(65536)
        bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, image_index, category,
                                             jpeg_data_tensor, bottleneck_tensor)
        ground_truth = np.zeros(n_classes, dtype=np.float32)
        ground_truth[label_index] = 1.0
        bottlenecks.append(bottleneck)
        ground_truths.append(ground_truth)
    return np.array(bottlenecks), np.array(ground_truths)

def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):
    bottlenecks = []
    ground_truths = []
    label_name_list = list(image_lists.keys())
    for label_index, label_name in enumerate(label_name_list):
        category = 'testing'
        for index in range(len(image_lists[label_name][category])):
            bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,
                                                 jpeg_data_tensor, bottleneck_tensor)
            ground_truth = np.zeros(n_classes, dtype=np.float32)
            ground_truth[label_index] = 1.0
            bottlenecks.append(bottleneck)
            ground_truths.append(ground_truth)
    return np.array(bottlenecks), np.array(ground_truths)

# -------------------------- 焦点损失函数 --------------------------
def focal_loss(labels, logits, class_weights, gamma=GAMMA, alpha=ALPHA):
    """焦点损失实现,解决类别不平衡问题"""
    # 计算softmax概率
    probs = tf.nn.softmax(logits)
    
    # 计算焦点因子
    p_t = tf.reduce_sum(labels * probs, axis=1)
    modulating_factor = tf.pow(1.0 - p_t, gamma)
    
    # 计算类别权重
    alpha_factor = tf.reduce_sum(labels * class_weights, axis=1)
    
    # 计算交叉熵
    ce = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)
    
    # 组合焦点损失
    focal_loss = alpha_factor * modulating_factor * ce
    return tf.reduce_mean(focal_loss)

# -------------------------- 主函数 --------------------------
def main(_):
    # 1. 加载数据集(已添加过采样)
    image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)
    n_classes = len(image_lists.keys())
    if n_classes == 0:
        raise ValueError(f"目标域数据集路径 {INPUT_DATA} 下无类别文件夹,请检查!")
    
    # 2. 计算类权重(用于焦点损失)
    class_counts = {label: len(image_lists[label]['training']) for label in image_lists}
    total_samples = sum(class_counts.values())
    class_weights = [total_samples / (n_classes * class_counts[label]) for label in image_lists]
    class_weights_tensor = tf.constant([class_weights], dtype=tf.float32)
    print("\n类权重(用于焦点损失):")
    for label, weight in zip(image_lists.keys(), class_weights):
        print(f"类别 {label}: 权重 = {weight:.2f}")
    
    # 3. 加载预训练模型
    model_path = os.path.join(MODEL_DIR, MODEL_FILE)
    if not os.path.exists(model_path):
        raise FileNotFoundError(f"源域模型 {model_path} 不存在,请下载并放置到该路径!")
    
    with GFile(model_path, 'rb') as f:
        graph_def = tf.compat.v1.GraphDef()
        graph_def.ParseFromString(f.read())
    
    with tf.compat.v1.Session() as sess:
        # 导入源域模型
        bottleneck_tensor, jpeg_data_tensor = tf.compat.v1.import_graph_def(
            graph_def, 
            return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME]
        )
        
        # 4. 定义目标域模型
        bottleneck_input = tf.compat.v1.placeholder(
            tf.float32, [None, BOTTLENECK_TENSOR_SIZE], 
            name='BottleneckInputPlaceholder'
        )
        
        ground_truth_input = tf.compat.v1.placeholder(
            tf.float32, [None, n_classes], 
            name='GroundTruthInput'
        )
        
        # 模型结构
        with tf.compat.v1.name_scope('final_training_ops'):
            weights = tf.compat.v1.Variable(tf.random.truncated_normal(
                [BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001
            ))
            biases = tf.compat.v1.Variable(tf.zeros([n_classes]))
            logits = tf.matmul(bottleneck_input, weights) + biases
            final_tensor = tf.nn.softmax(logits)
        
        # 5. 使用焦点损失代替标准交叉熵
        cross_entropy_mean = focal_loss(
            ground_truth_input, 
            logits, 
            class_weights_tensor,
            gamma=GAMMA,
            alpha=ALPHA
        )
        
        # 6. 动态学习率(指数衰减)
        global_step = tf.compat.v1.train.get_or_create_global_step()
        learning_rate = tf.compat.v1.train.exponential_decay(
            LEARNING_RATE, 
            global_step, 
            1000,  # 每1000步衰减一次
            0.96,  # 衰减率
            staircase=True  # 阶梯式衰减
        )
        
        # 使用Adam优化器
        optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)
        train_step = optimizer.minimize(cross_entropy_mean, global_step=global_step)
        
        # 7. 评估指标
        with tf.compat.v1.name_scope('evaluation'):
            correct_prediction = tf.equal(
                tf.argmax(final_tensor, 1), 
                tf.argmax(ground_truth_input, 1)
            )
            evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        
        # 初始化变量
        sess.run(tf.compat.v1.global_variables_initializer())
        
        # 8. 训练循环
        print("\n开始训练...")
        best_validation_acc = 0.0
        
        for i in range(STEPS):
            # 获取训练批次
            train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(
                sess, n_classes, image_lists, BATCH, 'training', 
                jpeg_data_tensor, bottleneck_tensor
            )
            
            # 执行训练
            _, current_lr = sess.run([train_step, learning_rate], feed_dict={
                bottleneck_input: train_bottlenecks,
                ground_truth_input: train_ground_truth
            })
            
            # 定期评估验证集
            if i % 100 == 0 or i + 1 == STEPS:
                validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(
                    sess, n_classes, image_lists, BATCH, 'validation', 
                    jpeg_data_tensor, bottleneck_tensor
                )
                
                validation_acc = sess.run(evaluation_step, feed_dict={
                    bottleneck_input: validation_bottlenecks,
                    ground_truth_input: validation_ground_truth
                })
                
                # 保存最佳模型(可选)
                if validation_acc > best_validation_acc:
                    best_validation_acc = validation_acc
                
                print(f"Step {i:4d}: 验证集准确率 = {validation_acc*100:.1f}% | "
                      f"学习率 = {current_lr:.6f} | "
                      f"最佳验证准确率 = {best_validation_acc*100:.1f}%")
        
        # 9. 最终测试
        test_bottlenecks, test_ground_truth = get_test_bottlenecks(
            sess, image_lists, n_classes, 
            jpeg_data_tensor, bottleneck_tensor
        )
        
        test_acc = sess.run(evaluation_step, feed_dict={
            bottleneck_input: test_bottlenecks,
            ground_truth_input: test_ground_truth
        })
        
        print(f"\n最终测试集准确率 = {test_acc*100:.1f}%")

# -------------------------- 程序入口 --------------------------
if __name__ == '__main__':
    tf.compat.v1.app.run(main=main)

@浙大疏锦行

相关推荐
yumgpkpm3 小时前
数据可视化AI、BI工具,开源适配 Cloudera CMP 7.3(或类 CDP 的 CMP 7.13 平台,如华为鲲鹏 ARM 版)值得推荐?
人工智能·hive·hadoop·信息可视化·kafka·开源·hbase
亚马逊云开发者3 小时前
通过Amazon Q CLI 集成DynamoDB MCP 实现游戏场景智能数据建模
人工智能
nix.gnehc3 小时前
PyTorch
人工智能·pytorch·python
J_Xiong01173 小时前
【VLNs篇】17:NaVid:基于视频的VLM规划视觉语言导航的下一步
人工智能·机器人
小殊小殊3 小时前
【论文笔记】视频RAG-Vgent:基于图结构的视频检索推理框架
论文阅读·人工智能·深度学习
IT_陈寒3 小时前
Vite 5.0实战:10个你可能不知道的性能优化技巧与插件生态深度解析
前端·人工智能·后端
大模型真好玩3 小时前
LangChain1.0实战之多模态RAG系统(二)——多模态RAG系统图片分析与语音转写功能实现
人工智能·langchain·mcp
机器之心4 小时前
智能体&编程新王Claude Opus 4.5震撼登场,定价大降2/3
人工智能·openai
小殊小殊4 小时前
【论文笔记】知识蒸馏的全面综述
人工智能·算法·机器学习