coding-AI-01-常用tips知识点

加载自定义环境变量到项目中
import  sys
path_name = r'utils'
if path_namr not in sys.path:
	sys.path.inser(0, path_name)
else:
	print('already add {}'.format(path_name))
	
训练指定GPU
device主要是设置CUDA_VISIBLE_DEVICES变量实现
#不使用GPU
CUDA_VISIBLE_DEVICES=""
#使用device序号为1的卡
CUDA_VISIBLE_DEVICES=1
#使用device为0和1的卡
CUDA_VISIBLE_DEVICES=0,1
#使用device为0和1的卡
CUDA_VISIBLE_DEVICES=0,1#使用device为0,1,3的卡,2号卡不可见
CUDA_VISIBLE_DEVICES=0,1,3

# **例如使用0和3号device** 代码放在文件开始位置,没有device.to设备中
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,3"

use_cuda = not args.no_cuda and torch.cuda.is_available()

device = torch.device("cuda" if use_cuda else "cpu")
CPU和GPU资源上运行代码
import tensorflow as tf
import tensorflow.contrib.eager as tfe
# 获取GPU个数
print(tf.contrib.eager.num_gpus())
#定义一个张量
data = tf.random.normal([3, 3, 3])
gpu0_ = data.gpu()
cpu_ = data.cpu()

# 在0号GPU上运行加法
y_gpu = tf.add(gpu0_, gpu0_)
# 在CPU上运行加法
y_cpu_ = tf.add(cpu_, cpu_)

模型预测
def test(args, model, device, test_loader):
    # 命令行输入参数、网络模型、设备对象、数据加载器
    model.eval()
    # 模型评估方法
    test_loss = 0
    correct = 0
    # 测试误差、准确度初始化为0
    with torch.no_grad():
    # 
        for data, target in test_loader:
        #遍历数据集,data:测试输入数据:样本特征,target:测试输出数据,样本标签
            data, target = data.to(device), target.to(device)
            #把数据传输到指定设备上
            output = model(data)
            # 调用模型对象(样本特征)预测,输出返回到output中
            test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
            # 计算输出与样本标签之间的误差
            pred = output.max(1, keepdim=True)[1] 
            # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值