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]

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

被折叠的 条评论
为什么被折叠?



