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_)
模型预测
deftest(args, model, device, test_loader):# 命令行输入参数、网络模型、设备对象、数据加载器
model.eval()# 模型评估方法
test_loss =0
correct =0# 测试误差、准确度初始化为0with 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()