【StratifiedKFold】分层抽样数据集来减少训练时长

以TubeR来说明:

ANNO_PATH: '/data1/ws/Tubelet-transformer/datasets/assets/my_ava_{}_v22.json'
train_bbox_json = json.load(open(cfg.CONFIG.DATA.ANNO_PATH.format("train")))
train_video_frame_bbox, train_frame_keys_list = train_bbox_json["video_frame_bbox"], train_bbox_json["frame_keys_list"]

在这里插入图片描述
也就是说,找到dataloader下的训练文件来源,我们对这个文件进行分层抽样。

1. 查询原配置文件信息

import json
import pandas as pd

train_bbox_json = json.load(open('/data1/ws/Tubelet-transformer/datasets/assets/ava_train_v22.json'))
train_video_frame_bbox, train_frame_keys_list = train_bbox_json["video_frame_bbox"], train_bbox_json["frame_keys_list"]
"""
train_bbox_json: 
video_frame_bbox: 'zlVkeKC6Ha8,1782': {'bboxes': [[0.042, 0.046, 0.97, 0.98]], 'acts': [[10, 73, 79]]},
frame_keys_list:  'zlVkeKC6Ha8,1782'
"""
print(list(train_bbox_json)[:2])
print(list(train_video_frame_bbox.items())[:2]) 
print(list(train_frame_keys_list)[:2]) 

['video_frame_bbox', 'frame_keys_list']
[('-5KQ66BBWC4,0902', {'bboxes': [[0.077, 0.151, 0.28300000000000003, 0.8109999999999999], [0.332, 0.19399999999999998, 0.48100000000000004, 0.8909999999999999], [0.505, 0.105, 0.653, 0.78], [0.626, 0.146, 0.805, 0.818], [0.805, 0.222, 0.997, 1.0]], 'acts': [[79, 8], [79, 8], [8], [8], [79, 8]]}), ('-5KQ66BBWC4,0903', {'bboxes': [[0.0, 0.162, 0.177, 0.804], [0.141, 0.158, 0.298, 0.825], [0.32799999999999996, 0.182, 0.484, 0.895], [0.507, 0.147, 0.6659999999999999, 0.789], [0.642, 0.158, 0.7909999999999999, 0.8590000000000001], [0.785, 0.15, 0.8859999999999999, 0.703], [0.802, 0.267, 0.9940000000000001, 0.971], [0.865, 0.158, 0.991, 0.436]], 'acts': [[79, 8], [11, 79], [79, 8], [79, 8], [8], [11, 79], [79, 8], [79, 8]]})]
['D8Vhxbho1fY,1798', 'PcFEhUKhN6g,1408']

2. 分层抽样 StratifiedKFold

from sklearn.model_selection import StratifiedGroupKFold
import pandas as pd

# Load the data from the csv file
data = pd.read_csv('/data1/ws/Tubelet-transformer/datasets/assets/ava_val_v2.2.csv')

# Get the target variable
target = data.iloc[:, -2]

# Create the StratifiedKFold object
skf = StratifiedGroupKFold(n_splits=10, shuffle=True, random_state=42)

# Get the indices of the samples to keep
_, indices = next(skf.split(data, target, groups=data.iloc[:, 0]))

# Keep only the selected samples
selected_data = data.iloc[indices]

# Save the selected samples to a new csv file
selected_data.to_csv('/data1/ws/Tubelet-transformer/datasets/selected_val_data.csv', index=False)

80万条数据变为8万。
在这里插入图片描述

