python - 从 Tensorflow 迁移到 PyTorch 时模型定义的注意事项

标签 python tensorflow pytorch

在调试 tf 时感到沮丧后,我最近刚刚切换到 PyTorch,并了解到它几乎完全等同于用 numpy 进行编码。我的问题是我们可以在 PyTorch 模型中使用哪些允许的 python 方面(完全放在 GPU 上),例如。 if-else必须在tensorflow中实现如下

a = tf.Variable([1,2,3,4,5], dtype=tf.float32)
b = tf.Variable([6,7,8,9,10], dtype=tf.float32)
p = tf.placeholder(dtype=tf.float32)
ps = tf.placeholder(dtype=tf.bool)

li = [None]*5
li_switch = [True, False, False, True, True]

for i in range(5):
    li[i] = tf.Variable(tf.random.normal([5]))

sess = tf.Session()
sess.run(tf.global_variables_initializer())

def func_0():
    return tf.add(a, p)
def func_1():
    return tf.subtract(b, p)

with tf.device('GPU:0'):
    my_op = tf.cond(ps, func_1, func_0)

for i in range(5):
    print(sess.run(my_op, feed_dict={p:li[i], ps:li_switch[i]}))

上述代码在 pytorch 中的结构会如何变化?如何将上面的变量和操作放在 GPU 上,并将列表输入并行化到 pytorch 中的图形?

最佳答案

在pytorch中,可以像编写普通python代码一样编写代码。

CPU

import torch
a = torch.FloatTensor([1,2,3,4,5])
b = torch.FloatTensor([6,7,8,9,10])
cond = torch.randn(5)

for ci in cond:
    if ci > 0:
        print(torch.add(a, 1))
    else:
        print(torch.sub(b, 1))

GPU

将张量移至 GPU,如下所示:

a = torch.FloatTensor([1,2,3,4,5]).to('cuda')
b = torch.FloatTensor([6,7,8,9,10]).to('cuda')
cond = torch.randn(5).to('cuda')

import torch.nn as nn

class Cond(nn.Module):
    def __init__(self):
        super(Cond, self).__init__()

    def forward(self, cond, a, b):
        result =  torch.empty(cond.shape[0], a.shape[0]).cuda()
        for i, ci in enumerate(cond):
            if ci > 0:
                result[i] = torch.add(a, 1)
            else:
                result[i] = torch.sub(b, 1)

        return result

cond_model = Cond().to('cuda')
output = cond_model(cond, a, b)

https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#cuda-tensors

关于python - 从 Tensorflow 迁移到 PyTorch 时模型定义的注意事项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063686/

相关文章:

python - 使用多个 GPU 运行 LSTM 得到 "Input and hidden tensors are not at the same device"

python - 在 python 2.6.6 中获取子子的子值

python - TensorFlow matmul : Blas xGEMMBatched launch failed

android - Android:出现错误:添加新依赖项后,任务 ':app:processDebugGoogleServices'的执行失败

python - 如何在 Tensorflow 中构建 spp-net?

python - 如何在 Google Colab 中的另一个虚拟机上拍摄和恢复模型训练的快照?

python - 如何在 YOLO v8 中卡住主干、特征提取层

python - SSL 1108 Mac 问题

python - 如何将 Librosa 光谱图保存为特定大小的图像?

python - 有没有办法修复 python 3 中的最大递归级别?