torch.cuda.OutOfMemoryError

文章讲述了在使用PyTorch训练CIFAR10数据集的卷积神经网络模型时遇到CUDA内存溢出问题,通过调整batch_size和网络结构解决了问题。具体表现为调整输入输出shape,减少模型复杂度,最终实现模型的训练并保存权重。

torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 8.00 GiB (GPU 0; 7.92 GiB total capacity; 1.48 MiB already allocated; 6.91 GiB free; 22.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

遇到这个错误,按网上改小batch_size改的很小了,依然报错。

后改小了网络结构,搞定。

错误原因是网络的输入输出shape不一致。

错误的shape

128 * 128 * 8=131072

改后。

torch.nn.Flatten(),

torch.nn.Linear(in_features=8 * 8 * 8, out_features=512),

import torch
from matplotlib import pyplot as plt
from torch import nn, optim
# from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from tqdm import tqdm
from matplotlib.ticker import MaxNLocator
 
# 超参数
batch_size = 128  # 批大小
learning_rate = 0.0001  # 学习率
epochs = 20  # 迭代次数
channels = 3  # 图像通道大小
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck']

# 数据集下载和预处理
transform = transforms.Compose([transforms.ToTensor(),  # 将图片转换成PyTorch中处理的对象Tensor,并且进行标准化0-1
                                transforms.Normalize([0.5], [0.5])])  # 归一化处理
path = './data/'  # 数据集下载后保存的目录
# 下载训练集和测试集
trainData = datasets.CIFAR10(path, train=True, transform=transform, download=True)
testData = datasets.CIFAR10(path, train=False, transform=transform)

# 将数据集前20个图片数据可视化显示
#
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值