Keras vs. Tensorflow——哪一个更好,我应该学习哪一个?

star2017 1年前 ⋅ 3703 阅读

我应该用Keras 还是TensorFlow来做我的项目呢?TensorFlow好还是Keras更好?我该把时间花在研究TensorFlow身上吗?还是Keras?

以上都是我常在收件箱、社交媒体、甚至与深层学习的研究人员、实践者和工程师的亲自交谈中听到的问题。

我甚至收到一些与我的书《用Python进行计算机视觉的深度学习》相关的问题,读者问我为什“仅仅”涵盖Keras——关于TensorFlow呢?

真不幸,因为这是一个错误的问题。

截至2017年中期,Keras实际上被完全采纳并融入了TensorFlow。这个TensorFlow+Keras的集成意味着你可以:

  1. 使用Keras的易用接口定义模型
  2. 如果需要(1)特定的TensorFlow功能或(2)需要实现Keras不支持但TensorFlow支持的自定义特性,那么可以下拉到TensorFlow中。

简而言之:

可以将TensorFlow代码直接插入到Keras模型或训练管道序列中!

别误会我的意思。我并不是说,对于某些应用程序,您不需要了解一点TensorFlow——如果您正在执行新颖的研究并且需要定制实现,则尤其如此。我只是说如果在做这些事时:

  1. 刚刚开始学习深度学习
  2. 试图决定为下一个项目使用哪一个库
  3. 想知道Keras或TensorFlow哪个“更好”

就会感觉得到了。

别担心,做就是了。我的建议是使用Keras启动,然后为您需要的任何特定功能下拉到TensorFlow。

在今天的文章中,我将向您展示如何训练(1)使用严格Keras的神经网络和(2)使用直接构建到TensorFlow库中的Keras+TensorFlow集成(带有定制特性)的模型。

要了解更多关于Keras vs. Tensorflow,继续阅读!

Keras和TensorFlow——哪一个更好,我应该学习哪一个?

在今天教程的剩余部分中,我将继续讨论Keras vs.TensorFlow的论点以及它是如何提出错误的问题的。

我们将会实现一个卷积神经网络(CNN),使用标准keras模块和直接刻入到TensorFlow中的tf.keras模块。

我们将在示例数据集上训练这些CNN,然后检查结果——正如您将发现的,Keras和TensorFlow和谐地生活在一起。

也许最重要的是,你会明白为什么Keras vs. TensorFlow的论点不再有意义。

如果你问“Keras vs. TensorFlow”,这本身就不是一个问题

图1:“我应该使用KARAS还是Tensorflow?“

询问是否应该使用Keras还是TensorFlow是错误的问题——事实上,这个问题甚至不再有意义。尽管自从TensorFlow宣布将把Keras集成到官方的TensorFlow发行版已经超过一年了,我仍然惊讶于许多深层学习实践者不知道他们可以通过tf.keras子模块访问Keras。

更重要的是,Keras+TensorFlow集成是无缝的,允许您将原始TensorFlow代码直接放入Keras模型中。

使用TensorFlow中的Keras给你最好的两个世界:

  1. 您可以使用Keras提供的简单、直观的API来创建模型。
  2. Keras API本身类似于Scikit-learn,可以说是机器学习API的“金标准”。
  3. Keras API是模块化的,Python式的,超级简单易用。
  4. 当需要自定义层实现、更复杂的损失函数等时,可以下拉到TensorFlow,并自动将代码与Keras模型集成。

在过去的几年里,深度学习的研究者、实践者和工程师常常不得不选择:

  • 我是否使用易用性,但可能更难定制Keras库?
  • 或者我是否利用了相当困难的TensorFlow API,编写了一个数量级的更多代码,更不用说使用不太容易遵循的API来工作?

幸运的是,我们不再需要选择了。

如果你发现自己处于这样的境地:“我应该用Keras 还是TensorFlow呢?”“退后一步——你问错了问题——你可以同时拥有两个。

通过“tf.Keras”模块将Keras构建为TensorFLow

图3:如您所见,通过导入TensorFlow(作为tf)并随后调用tf.keras,我在Python shell中演示了Keras实际上是TensorFlow的一部分。

包括Keras在内tf.keras允许您使用标准的keras软件包来执行以下简单的前馈神经网络:

# import the necessary packages
from keras.models import Sequential
from keras.layers.core import Dense
import tensorflow as tf
 
