tensorflow框架转pytorch框架

最近在融合两份代码时,发现一份代码使用的是tensorflow而自己的代码使用的是pytorch框架。在转换过程中使用到的一些函数替换方法做一个简单的记录。

名称TensorFlowpytorchnp
二维卷积

tf.nn.conv2d(input,w,

strides=[1,1,1,1],

padding='SAME')

torch.nn.Conv2d(in_channels,mid_channels,

kernel_size=(3,3),strides=(1,1),padding=(1,1))

生成张量(1的矩阵)

tf.ones(shape=(1,1,1,1), dtype=tf.float32)

torch.ones(1,1,1,1)

创建张量

tf.constant(x)

torch.tensor(x)

relu激活函数tf.nn.relu(x)torch.nn.ReLU(x)
填充函数

tf.pad(input_x,[(a0,b0),

(a1,b1),(a2,b2),(a3,b3)])

pad_num = (a3,b3,a2,b2,a1,b1,a0,b0)

torch.nn.functional.pad(input_x,

pad_num, mode='constant')

元素个数tf.size(input_x)torch.numel(input_x)
展平

tf.reshape(input_x,

(tf.size(input_x),-1))

input_x.view(torch.numel(input_x),-1)
softmaxtf.nn.softmax(input_x,axis=1)torch.nn.functional.softmax(input_x,dim=1)
调整类型tf.cast(input_x,tf.int32)input_x.type(torch.LongTensor)
去除维度1

tf.squeeze(input_x,

squeeze_dims=1)

torch.squeeze(input_x)
合并

tf.concat((input_x1,

input_x2),axis=3)

torch.cat((input_x1,input_x2),dim=3)
划分成相同维度的块

tf.split(input_x,axis=3,

num_or_size_splits=2)

torch.chunk(input_x,dim=3,chunks=2)
重复tf.tile()input_.repeat()
交换维度tf.transpose(input_x,[0,1,2,3])

input_x.permute((0,1,2,3)) 注意这种用法:p01.permute((0,2,3,1)).contiguous().

view(int(np.prod(shape01)),-1)

增加一个维度

tf.expand_dims

np.expand_dims

比较两个张量取最大值

tf.maximum(input_x)

np.maximum

(input_x)

tf.transpose(input,[1, 0, 2])

input.permute([1, 0, 2])

tf.range(10)

torch.arange(0)

tf.reduce_sum(x, axis=1, keep_dims=True)

torch.sum(x,dim=1,keepdim=True)

tf.clip_by_value(x, min, max)

torch.clamp(x, min, max)

