TensorFlow和PyTorch的实际应用比较

tensorflow和pytorch是两个最受欢迎的开源深度学习框架,这两个框架都为构建和训练深度学习模型提供了广泛的功能,并已被研发社区广泛采用。但是作为用户,我们一直想知道哪种框架最适合我们自己特定项目,所以在本文与其他文章的特性的对比不同,我们将以实际应用出发,从性能、可伸缩性和其他高级特性方面比较tensorflow和pytorch。
01  性能
在选择深度学习框架时,一个关键的考虑因素是你构建和训练的模型的性能。
tensorflow和pytorch都进行了性能优化,这两个框架都提供了大量的工具和技术来提高模型的速度。
就原始性能而言,tensorflow比pytorch更好一些。这两个框架之间的一个关键区别是使用静态计算图而不是动态计算图。在tensorflow中,在模型训练之前,计算图是静态构造的。这使得tensorflow可以通过分析图并应用各种优化技术来更有效地优化图的性能。
而pytorch使用动态计算图,这意味着图是在训练模型时动态构建的。虽然这可能更灵活,更容易使用,但在某些情况下也可能效率较低。
但是记住这一点很重要
tensorflow和pytorch之间的性能差异相非常小,这是因为这两个框架都对性能进行了优化,并提供了许多工具和方法来提高模型的速度,在很多情况下根本发现不了他们的区别。
除了使用静态与动态计算图之外,还有许多其他因素会影响模型的性能。这些因素包括硬件和软件环境的选择、模型的复杂性以及数据集的大小。通过考虑这些因素并根据需要应用优化技术,可以使用tensorflow或pytorch构建和训练高性能模型。
除了原始性能,tensorflow和pytorch都提供了大量的工具和方法来提高模型的速度:
tensorflow提供了多种优化方法,可以极大地提高模型的性能,例如自动混合精度和xla。
xla(加速线性代数):tensorflow包括一个称为xla的即时(jit)编译器,它可以通过应用多种优化技术来优化模型的性能,包括常数折叠、代数简化和循环融合。要启用xla,可以使用tf.config.optimizer.set_jit函数。
tfx (tensorflow extended): tfx是一套用于构建和部署机器学习管道的库和工具,包括用于数据处理、模型训练和模型服务的工具。tfx可以通过自动化所涉及的许多步骤,更有效地构建和部署机器学习模型。
tf.function函数装饰器可以将tensorflow函数编译成一个图,这可能比强制执行函数更快,可以利用tensorflow的优化技术来提高模型的性能。
pytorch通过使用torch.autograd 和torch.jit等提供了优化模型的方法,它提高模型的有效性
torch.autograd.profiler:通过跟踪 pytorch 模型的各种元素使用的时间和内存量,可以帮助找到瓶颈和代码中需要改进的地方。
torch.nn.dataparallel:torch.nn.dataparallel 类可跨多个设备(例如 gpu)并行训练 pytorch 模型。通过使用 dataparallel,可以利用多个设备来增加模型的推理效率。
torch.jit:使用即时 (jit) 编译器优化 pytorch 模型。torch.jit 将模型编译成静态计算图,与动态图相比可以更有效地进行优化。
静态与动态计算图定义的编码示例:
如前所述,tensorflow在原始性能方面比pytorch略有优势,这是由于它的静态计算图。
下面是一个在tensorflow中构建前馈神经网络的简单例子:
import tensorflow as tf # define the model model = tf.keras.sequential([ tf.keras.layers.dense(64, activation='relu', input_shape=(64,)), tf.keras.layers.dense(64, activation='relu'), tf.keras.layers.dense(10, activation='softmax') ]) # compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # fit the model model.fit(x_train, y_train, epochs=5)  
下面是在pytorch中实现和训练的相同模型:
import torch import torch.nn as nn import torch.optim as optim # define the model class net(nn.module): def __init__(self): super(net, self).__init__() self.fc1 = nn.linear(64, 64) self.fc2 = nn.linear(64, 64) self.fc3 = nn.linear(64, 10) def forward(self, x): x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) return x # create the model instance model = net() # define the loss function and optimizer criterion = nn.crossentropyloss() optimizer = optim.adam(model.parameters()) # training loop for epoch in range(5): # forward pass output = model(x_train) loss = criterion(output, y_train) # backward pass and optimization step optimizer.zero_grad() loss.backward() optimizer.step()  
这两个例子都展示了如何构建和训练一个简单的前馈神经网络,虽然方法不同但是他们的性能基本却相同。对于性能的对比,目前来说两个框架基本相同,差异可以忽略不计。
02   可伸缩性
在选择深度学习框架时,另一个重要考虑因素是可伸缩性。随着模型的复杂性和规模的增长,需要一个能够处理不断增长的计算需求的框架。
这两个框架都提供了扩展模型的策略,但它们处理问题的方式略有不同。
tensorflow在设计时考虑了可伸缩性,并提供了许多用于分布式训练和部署的工具。
例如,tensorflow 的 tf. distribute api 可以轻松地跨多个设备和服务器分发训练,而 tensorflow serving 可以将经过训练的模型部署到生产环境。
pytorch也提供用于分布式培训和部署的工具,但重点更多地放在研究和开发上,而不是生产环境。
pytorch 的 torch.nn.dataparallel 和 torch.nn.parallel.distributeddataparallel 类可以跨多个设备并行训练,而 pytorch lightning 库(非官方)为分布式训练和部署提供了一个高级接口。
tensorflow
tf.distribute.strategy:tf.distribute.strategy api 可跨多个设备和机器并行训练 tensorflow 模型。有许多不同的策略可用,包括 tf.distribute.mirroredstrategy,它支持在单台机器上的多个 gpu 上进行训练,以及 tf.distribute.experimental.multiworkermirroredstrategy,它在具有多个 gpu 的多台机器上提供训练。
tf.data.dataset:可以为训练构建了高效且高度并行化的数据管道。通过使用 tf.data.dataset,可以轻松地并行加载和预处理大型数据集,这可以模型扩展到更大的数据集。
tf.keras.layers.normalization:tf.keras.layers.normalization 层实时规范化输入数据,这可能有助于提高模型的性能。应用归一化可以减少大输入值的影响,这可以帮助模型更快地收敛并获得更好的性能。
tf.data.dataset.interleave:通过对数据并行应用函数,再次并行处理输入数据。这对于数据预处理等任务非常有用,在这些任务中您需要对数据应用大量转换。
pytorch
torch.nn.parallel.distributeddataparallel:torch.nn.parallel.distributeddataparallel 类在多个设备和机器上并行训练 pytorch 模型。但是需要使用torch.nn.parallel.distributeddataparallel.init_process_group 设置分布式训练环境。
torch.utils.data.dataloader:创建一个数据迭代器,用于并行处理数据的加载和预处理。
torch.utils.data.distributed.distributedsampler:类似于 torch.utils.data.distributedsampler,但设计用于与 distributeddataparallel 类一起使用。通过使用 distributedsampler,可以确保在使用distributeddataparallel 进行训练时,每个设备都会收到平衡的数据样本。
通过利用这些函数和类,可以将 tensorflow 和 pytorch 模型扩展到更大的数据集和更强大的硬件,构建更准确、更强大的模型。
下面介绍了提高可伸缩性的两种不同方法。
tensorflow的第一个例子使用了tf.distribute. mirrredstrategy:
import tensorflow as tf # define the model model = tf.keras.sequential([ tf.keras.layers.dense(64, activation='relu', input_shape=(64,)), tf.keras.layers.dense(64, activation='relu'), tf.keras.layers.dense(10, activation='softmax') ]) # compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # define the distribution strategy strategy = tf.distribute.mirroredstrategy() # load the dataset dataset = tf.data.dataset.from_tensor_slices((x_train, y_train)).batch(64) # define the training loop with strategy.scope(): for epoch in range(5): for x_batch, y_batch in dataset: model.fit(x_batch, y_batch)  
在pytorch使用 torch.nn.dataparallel :
import torch import torch.nn as nn import torch.optim as optim # define the model class net(nn.module): def __init__(self): super(net, self).__init__() self.fc1 = nn.linear(64, 64) self.fc2 = nn.linear(64, 64) self.fc3 = nn.linear(64, 10) def forward(self, x): x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) return x # create the model instance and wrap it in dataparallel model = nn.dataparallel(net()) # define the loss function and optimizer criterion = nn.crossentropyloss() optimizer = optim.adam(model.parameters()) # training loop for epoch in range(5): # forward pass output = model(x_train) loss = criterion(output, y_train) # backward pass and optimization step optimizer.zero_grad() loss.backward() optimizer.step()  
这两个例子都展示了如何在多个设备上并行训练,但tensorflow对于分布式训练的支持要比pytorch更好一些。
03   高级的特性
除了性能和可伸缩性之外,这两个框架还提供了许多项目相关的高级特性。
例如,tensorflow拥有强大的工具和库生态系统,包括用于可视化的tensorboard和用于模型部署和服务的tensorflow extended。
pytorch也多个高级特性,一般都会命名为 torchxxx,比如torchvision,torchaudio等等
我们以tensorboard为例介绍两个库的使用,虽然tensorboard是tensorflow的一部分,但是pytorch也通过代码部分兼容了数据部分的发送,也就是说使用pytorch也可以往tensorboard写入数据,然后通过tensorboard进行查看。
tensorflow 在训练时使用tensorboard的callback可以自动写入。
import tensorflow as tf # define the model model = tf.keras.sequential([ tf.keras.layers.dense(64, activation='relu', input_shape=(64,)), tf.keras.layers.dense(64, activation='relu'), tf.keras.layers.dense(10, activation='softmax') ]) # compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # define a tensorboard callback tensorboard_callback = tf.keras.callbacks.tensorboard(log_dir='logs') # fit the model model.fit(x_train, y_train, epochs=5, callbacks=[tensorboard_callback])  
pytorch需要自行代码写入:
import numpy as np from torch.utils.tensorboard import summarywriter writer = summarywriter(comment='test_tensorboard') for x in range(100): writer.add_scalar('y=2x', x * 2, x) writer.add_scalar('y=pow(2, x)', 2 ** x, x) writer.add_scalars('data/scalar_group', {xsinx: x * np.sin(x), xcosx: x * np.cos(x), arctanx: np.arctan(x)}, x) writer.close()  
在高级特性中我觉得最主要的就是tensorflow 中引入了keras,这样只需要几行代码就可以完成完整的模型训练
# compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5)  
而pytorch还要手动进行损失计算,反向传播
output = model(x_train) loss = criterion(output, y_train) # backward pass and optimization step optimizer.zero_grad() loss.backward() optimizer.step()  
虽然这样灵活性很高,但是应该有一个像keras这样的通用方法(tensorflow 也可以手动指定计算过程,并不是没有),所以在这一部分中我觉得tensorflow要比pytorch好很多。
当然也有一些第三方的库来简化pytorch的训练过程比如pytorch lightning、torchhandle等但是终究不是官方的库。
04   最后总结
最适合你的深度学习框架将取决于你的具体需求和要求
tensorflow 和 pytorch 都提供了广泛的功能和高级特性,并且这两个框架都已被研发社区广泛采用。作为高级用户,我的个人建议是深入学习一个库,另外一个库代码基本上是类似的,基础到了基本上做到能看懂就可以了,比如
class dnnmodel(nn.module): def __init__(self): super(dnnmodel, self).__init__() self.fc1 = nn.linear(2,4) self.fc2 = nn.linear(4,8) self.fc3 = nn.linear(8,1) # 正向传播 def forward(self,x): x = f.relu(self.fc1(x)) x = f.relu(self.fc2(x)) y = nn.sigmoid()(self.fc3(x)) return y ################ class dnnmodel(models.model): def __init__(self): super(dnnmodel, self).__init__() def build(self,input_shape): self.dense1 = layers.dense(4,activation = relu,name = dense1) self.dense2 = layers.dense(8,activation = relu,name = dense2) self.dense3 = layers.dense(1,activation = sigmoid,name = dense3) super(dnnmodel,self).build(input_shape) # 正向传播 @tf.function(input_signature=[tf.tensorspec(shape = [none,2], dtype = tf.float32)]) def call(self,x): x = self.dense1(x) x = self.dense2(x) y = self.dense3(x) return y  
看看上面代码的两个类它们的区别并不大,对吧。
下面是google trends的趋势对比,我们可以看到明显的区别