# define the 3072-1024-512-3 architecture using Keras
model = Sequential()
model.add(Dense(1024, input_shape=(3072,), activation="sigmoid"))
model.add(Dense(512, activation="sigmoid"))
model.add(Dense(10, activation="softmax"))

然后使用tf.keras子模块实现相同的网络,该子模块是TensorFlow的一部分:

# define the 3072-1024-512-3 architecture using tf.keras
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(1024, input_shape=(3072,),
	activation="sigmoid"))
model.add(tf.keras.layers.Dense(512, activation="sigmoid"))
model.add(tf.keras.layers.Dense(10, activation="softmax"))

这是否意味着你必须使用tf.keras?标准的keras包现在过时了吗?不,当然不是。

作为一个库,Keras仍将独立于TensorFlow独立运行,因此未来两者可能会出现分歧;然而,考虑到Google官方同时支持Keras和TensorFlow,这种分歧似乎极不可能。

重点是:

如果你愿意用纯Keras编写代码,那就去做,继续做下去。

但是如果你发现自己在TensorFlow中工作,你应该开始利用Keras API:

  • 它建立在TensorFlow中。
  • 使用起来更容易些。
  • 当您需要纯TensorFlow实现特定的功能或功能时,它可以直接落入您的Keras模型中。

没有更多的Keras vs. TensorFlow论证——你可以同时拥有这两个,同时你也得到了最好的两个世界。

我们的示例数据集

图4:CIFAR-10数据集有10个类,用于今天的演示(图像信用)。

为了简单起见,我们将使用以下方法在CIFAR-10数据集上训练两个独立的卷积神经网络:

  • 用TensorFlow做后端的Keras
  • Tr.Keras内部的Keras子模块

我还将展示如何在实际的Keras模型中包含自定义的TensorFlow代码。

CIFAR-10数据集本身由10个单独的类组成,具有50000个训练图像和10000个测试图像。图4中显示了一个示例。

我们的项目结构

我们的项目结构现在可以用 tree 命令在终端中查看:

$ tree --dirsfirst
.
├── pyimagesearch
│   ├── __init__.py
│   ├── minivggnetkeras.py
│   └── minivggnettf.py
├── plot_keras.png
├── plot_tf.png
├── train_network_keras.py
└── train_network_tf.py
 
1 directory, 7 files

pyimagesearch模块包含与此博客帖子相关联的下载。它不是可安装的pip,但它包含在“下载”中。让我们回顾一下模块中的两个重要Python文件:

  1. minivggnetkeras.py:这是我们基于VGGNET的一个深度学习模型的MINIVGGNET的严格的Keras实现。
  2. minivggnettf.py:这是我们的TensorFlow+Keras(即,tf.keras)实现的miniVGGNET。

项目文件夹的根包含两个Python文件:

  1. train_network_keras.py:这是我们将使用严格的KLAS实现的第一个训练脚本。
  2. train_network_tf.py:TensorFlow+Keras版本的训练脚本几乎是相同的;我们将遍历它,同时强调差异。

每个脚本也将生成相应的训练精度/丢失图:

  1. plot_keras.png
  2. plot_tf.png

正如您从目录结构中看到的,今天我们将为Keras和TensorFlow(使用tf.keras模块)演示MiniVGGNet的实现+培训。

用Keras训练网络

图5:使用KIAS实现的MIVIGNNET美国有线电视新闻网网络架构。

训练我们的网络的第一步是在Keras实现网络体系结构。

我假设您已经熟悉了用Keras训练神经网络的基本原理——如果不熟悉,请参考这篇介绍性文章

打开minivggnetkeras.py文件并插入以下代码:

# import the necessary packages
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Dropout
from keras.layers.core import Dense
from keras.layers import Flatten
from keras.layers import Input
from keras.models import Model

首先,我们需要建立一组Keras导入来构建模型。

从这里,我们定义了我们的MiniVGGNetKeras 类:

class MiniVGGNetKeras:
	@staticmethod
	def build(width, height, depth, classes):
		# initialize the input shape and channel dimension, assuming
		# TensorFlow/channels-last ordering
		inputShape = (height, width, depth)
		chanDim = -1
 
		# define the model input
		inputs = Input(shape=inputShape)

我们在第12行定义构建方法,并定义输入形状和输入。我们将假设“通道最后”排序,这就是为什么深度是输入形状元组中的最后一个值。