tf.multinomial(logits=a, num_samples=1

torch.multinomial(input=a, num_samples=1, replacement=False)

tf.equal(x, y)

torch.eq(x, y)

tf.nn.embedding_lookup(W_fe, Feature_input + 1)

torch.index_select(W_fe, 0, Feature_input + 1)

tf.one_hot()

functional.one_hot()

部分举例

 1、tf.maximum和np.maximum等价

2、torch.nn.Con2d 和 tf.nn.conv2d 的互相转换

torch:
data_c=padded[:,:,:,channel_idx:(channel_idx+1)]
conv2d=torch.nn.Conv2d(kernel_i[2],kernel_i[3],kernel_size=(kernel_i[0],kernel_i[1]),stride=(1,1),padding=(0,0))
data_c=conv2d(data_c)
tf:
data_c=padded[:,:,:,channel_idx:(channel_idx+1)]
data_c=tf.nn.conv2d(data_c,kernel_i,[1,1,1,1],'VALID')

3、tf.pad和torch.nn.functional.pad的相互转换

tf:    padded=tf.pad(img,[[0,0],[pad_w,pad_w],[pad_w,pad_w],[0,0]],mode='REFLECT')
Torch: pad_num=(0,0,pad_w,pad_w,pad_w,pad_w,0,0)
       padded=torch.nn.functional.pad(img,pad_num,mode='REFLECT')

4、tf.tile和torch.repeat的使用是一样的

tx_1=tf.tile(tx,[1,1,1,3])
tx_1=tx(1,1,1,3)

5、tf.newaxis 给tensor增加维度

     在torch中增加tensor维度的方法

        (1) 使用None来增加维度

        diff = X[:, None, :] - X[None, :, :]
        diff

        (2) 使用unsqueeze增加维度

        diff = X.unsqueeze(1) - X.unsqueeze(0)
        diff

        (3) 使用einpos.rearrange增加维度

        from einops import rearrange
        diff = rearrange(X, 'i j -> i () j') - rearrange(X, 'i j -> () i j')
        diff输出都是:

 6、tf.cast() 转 x.type() or x.to()

x=tf.cast(tf.range(-radius,radius+1),dtype=dtype)

x=torch.range(-radius,radius+1).type(dtype=dtype)

7、torch.tensor和tf.constant 相互转换

        张量的基本操作——创建张量

        在Python对象上创建,例如:列表, TensorFlow版本如下所示:

     
        PyTorch版本如下所示:

后续如果有类似的应用会继续补充。

                                                                                    -----2023.02.03

参考:1、https://blog.csdn.net/strawberry47/article/details/125100924

2、记录一下,tensorflow2.0和torch的函数移植对比_Tony Einstein的博客-CSDN博客_tensorflow torch

  • 13
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将TensorFlow代码换为PyTorch代码需要进行以下步骤: 1. 理解TensorFlowPyTorch的差异:TensorFlow是基于数据流图的框架,而PyTorch是基于动态计算图的框架。因此,在代码时需要注意这两种框架的不同之处。 2. 将TensorFlow代码中的变量、操作和图形换为PyTorch中的张量、操作和计算图。 3. 将TensorFlow代码中的损失函数、优化器和训练循环换为PyTorch中的相应函数和循环。 4. 对于一些特殊的TensorFlow操作,如卷积、池化和循环神经网络,需要使用PyTorch中的相应操作进行替换。 5. 在代码时,需要注意TensorFlowPyTorch的API名称和参数的不同之处。 总之,将TensorFlow代码换为PyTorch代码需要一定的技术和经验,需要仔细研究两种框架的差异,并进行适当的修改和调整。 ### 回答2: TensorFlowPyTorch是两个非常受欢迎的深度学习框架。虽然它们具有许多相似之处,但它们的语法和架构都不同。这就意味着在从TensorFlow换到PyTorch时需要进行额外的努力。 出于这个原因,很多人都在寻找将TensorFlow代码化为PyTorch的方法。下面是一些方法: 1.手动代码 手动换是代码的最基本方法。它需要对两种框架的不同语法有一定的了解,并花费大量的时间将代码从一个框架换到另一个框架。虽然这种方法的好处是完全自定义化,但由于其奇异性,这种方法往往会花费很长时间。 2.使用现有的库 为了更快地将TensorFlow代码换为PyTorch,可以使用各种换库。这些库将自动将TensorFlow代码换为PyTorch代码。此方法的好处是速度更快,但由于自动化过程的奇异性,可能需要手动调整换后的代码。 3.使用换平台 换平台是一种支持从一种框架化为另一种框架的自动化工具。这是一种优秀的方式,因为它可以从代码级别换到网络级别。这些平台通常具有可视化界面,使您可以看到TensorFlow代码PyTorch代码之间的差异。 总之,TensorFlowPyTorch都是非常强大的深度学习框架代码时需要花费大量的时间,因此您需要选择最适合您需求的方法。手动换方法是最常用的方法,但使用库和换平台将会使过程更加高效。 ### 回答3: TensorFlowPyTorch是两个最流行的深度学习框架,它们都为用户带来了高效的张量计算库和易于使用的深度学习模型构建平台。对于那些想要自己从TensorFlowPyTorch的人来说,他们需要知道如何在两种框架之间代码。因此,下面将介绍如何将TensorFlow代码换为PyTorch。 首先,需要了解两个框架之间的差异,以便更好地了解代码换方式。TensorFlow的图形模型和动态计算图模型是PyTorch的静态计算图模型的很好的对应物。在TensorFlow中,用户构建的模型是一系列计算图中的节点,表示为tf.Operation对象,而张量表示为tf.Tensor对象。在PyTorch中,静态计算图被表示为一系列计算操作/步骤,即nn.Module对象。张量则类似于TensorFlow中的tf.Tensor对象。 接下来是一些常见的TensorFlow代码换到PyTorch代码的指南。 1. 张量操作: 首先需要看一下TensorFlow的张量操作与PyTorch的张量操作之间的差异。TensorFlow允许在执行操作之前定义张量,在张量右侧添加操作符。而在PyTorch中,记录张量和操作之间的依赖关系,操作只能在执行时添加。 例如: TensorFlow: ``` import tensorflow as tf import numpy as np x = tf.constant(np.array([[1, 2], [3, 4]])) y = tf.constant(5) z = x * y print(z) ``` PyTorch: ``` import torch import numpy as np x = torch.tensor(np.array([[1, 2], [3, 4]])) y = torch.tensor(5) z = x * y print(z) ``` 2. 模型定义: 在TensorFlow中,用户需要明确地定义计算图。在PyTorch中,可以使用nn.Module来定义模型,再将模型的输入传递给模型中的forward方法,以便进行计算。 例如,下面是一个使用TensorFlow定义的简单的线性模型: TensorFlow: ``` import tensorflow as tf import numpy as np class LinearModel(object): def __init__(self): self.W = tf.Variable(np.zeros([2, 1]), dtype=tf.float32) self.b = tf.Variable(np.zeros([1, 1]), dtype=tf.float32) def __call__(self, x): return tf.matmul(x, self.W) + self.b ``` PyTorch: ``` import torch.nn as nn import torch class LinearModel(nn.Module): def __init__(self): super(LinearModel, self).__init__() self.W = nn.Parameter(torch.zeros(2, 1)) self.b = nn.Parameter(torch.zeros(1, 1)) def forward(self, x): return x @ self.W + self.b ``` 3. 损失函数: 在两种框架中,优化模型的常见方法是使用损失函数。然而,不同的框架有不同的损失函数。带权重的分类交叉熵损失函数在TensorFlow中表示为tf.nn.weighted_cross_entropy_with_logits,而在PyTorch中表示为nn.BCEWithLogitsLoss。 例如: TensorFlow: ``` import tensorflow as tf import numpy as np x = tf.Variable(np.array([[1, 2], [3, 4]]), dtype=tf.float32) y_true = tf.Variable(np.array([[0], [1]]), dtype=tf.float32) weights = tf.Variable(np.array([[2], [3]]), dtype=tf.float32) loss = tf.nn.weighted_cross_entropy_with_logits( logits=x, targets=y_true, pos_weight=weights) ``` PyTorch: ``` import torch import numpy as np import torch.nn as nn x = nn.Parameter(torch.tensor([[1, 2], [3, 4]], dtype=torch.float)) y_true = nn.Parameter(torch.tensor([[0], [1]], dtype=torch.float)) weights = nn.Parameter(torch.tensor([[2], [3]], dtype=torch.float)) loss = nn.BCEWithLogitsLoss(weight=weights)(x, y_true) ``` 总结: 在TensorFlowPyTorch之间代码不是太困难,因为两种框架之间有许多重叠的部分。重要的是要熟悉两个框架的差异,以便更好地代码。尽管这两个框架都可以满足许多需求,但在某些情况下,一个框架可能比另一个框架更适合某些人。因此,将TensorFlow代码换成PyTorch可能会使某些开发人员更容易使用PyTorch深度学习框架
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值