索尼正式推出了2020年电视新品全矩阵
奥迪在高速公路测试L4级自动驾驶
OPPOR17Pro评测 凭什么获得行业与用户的一致认可
索尼:希望Xperia手机保持创新,努力把手机做到更窄边框
涂鸦智能与TCL达成合作共同推进AIoT的发展
TensorFlow和PyTorch的实际应用比较
全球知名半导体公司台积电官宣:正式启动2nm工艺的研发
可控硅调压器工作原理
超高清逐步延伸到安防监控领域 监控数据规模呈指数级增长
平板市场不景气,10.5寸苹果iPad Pro或主打设计:采用无边框?
老司机讲解初识热敏 FFC(FPC)焊接方法和注意事项
黑科技石墨烯电池助你远离“里程焦虑症”石墨负极在充放电过程中的相变机
西部数据Black™NVMe™M.2固态硬盘评测 凭借超高性能亦会有惊艳的表现
碳化硅SiC功率器件,全球市场总体规模,前三十大厂商排名及市场份额
应用面向对象编程SoC原则的典型示例
关于中国义乌国际装备博览会的介绍和分析
智算中心加速落地,计算力就是生产力
三星电视开启双12大促,携手天猫商城开启年度钜惠
如何在Linux使用truncate命令将文件缩小或扩展到指定的大小
机载AESA雷达的发展概述