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
相关推荐
冬奇Lab9 小时前
每日一个开源项目(第140篇):AgentScope 2.0 - 阿里开源的生产级 Agent 框架
人工智能·开源·agent
冬奇Lab9 小时前
Skill 系列(04):Skill 指标体系——L1/L2/L3 三层监控,让质量下降有据可查
人工智能·开源·llm
IT_陈寒10 小时前
Vite的静态资源打包让我熬夜到三点,这坑千万别跳
前端·人工智能·后端
玩转AI不是事11 小时前
用IndexedDB做AI对话离线缓存实战
人工智能
学测绘的小杨11 小时前
CompassFusion:一个从 GNSS 到 GNSS/INS 组合导航的独立工程包
python
Asize11 小时前
多模态生图:从 Vite 工程化到前端调用 Qwen Image
javascript·人工智能·后端
MobotStone12 小时前
AI项目越多,为什么越容易失控
人工智能·aigc
十有八七12 小时前
AI时代的置身X内
前端·人工智能
Lkstar12 小时前
A2A协议深度解析|Agent2Agent通信标准,智能体互联网的"HTTP"
人工智能·llm
百度Geek说12 小时前
当代码越来越便宜,什么在变贵?
人工智能