从Tensorflow到PyTorch时模型定义的考虑

时间:2019-05-09 16:18:12

标签: python tensorflow pytorch

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

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中的图形中?

2 个答案:

答案 0 :(得分:1)

在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

答案 1 :(得分:1)

要在PyTorch中初始化export ANDROID_HOME=$HOME/Android/Sdk export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/platform-tools a张量,请执行以下操作:

b

但是,由于您需要将它们完全放在GPU上,因此必须使用神奇的a = torch.tensor([1,2,3,4,5], dtype=torch.float32) b = torch.tensor([6,7,8,9,10], dtype=torch.float32) 函数。因此,它将是:

.cuda()

将张量移动到GPU


另一种初始化方式是:

a = torch.tensor([1,2,3,4,5], dtype=torch.float32).cuda()
b = torch.tensor([6,7,8,9,10], dtype=torch.float32).cuda()

如果我们需要生成随机正态分布,请使用torch.randn(还有torch.rand会进行均匀的随机分布)。

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

(捕获该错误,必须在li = torch.randn(5, 5) 上对其进行初始化,您不能对位于单独的处理单元(即CPU和GPU)上的张量进行操作)

cuda

li = torch.randn(5, 5).cuda() 初始化没有区别。

处理li_switchfunc_0的一种可能方法是将它们声明为

func_1

然后,对于谓词函数调用,它可以像这样简单:

def func_0(li_value):
    return torch.add(a, li_value)
def func_1(li_value):
    return torch.sub(b, li_value)

但是,我建议对您的操作进行向量化,然后执行以下操作:

for i, pred in enumerate(li_switch):
    if pred:
        func_0(li[i])
    else:
        func_1(li[i])

这是最优化的。