让我们开始定义卷积神经网络的主体:

		# first (CONV => RELU) * 2 => POOL layer set
		x = Conv2D(32, (3, 3), padding="same")(inputs)
		x = Activation("relu")(x)
		x = BatchNormalization(axis=chanDim)(x)
		x = Conv2D(32, (3, 3), padding="same")(x)
		x = Activation("relu")(x)
		x = BatchNormalization(axis=chanDim)(x)
		x = MaxPooling2D(pool_size=(2, 2))(x)
		x = Dropout(0.25)(x)
 
		# second (CONV => RELU) * 2 => POOL layer set
		x = Conv2D(64, (3, 3), padding="same")(x)
		x = Activation("relu")(x)
		x = BatchNormalization(axis=chanDim)(x)
		x = Conv2D(64, (3, 3), padding="same")(x)
		x = Activation("relu")(x)
		x = BatchNormalization(axis=chanDim)(x)
		x = MaxPooling2D(pool_size=(2, 2))(x)
		x = Dropout(0.25)(x)

检查代码块时,您将注意到我们正在堆叠一系列卷积、ReLU激活和批量标准化层,然后应用池层来减少卷的空间维度。丢包也适用于减少过拟合。

为了简要回顾层类型和术语,请务必查看我以前的Keras教程来解释它们。为了深入学习,你应该拿起一本我的深度学习书,用Python进行计算机视觉的深度学习

让我们添加全连接(FC)层到网络:

		# first (and only) set of FC => RELU layers
		x = Flatten()(x)
		x = Dense(512)(x)
		x = Activation("relu")(x)
		x = BatchNormalization()(x)
		x = Dropout(0.5)(x)
 
		# softmax classifier
		x = Dense(classes)(x)
		x = Activation("softmax")(x)
 
		# create the model
		model = Model(inputs, x, name="minivggnet_keras")
 
		# return the constructed network architecture
		return model

我们的FC和SoftMax分类器被附加到网络上。然后我们定义神经网络模型并将其返回给调用函数。

现在我们已经在Keras中实现了美国有线电视新闻网,让我们创建用于训练它的驱动程序脚本。

打开train_network_keras.py并插入以下代码:

# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
 
# import the necessary packages
from pyimagesearch.minivggnetkeras import MiniVGGNetKeras
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from keras.optimizers import SGD
from keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
import argparse
 
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--plot", type=str, default="plot_keras.png",
	help="path to output loss/accuracy plot")
args = vars(ap.parse_args())

我们在2-13行导入我们需要的软件包。

注意以下事项:

  1. 在第3行,Matplotlib的后端设置为“Agg”,这样我们就可以将我们的训练图保存为图像文件。
  2. 在第6行,我们导入MiniVGGNetKeras类。
  3. 我们使用scikit-learning的LabelBinarizer用于“单热”编码及其classification_report来打印分类精度统计数据(第7和8行)。
  4. 我们的数据集方便地在第10行导入。如果您想学习如何使用自定义数据集,我建议您参考前面的Keras教程或这篇文章,其中展示了如何使用Keras进行实际示例

我们唯一的命令行参数(我们的输出-绘图路径)在16-19行解析。

让我们加载CIFAR-10并对标签进行编码:

# load the training and testing data, then scale it into the
# range [0, 1]
print("[INFO] loading CIFAR-10 data...")
split = cifar10.load_data()
((trainX, trainY), (testX, testY)) = split
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
 
# convert the labels from integers to vectors
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
 
# initialize the label names for the CIFAR-10 dataset
labelNames = ["airplane", "automobile", "bird", "cat", "deer",
	"dog", "frog", "horse", "ship", "truck"]

我们在第24和25行加载和提取训练和测试分段,并将第26和27行的数据转换为浮点+刻度。

我们对我们的标签进行编码,并在30-36行初始化实际的标签名。

接下来,让我们来训练这个模型:

# initialize the initial learning rate, total number of epochs to
# train for, and batch size
INIT_LR = 0.01
EPOCHS = 30
BS = 32
 
