Pytorch 使用报错 RuntimeError: Caught RuntimeError in DataLoader worker process 0.

这个错误是可能是由于在DataLoader的工作进程中尝试访问CUDA设备导致的。PyTorch的DataLoader使用多进程加载数据,而CUDA上下文不能在子进程中直接使用。

修改前的代码为:

复制代码
def prepare_data(file_path):
    # 读取Excel文件
    df = pd.read_excel(file_path, header=None)
    df = df.iloc[1:]
    print(df)

    # 提取特征和标签
    features = df.iloc[:, :-1].values.astype('float32')  # extract feature
    labels = df.iloc[:, -1].values.astype('int64')  # extract label



    # 数据标准化
    scaler = StandardScaler()
    features = scaler.fit_transform(features)

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(
        features, labels, test_size=0.2, random_state=42
    )

    # 转换为PyTorch张量并移动到设备
    X_train = torch.tensor(X_train, device=device)
    X_test = torch.tensor(X_test, device=device)
    y_train = torch.tensor(y_train, device=device)
    y_test = torch.tensor(y_test, device=device)

    return X_train, X_test, y_train, y_test, scaler

数据加载修改为下运行OK:

复制代码
class ExcelDataset(Dataset):
    def __init__(self, features, labels):
        # 确保数据在CPU上
        self.features = features.cpu() if features.is_cuda else features
        self.labels = labels.cpu() if labels.is_cuda else labels
相关推荐
AI科技星8 分钟前
基于全域数学公理体系求解三元约束极值题【乖乖数学】
人工智能·算法·机器学习·密码学·拓扑学·乖乖数学·全域数学
汤姆小白3 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
喜欢就别5 小时前
【Agentic RL / 强化学习 / OPD】OpenClaw-RL 源码阅读笔记 --- (2)--- On-Policy Distillation
人工智能·笔记
糯米导航8 小时前
AI 视觉回归实战:截图对比不是“找不同”,如何让智能差异分析真正服务 UI 质量
人工智能·ui·回归
科技圈观察8 小时前
2026年好伴AI医疗专用大模型应用梳理与梯队参考
人工智能
jkyy20149 小时前
深耕AI健康医疗数据智库,赋能企业构建主动健康管理新生态
大数据·人工智能·健康医疗
cd_949217219 小时前
3D角色自动绑骨怎么做?用V2Fun完成建模、绑定、动作和导出
人工智能·3d
瑞禧生物tech9 小时前
SH-PEG-Biotin巯基-聚乙二醇-生物素 HS-PEG-Bio 深度解析
人工智能
QYR-分析9 小时前
机器人安全控制器行业高速扩容 本土替代迎来全新发展窗口期
人工智能·安全·机器人
向日的葵0069 小时前
langchain的Tools教程(三)
python·langchain·tools