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
相关推荐
京东零售技术20 小时前
京东零售胡浩:智能供应链从运筹到大模型到超级智能体的演进
大数据·人工智能
榕壹云20 小时前
GEO正在通过大模型技术重构企业数字营销生态
人工智能·重构·geo
计算机软件程序设计1 天前
基于Python的二手车价格数据分析与预测系统的设计与实现
开发语言·python·数据分析·预测系统
K姐研究社1 天前
通义万相Wan2.5模型实测,可生成音画同步视频
人工智能·aigc·音视频
mortimer1 天前
Traceback 模块:`format_exc` 和 `format_exception` 傻傻分不清
python
云起SAAS1 天前
老年ai模拟恋爱抖音快手微信小程序看广告流量主开源
人工智能·微信小程序·小程序·ai编程·看广告变现轻·老年ai模拟恋爱·ai模拟恋爱
Cherry Zack1 天前
了解Django模型,从基础到实战
python·学习·django
qq7422349841 天前
语音识别:PyAudio、SoundDevice、Vosk、openai-whisper、Argos-Translate、FunASR(Python)
python·whisper·语音识别
曾经的三心草1 天前
OpenCV2-图像基本操作-阈值与平滑处理-形态学-梯度运算
python·opencv
xiangzhihong81 天前
Spring Boot实现文字转语音功能
开发语言·python