CNN 使用GPU训练模型

文章讲述了如何在CNN参数调优过程中,通过支持CPU或GPU算力类型,减少CPU压力,并提供了使用CUDA和GPU环境的代码示例。作者还展示了如何构建和训练一个QuadrantClassifier模型,以及如何通过数据生成器生成训练和验证数据。

CPU压力过大的问题:

前面分析 CNN参数调优 时,
程序占用CPU资源过大,如下图(不同设备可能不同):
在这里插入图片描述

尝试代码进行如下优化:

1.使程序能同时支持CPU或GPU算力类型
2.使用GPU环境能减少CPU的压力

详细代码如下:

"""
CNN CUDA(统一计算设备架构,是由NVIDIA推出的通用并行计算架构)
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
from tqdm import tqdm

# CUDA环境是否存在(如果不存在就使用CPU环境)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 数据生成器
class DataGenerator(object):
    def __init__(self):
        super(DataGenerator, self).__init__()
        self.trainData = []
        self.trainLabels = []
        self.valData = []
        self.valLabels = []

    # 检查tx,ty坐标象限分类
    def check_quadrant(self, tx, ty):
        if (tx > 0) and (ty > 0):
            return 0  # 第一象限
        if (tx < 0) and (ty > 0):
            return 1  # 第二象限
        if (tx < 0) and (ty < 0):
            return 2  # 第三象限
        if (tx > 0) and (ty < 0):
            return 3  # 第四象限
        # 浮点数比较
        if (abs(tx) > 0) and (abs(ty) < 0.000001):
            return 4  # x轴
        # 浮点数比较
        if (abs(tx) < 0.000001) and (abs(ty) > 0):
            return 5  # y轴
        return 6  # 原点

    # 随机整数
    def random_int(self, low, high):
        return np.random.randint(low, high)

    # 特殊值数据
    def random_special_point(self, index, count, low, high):
        perCnt = count // 3
        if index < perCnt:
            tx = 0
            ty = 0
            tl = self.check_quadrant(tx, ty)
        elif index < perCnt * 2:
            tx = 0
            ty = self.random_int(low, high)
            tl = self.check_quadrant(tx, ty)
        else:
            tx = self.random_int(low, high)
            ty = 0
            tl = self.check_quadrant(tx, ty)
        return tx, ty, tl

    # 随机生成训练和验证数据
    # train(low, high, count)
    # val(low, high, count)
    def generateData(self, train: tuple[int, int, int], val: tuple[int, int, int]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值