# initialize the optimizer and model
print("[INFO] compiling model...")
opt = SGD(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model = MiniVGGNetKeras.build(width=32, height=32, depth=3,
	classes=len(labelNames))
model.compile(loss="categorical_crossentropy", optimizer=opt,
	metrics=["accuracy"])
 
# train the network
print("[INFO] training network for {} epochs...".format(EPOCHS))
H = model.fit(trainX, trainY, validation_data=(testX, testY),
	batch_size=BS, epochs=EPOCHS, verbose=1)

建立了训练参数和优化方法(第40-46行)。

然后我们使用我们的 MiniVGGNetKeras.build 方法初始化我们的模型并编译它(第45-50行)。

随后,我们开始训练程序(第54和第55行)。

让我们评估网络并生成一个绘图:

# evaluate the network
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32)
print(classification_report(testY.argmax(axis=1),
	predictions.argmax(axis=1), target_names=labelNames))
 
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, EPOCHS), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, EPOCHS), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, EPOCHS), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, EPOCHS), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy on Dataset")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="lower left")
plt.savefig(args["plot"])

在这里,我们评估网络对我们测试数据的分割,并生成一个分类报告。最后,我们组合并输出我们的绘图。

注意:通常,我会在这里序列化并导出我们的模型,以便可以在图像或视频处理脚本中使用它,但是今天我们不打算这样做,因为这超出了本教程的范围。

要运行我们的脚本,请确保使用博客帖子的“下载”部分来下载源代码。

打开一个终端并执行以下命令:

$ python train_network_keras.py
Using TensorFlow backend.
[INFO] loading CIFAR-10 data...
[INFO] compiling model...
[INFO] training network for 30 epochs...
Train on 50000 samples, validate on 10000 samples
Epoch 1/30
50000/50000 [==============================] - 328s 7ms/step - loss: 1.7652 - acc: 0.4183 - val_loss: 1.2965 - val_acc: 0.5326
Epoch 2/30
50000/50000 [==============================] - 325s 6ms/step - loss: 1.2549 - acc: 0.5524 - val_loss: 1.1068 - val_acc: 0.6036
Epoch 3/30
50000/50000 [==============================] - 324s 6ms/step - loss: 1.1191 - acc: 0.6030 - val_loss: 0.9818 - val_acc: 0.6509
...
Epoch 28/30
50000/50000 [==============================] - 337s 7ms/step - loss: 0.7673 - acc: 0.7315 - val_loss: 0.7307 - val_acc: 0.7422
Epoch 29/30
50000/50000 [==============================] - 330s 7ms/step - loss: 0.7594 - acc: 0.7346 - val_loss: 0.7284 - val_acc: 0.7447
Epoch 30/30
50000/50000 [==============================] - 324s 6ms/step - loss: 0.7568 - acc: 0.7359 - val_loss: 0.7244 - val_acc: 0.7432
[INFO] evaluating network...
             precision    recall  f1-score   support
 
   airplane       0.81      0.73      0.77      1000
 automobile       0.92      0.80      0.85      1000
       bird       0.68      0.56      0.61      1000
        cat       0.56      0.55      0.56      1000
       deer       0.64      0.77      0.70      1000
        dog       0.69      0.64      0.66      1000
       frog       0.72      0.88      0.79      1000
      horse       0.88      0.72      0.79      1000
       ship       0.80      0.90      0.85      1000
      truck       0.78      0.89      0.83      1000
 
avg / total       0.75      0.74      0.74     10000

我的CPU每完成一个都要花上5分钟。

图6:用Matplotlib绘制精度/损耗训练曲线。这个网络是和Keras一起训练的

从终端输出中可以看出,我们在测试集上获得了75%的精确度——当然不是最先进的;然而,它远远优于随机猜测(1/10)。

对于一个小网络来说,我们的准确性其实相当不错!

正如我们的输出图在图6中演示的那样,没有发生过拟合。

用TensorFlow和tf.keras训练网络

Figure 7: The MiniVGGNet CNN architecture built with tf.keras(a module which is built into TensorFlow) is identical to the model that we built with Keras directly. They are one and the same with the exception of the activation function which I have changed for demonstration purposes.

既然我们已经使用Keras库实现并训练了一个简单的美国有线电视新闻网,那么让我们来学习一下:

  1. 使用TensorFlow的tf.keras实现相同的网络体系结构
  2. 在我们的Keras模型中包含一个TensorFlow激活函数,在Keras本身中没有实现。

为了开始,打开activation文件,我们将实现MiniVGGNet的TensorFlow版本:

# import the necessary packages
import tensorflow as tf
 