/data1/ws/anaconda3/envs/pytorch/lib/python3.11/site-packages/sklearn/model_selection/_split.py:737: UserWarning: The least populated class in y has only 7 members, which is less than n_splits=10.
warnings.warn(
/data1/ws/anaconda3/envs/pytorch/lib/python3.11/site-packages/sklearn/model_selection/_split.py:737: UserWarning: The least populated class in y has only 3 members, which is less than n_splits=10.
warnings.warn(
UserWarning: y 中填充最少的类只有 3 个成员,小于 n_splits= 10.
警告.警告(

3. 清理数据 (除0和删最后一列)

最后一列数据是person id,我们任务中不需要。

import pandas as pd

original_data = pd.read_csv('/data1/ws/Tubelet-transformer/datasets/selected_data.csv')

# 删除最后一列为0的数据
filtered_data = original_data.loc[original_data.iloc[:, -1] != 0]
filtered_data.to_csv('/data1/ws/Tubelet-transformer/datasets/2.csv', index=False)

# 再删除最后一列数据
df = filtered_data.iloc[:, :-1]
df.to_csv('/data1/ws/Tubelet-transformer/datasets/3.csv', index=False)

在这里插入图片描述
在这里插入图片描述

4. video_frame_bbox键生成

import json
import csv


# 读取CSV文件并转化为字典
def csv_to_dict(csv_file):
    result_dict = {}
    with open(csv_file, 'r') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            if len(row) >= 7:
                video_id, time, *bbox_data = row[:6]
                categories = [int(category)-1 for category in row[6:]]
                frame_key = f"{video_id},{time}"
                if frame_key in result_dict:
                    result_dict[frame_key]["bboxes"].append([float(coord) for coord in bbox_data])
                    result_dict[frame_key]["acts"].extend(categories)
                else:
                    result_dict[frame_key] = {
                        "bboxes": [[float(coord) for coord in bbox_data]],
                        "acts": categories
                    }
    # Ensure each category is in its own list
    for key, value in result_dict.items():
        result_dict[key]["acts"] = [[category] for category in value["acts"]]
        bboxes = value["bboxes"]
        for i in range(len(bboxes)):
            if bboxes[i] in bboxes[i+1:]:
                # print(f"Duplicate bbox found at index {i} in {key}")
                result_dict[key]["acts"][i] + result_dict[key]["acts"][i+1]

    return result_dict


# 保存字典为JSON文件
def save_to_json(data, output_file):
    import json
    with open(output_file, 'w') as jsonfile:
        json.dump(data, jsonfile, indent=4)

# 输入的CSV文件路径
csv_file_path = '/data1/ws/Tubelet-transformer/datasets/3.csv'

# 转化为字典
result_dict = csv_to_dict(csv_file_path)

# # 删除键中重复的字典
# for key, value in result_dict.items():
#     value['bboxes'] = list(set(tuple(box) for box in value['bboxes']))
    
print(result_dict)
# print(len(result_dict))
with open('video_frame_bbox.txt', 'w') as f:
    f.write(str(result_dict))

save_to_json(result_dict, 'video_frame_bbox.json')

在这里插入图片描述

5. frame_keys_list

import csv

csv_file = '/data1/ws/Tubelet-transformer/datasets/3.csv'
data_dict = {}

with open(csv_file, 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)  # Skip the header row if present
    for row in csv_reader:
        key = row[0] + "," + row[1]
        if key not in data_dict:
            data_dict[key] = [float(val) for val in row[2:]]
        else:
            result_dict = {"frame_keys_list": [key for key in data_dict]}
# print(result_dict)

with open('result_dict.txt', 'w') as f:
    f.write(str(result_dict))

在这里插入图片描述

把单引号变成双引号!

6. 粘贴复制到源文件

在这里插入图片描述
在这里插入图片描述

<think>好的,我现在需要帮用户生成一个结合交叉验证和随机森林进行微阵列基因数据特征选择的Python代码。首先,我得理清楚用户的需求。用户提到要利用交叉验证准则与随机森林结合,先划分数据集训练模型,进行特征选择,计算每折的基尼系数,调整树的数量和节点最小大小,找到最佳参数,然后测试不同特征数量在测试集上的准确率,生成折线图,最后可视化特征重要度。 首先,我需要确认用户的数据是什么样的。微阵列基因数据通常具有高维度,特征数量远大于样本数,所以特征选择非常重要。用户可能希望减少特征数量,同时保持或提高模型的准确性。用户可能对交叉验证的具体步骤不太清楚,需要详细说明如何划分数据集,尤其是交叉验证的部分。 接下来,用户提到在训练集上训练随机森林模型,进行特征选择。这里可能需要用到随机森林的特征重要性评估,比如基尼系数或平均不纯度减少。用户要求计算每折的基尼系数,显示不同的树的数量和节点的最小大小,根据平均基尼系数找出最佳参数。这说明用户想要调参,找到随机森林的最佳超参数,比如n_estimators和min_samples_leaf。 然后,用户希望取不同的特征选择数量,在测试集上测试准确率,生成折线图来确定最佳特征数量。这可能涉及逐步选择最重要的特征,从高到低排序,然后取不同数量的特征子集,评估模型性能。最后,可视化特征重要度,可能需要条形图或热图。 我需要确保代码的结构正确,首先导入必要的库,如numpy、pandas、sklearn中的相关模块,以及matplotlib用于绘图。然后加载数据,划分训练集和测试集,可能使用StratifiedKFold进行分层交叉验证,保持类别分布。 参数调优部分,用户需要遍历不同的树的数量和节点最小样本数,使用交叉验证计算基尼系数的平均值。这可能涉及到嵌套交叉验证,外层是划分训练测试集,内层是参数网格搜索。不过用户可能希望手动实现,而不是用GridSearchCV,以便更灵活地记录结果。 特征选择阶段,根据特征重要性排序,选择前k个特征,然后在测试集上评估准确率。这里需要生成不同k值的准确率,并绘制折线图找到最佳k值。最后,将特征重要性进行可视化,可能需要选取前N个重要特征展示。 需要注意的地方包括数据预处理,比如标准化或归一化,但随机森林通常不需要。另外,处理高维数据时的计算效率,可能需要使用并行处理或适当调整步长。用户可能没有提到数据是否已经预处理,需要假设数据已经准备好,或者代码中包含简单的预处理步骤。 可能的陷阱包括过拟合,因为微阵列数据特征多,样本少,交叉验证的设置需要严谨。另外,计算时间可能较长,尤其是当特征数量很大时,遍历不同的k值可能需要优化。 最后,代码需要结构清晰,注释详细,方便用户理解每一步的操作。可视化部分要调整图表样式,使其清晰易懂,比如折线图的标题、坐标轴标签,特征重要性图的排序和颜色选择。</think>以下是根据您的要求生成的Python代码实现方案,包含详细注释和可视化说明: ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import StratifiedKFold from sklearn.metrics import accuracy_score # === 数据准备 === # 假设数据格式:X为基因表达矩阵(样本×特征),y为类别标签 # X = pd.read_csv('gene_data.csv', index_col=0) # 实际需替换为数据路径 # y = pd.read_csv('labels.csv', index_col=0).values.ravel() # === 参数设置 === n_splits = 5 # 交叉验证折数 param_grid = { 'n_estimators': [100, 200, 300], # 树的数量 'min_samples_leaf': [1, 3, 5] # 叶节点最小样本数 } feature_steps = [50, 100, 150, 200] # 待测试的特征选择数量 # === 交叉验证框架 === skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42) results = pd.DataFrame() # 存储结果 feature_importances = [] # 存储特征重要性 for fold, (train_idx, test_idx) in enumerate(skf.split(X, y)): X_train, X_test = X.iloc[train_idx], X.iloc[test_idx] y_train, y_test = y[train_idx], y[test_idx] # === 参数调优 === best_gini = -np.inf best_params = {} for n_tree in param_grid['n_estimators']: for min_leaf in param_grid['min_samples_leaf']: # 训练随机森林 rf = RandomForestClassifier( n_estimators=n_tree, min_samples_leaf=min_leaf, random_state=42, n_jobs=-1 ).fit(X_train, y_train) # 计算基尼系数平均值 avg_gini = np.mean(rf.feature_importances_) # 记录最佳参数 if avg_gini > best_gini: best_gini = avg_gini best_params = {'n_tree': n_tree, 'min_leaf': min_leaf} # === 使用最佳参数 === best_rf = RandomForestClassifier( n_estimators=best_params['n_tree'], min_samples_leaf=best_params['min_leaf'], random_state=42, n_jobs=-1 ).fit(X_train, y_train) # 保存特征重要性 fold_importance = pd.DataFrame({ 'feature': X.columns, 'importance': best_rf.feature_importances_, 'fold': fold }) feature_importances.append(fold_importance) # === 特征数量选择 === sorted_idx = np.argsort(best_rf.feature_importances_)[::-1] for k in feature_steps: # 选择前k个重要特征 selected = sorted_idx[:k] # 在测试集评估 acc = accuracy_score( y_test, best_rf.predict(X_test.iloc[:, selected]) ) # 记录结果 results = pd.concat([results, pd.DataFrame({ 'fold': fold, 'n_features': k, 'accuracy': acc, 'n_tree': best_params['n_tree'], 'min_leaf': best_params['min_leaf'] }, index=[0])], ignore_index=True) # === 结果可视化 === # 1. 参数优化热力图 pivot_table = results.pivot_table( index='n_tree', columns='min_leaf', values='accuracy', aggfunc='mean' ) plt.figure(figsize=(10, 6)) sns.heatmap(pivot_table, annot=True, cmap='YlGnBu') plt.title('参数优化热力图(平均准确率)') plt.show() # 2. 特征数量-准确率曲线 mean_acc = results.groupby('n_features')['accuracy'].mean() std_acc = results.groupby('n_features')['accuracy'].std() plt.figure(figsize=(10, 6)) plt.errorbar(mean_acc.index, mean_acc, yerr=std_acc, fmt='-o', capsize=5, color='#1f77b4') plt.xlabel('特征数量') plt.ylabel('准确率') plt.title('特征选择数量与模型性能关系') plt.grid(True) plt.show() # 3. 特征重要性可视化 combined_importance = pd.concat(feature_importances) top_features = combined_importance.groupby('feature')['importance']\ .mean().nlargest(20) plt.figure(figsize=(12, 8)) sns.barplot(x=top_features.values, y=top_features.index, palette='viridis') plt.title('Top 20重要基因特征') plt.xlabel('平均基尼重要性') plt.tight_layout() plt.show() ``` ### 代码结构说明: 1. **数据准备阶段**: - 使用`StratifiedKFold`进行分层抽样,保持类别分布 - 假设输入数据为基因表达矩阵$X \in \mathbb{R}^{n \times p}$和标签向量$y$ 2. **参数优化模块**: - 通过网格搜索寻找最优参数组合$(n_{tree}, min_{leaf})$ - 基于基尼系数的加权平均值进行参数选择: $$\bar{G} = \frac{1}{p}\sum_{i=1}^{p} Gini_i$$ 3. **特征选择验证**: - 根据特征重要性排序选择前$k$个特征 - 在独立测试集上评估不同特征数量的准确率 4. **可视化模块**: - 热力图展示参数组合的验证效果 - 误差线图显示特征数量与准确率的关系 - 条形图呈现Top N重要特征 ### 关键数学表达: 1. 基尼重要性计算: $$Gini_j = \sum_{m=1}^M \frac{n_m}{n} \cdot Gini_m^{(j)}$$ 其中$M$为树的总数,$n_m$为第$m$棵树的样本数 2. 特征排序标准: $$\text{Rank}(f_i) = \frac{1}{K}\sum_{k=1}^K Gini_i^{(k)}$$ $K$表示交叉验证折数 ### 优化建议: 1. **大数据优化**: ```python from sklearn.feature_selection import SelectFromModel # 使用特征选择器加速计算 selector = SelectFromModel( estimator=RandomForestClassifier(n_jobs=-1), threshold="median" ).fit(X_train, y_train) X_reduced = selector.transform(X_train) ``` 2. **并行计算**: ```python from joblib import Parallel, delayed # 将参数搜索改为并行执行 results = Parallel(n_jobs=-1)( delayed(evaluate_params)(params) for params in param_combinations ) ``` 3. **早停机制**: ```python from sklearn.ensemble import RandomForestClassifier # 设置提前停止条件 rf = RandomForestClassifier( warm_start=True, n_estimators=0, n_iter_no_change=5 ) for i in range(1000): rf.n_estimators += 50 rf.fit(X_train, y_train) if rf._no_improvement_count >=5: break ``` 该实现方案通过系统化的交叉验证流程,同时优化了模型参数和特征选择数量,最后通过可视化直观呈现关键结果,特别适合处理高维微阵列基因数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值