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
相关推荐
ShiMetaPi26 分钟前
BM1684X平台:Qwen-2-5-VL图像/视频识别应用
人工智能·音视频·边缘计算·bm1684x·shimetapi
九河云34 分钟前
华为云代理商的作用与价值解析
大数据·人工智能·华为云
科技云报道1 小时前
科技云报到:热链路革命:阿卡 CRM 的 GTM 定位突围
人工智能
路人蛃1 小时前
Scikit-learn - 机器学习库初步了解
人工智能·python·深度学习·机器学习·scikit-learn·交友
AI导航猿2 小时前
做PPT、改图、带团队,这个协作工具干掉了我常用的4个软件|AI导航猿
人工智能
失散132 小时前
机器学习——04 逻辑回归
人工智能·机器学习·逻辑回归
荼蘼3 小时前
OpenCV 入门教程:开启计算机视觉之旅
人工智能·opencv·计算机视觉
左右_Sats3 小时前
SpringAI(RAG+MCP)使用-未完结
人工智能
Nep&Preception3 小时前
vasp计算弹性常数
开发语言·python
AI程序员3 小时前
上下文工程:把“一段话”升级成“一套解决方案”(工程师友好的通俗讲解)
人工智能