class MiniVGGNetTF:
	@staticmethod
	def build(width, height, depth, classes):
		# initialize the input shape and channel dimension, assuming
		# TensorFlow/channels-last ordering
		inputShape = (height, width, depth)
		chanDim = -1
 
		# define the model input
		inputs = tf.keras.layers.Input(shape=inputShape)
 
		# first (CONV => RELU) * 2 => POOL layer set
		x = tf.keras.layers.Conv2D(32, (3, 3), padding="same")(inputs)
		x = tf.keras.layers.Activation("relu")(x)
		x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)
		x = tf.keras.layers.Conv2D(32, (3, 3), padding="same")(x)
		x = tf.keras.layers.Lambda(lambda t: tf.nn.crelu(x))(x)
		x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)
		x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)
		x = tf.keras.layers.Dropout(0.25)(x)
 
		# second (CONV => RELU) * 2 => POOL layer set
		x = tf.keras.layers.Conv2D(64, (3, 3), padding="same")(x)
		x = tf.keras.layers.Lambda(lambda t: tf.nn.crelu(x))(x)
		x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)
		x = tf.keras.layers.Conv2D(64, (3, 3), padding="same")(x)
		x = tf.keras.layers.Lambda(lambda t: tf.nn.crelu(x))(x)
		x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)
		x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)
		x = tf.keras.layers.Dropout(0.25)(x)
 
		# first (and only) set of FC => RELU layers
		x = tf.keras.layers.Flatten()(x)
		x = tf.keras.layers.Dense(512)(x)
		x = tf.keras.layers.Lambda(lambda t: tf.nn.crelu(x))(x)
		x = tf.keras.layers.BatchNormalization()(x)
		x = tf.keras.layers.Dropout(0.5)(x)
 
		# softmax classifier
		x = tf.keras.layers.Dense(classes)(x)
		x = tf.keras.layers.Activation("softmax")(x)
 
		# create the model
		model = tf.keras.models.Model(inputs, x, name="minivggnet_tf")
 
		# return the constructed network architecture
		return model

在该文件中,注意导入由单个行(第2行)替换。TF.KARAStf.keras子模块包含我们可以直接调用的所有keras功能。

我想提醒大家注意Lambda层——它们用于插入定制的激活函数CRELU(级联的 ReLUs),这是基于Shang等人的《通过级联整流线性单元理解和改进卷积神经网络》一文的。这些线条用灰色突出显示。

CRELU不是在Keras中实现的,而是在TensorFlow中实现的——通过使用TensorFlow和tf.keras,我们只需一行代码就可以将CRELU添加到Keras模型中。

注意:CRELU有两个输出,一个正RELU和一个负Relu。对于正x值,CRELU将返回[x,0 ],而对于负x值,CRULU将返回[0,x]。欲了解更多信息,请参阅这里

下一步是实现我们的TensorFlow+Keras驱动程序脚本来训练MiniVGGNetTF。

打开train_network_tf.py并插入以下代码:

# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
 
# import the necessary packages
from pyimagesearch.minivggnettf import MiniVGGNetTF
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import argparse
 
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--plot", type=str, default="plot_tf.png",
	help="path to output loss/accuracy plot")
args = vars(ap.parse_args())
 
# load the training and testing data, then scale it into the
# range [0, 1]
print("[INFO] loading CIFAR-10 data...")
split = tf.keras.datasets.cifar10.load_data()
((trainX, trainY), (testX, testY)) = split
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
 
# convert the labels from integers to vectors
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
 
# initialize the label names for the CIFAR-10 dataset
labelNames = ["airplane", "automobile", "bird", "cat", "deer",
	"dog", "frog", "horse", "ship", "truck"]

我们的输入在2-12行。与我们的Keras训练脚本相比,惟一的改变包括导入MiniVGGNetTF类和导入tensorflow as tf而不是Keras。

我们的命令行参数在15到18行解析。

然后我们像以前一样在第23行加载数据。

其余的行是相同的-提取训练/测试分割和编码我们的标签。

让我们来训练我们的模型:

# initialize the initial learning rate, total number of epochs to
# train for, and batch size
INIT_LR = 0.01
EPOCHS = 30
BS = 32
 
# initialize the optimizer and model
print("[INFO] compiling model...")
opt = tf.keras.optimizers.SGD(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model = MiniVGGNetTF.build(width=32, height=32, depth=3,
	classes=len(labelNames))
model.compile(loss="categorical_crossentropy", optimizer=opt,
	metrics=["accuracy"])
 
# train the network
print("[INFO] training network for {} epochs...".format(EPOCHS))
H = model.fit(trainX, trainY, validation_data=(testX, testY),
	batch_size=BS, epochs=EPOCHS, verbose=1)
 
# evaluate the network
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32)
print(classification_report(testY.argmax(axis=1),
	predictions.argmax(axis=1), target_names=labelNames))
 
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, EPOCHS), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, EPOCHS), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, EPOCHS), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, EPOCHS), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy on Dataset")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="lower left")
plt.savefig(args["plot"])

