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
相关推荐
IT_陈寒9 分钟前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端
天天爱吃肉82189 分钟前
商用车多体动力学实战笔记|第6篇:动力传动系统(发动机、变速箱、分动器、TCS、LSD限滑差速)
大数据·人工智能·笔记·python·嵌入式硬件·汽车
海盗123428 分钟前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
大数据魔法师29 分钟前
【最全详解】DuckDB Python 全套 API 语法、参数与实战用法(零基础全覆盖)
python·数据分析
把所有砖敲烂1 小时前
DeepSeek V4正式版发布,教你在Codex中配置Flash
人工智能·产品
wyg_0311131 小时前
从0搭建极简transformer大模型
人工智能·深度学习·transformer
老王以为1 小时前
走进 AI Agent
前端·人工智能·架构
dong_junshuai1 小时前
每天一个开源项目#59 AirLLM:27.6K星,3.72GB显存跑2.8T模型
人工智能·程序员·github
文心快码BaiduComate1 小时前
Comate 已支持DeepSeek-V4-Flash 正式版
人工智能·程序员
MartinYeung51 小时前
[论文学习]OSReward:为跨平台计算机使用奖励模型建立标准化评估
人工智能·学习