在39-54行上进行的训练过程是相同的,除了那些用灰色突出显示的训练过程之外,其中只注意细微的变化。

从那里我们评估和绘制我们的数据(线58-63)。

正如你所看到的,我们已经实现了完全相同的训练过程,只是现在我们在使用tf.keras。

若要运行此脚本,请确保使用博客帖子的“下载”部分来获取代码。

从那里打开一个终端并执行以下命令:

$ python train_network_tf.py
[INFO] loading CIFAR-10 data...
[INFO] compiling model...
[INFO] training network for 30 epochs...
Train on 50000 samples, validate on 10000 samples
Epoch 1/30
50000/50000 [==============================] - 457s 9ms/step - loss: 1.7024 - acc: 0.4369 - val_loss: 1.3181 - val_acc: 0.5253
Epoch 2/30
50000/50000 [==============================] - 441s 9ms/step - loss: 1.1981 - acc: 0.5761 - val_loss: 1.1025 - val_acc: 0.6072
Epoch 3/30
50000/50000 [==============================] - 441s 9ms/step - loss: 1.0506 - acc: 0.6317 - val_loss: 1.0647 - val_acc: 0.6227
...
Epoch 28/30
50000/50000 [==============================] - 367s 7ms/step - loss: 0.6798 - acc: 0.7611 - val_loss: 0.7161 - val_acc: 0.7479
Epoch 29/30
50000/50000 [==============================] - 364s 7ms/step - loss: 0.6732 - acc: 0.7639 - val_loss: 0.6969 - val_acc: 0.7544
Epoch 30/30
50000/50000 [==============================] - 366s 7ms/step - loss: 0.6743 - acc: 0.7641 - val_loss: 0.6973 - val_acc: 0.7550
[INFO] evaluating network...
             precision    recall  f1-score   support
 
   airplane       0.86      0.69      0.76      1000
 automobile       0.93      0.79      0.85      1000
       bird       0.75      0.59      0.66      1000
        cat       0.59      0.55      0.57      1000
       deer       0.65      0.78      0.71      1000
        dog       0.70      0.66      0.68      1000
       frog       0.67      0.93      0.78      1000
      horse       0.90      0.75      0.82      1000
       ship       0.81      0.91      0.86      1000
      truck       0.80      0.89      0.84      1000
 
avg / total       0.76      0.76      0.75     10000

训练结束后,你有一个类似下面的训练绘图:

通过将CRELU替换为RELU激活函数,我们获得了76%的精度;然而,1%的增长可能是由于网络中权重的随机初始化——需要进一步的交叉验证实验来证明CRELU确实对此负责。提高精度。

然而,原始精度不是本节的重要方面。

相反,关注我们如何在TensorFlow激活函数中替换Keras模型中的标准Keras激活函数!

您也可以用自己的自定义激活函数、损失/成本函数或层实现来实现同样的操作。

总结

在今天的博客文章中,我们讨论了围绕Keras vs. TensorFlow的问题,包括:

  1. 我应该用Keras vs. TensorFlow来做我的项目吗?
  2. TensorFlow还是Keras更好?
  3. 我该把时间花在studying TensorFlow身上吗?还是Keras?

最终,我们发现,试图决定Keras和TensorFlow之间的关系变得越来越无关紧要。

Keras库已通过tf.keras模块直接集成到TensorFlow中。

基本上,您可以使用易于使用的Keras API编写模型和培训过程,然后使用纯TensorFlow将自定义实现添加到模型或培训过程中!

如果你正在试图从深层学习开始,试图为下一个项目在Keras或TensorFlow之间做出决定,或者只是想知道Keras或TensorFlow是否“更好”……那么是时候寻求一些动了。

我对你的建议很简单:

  1. 直接动手
  2. 在Python项目中键入导入Keras或导入tensorflow as tf(这样您就可以访问tf.keras)并开始工作。
  3. TensorFlow可以直接集成到您的模型或培训过程中,因此不需要比较特性、功能或易用性——所有TensorFlow和Keras都可以在项目中使用。


原文链接:Keras vs. TensorFlow – Which one is better and which one should I learn?(同代码下载链接)

翻译:Vivian


更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: