tensorflow 代码
介绍:(Introduction:)
Learning to develop Deep Learning models is not an easy task to accomplish — especially for those who may not have serious experience in the field. When beginning to learn how to build a DL model in TensorFlow, the workflow usually goes as follows:
学习开发深度学习模型并非易事,特别是对于那些在该领域没有丰富经验的人而言。 开始学习如何在TensorFlow中构建DL模型时,工作流程通常如下:
import tensorflow as tf
import tensorflow.keras as keras
# Import data
mnist = keras.datasets.mnist
# If you print shape, you will see the image sizes are (28,28)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Taken from basic image classification tutorial
# https://www.tensorflow.org/tutorials/images/cnn
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
# Compile model
model.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train model
model.fit(x_train, y_train, epochs = 10)
# From here, we can test and evaluate our model and do whatever we want with it.
However, if deployment or more technical models come into the picture, this format of building models may be more of a liability to your time than an asset. Python’s object oriented nature comes into play quite nicely to make it more of the latter rather than the former. This tutorial will break down the workflow in developing more robust models.
但是,如果需要部署或更多技术模型,则这种构建模型格式可能对您的时间负有更多的责任,而不是资产。 Python的面向对象特性非常好地发挥了作用,使它更多地是后者而不是前者。 本教程将分解开发更强大模型的工作流程。
遗产: (Inheritance:)
When observing the gist
above, we can see that we initialized keras.Sequential
, which is of class type tf.keras.Model
. By adding a list of layers as a parameter
, we initialize the layers to be called — in order — for the forward pass.
当观察上面的gist
,我们可以看到我们初始化了keras.Sequential
,它是类类型tf.keras.Model
。 通过添加图层列表作为parameter
,我们可以按顺序初始化要调用的图层。
We can use what is called class inheritance
to build upon TensorFlow Models. By inheriting the tf.keras.Model
class, we can incorporate our own layers to the model and build our forward pass from there.
我们可以使用所谓的class inheritance
来构建TensorFlow模型。 通过继承tf.keras.Model
类,我们可以将自己的图层合并到模型中,并从那里构建向前传递。
For examples such as simple classification, such as the example above, doing this might be a bit convoluted (pun intended.) With this in mind, I will still continue on with the same model as above. If you understand the basics of TensorFlow’s API, then you will be able to see how the calls in the above gist translate to developing more object-oriented code, which is the main aim of this article.
对于诸如简单分类之类的示例(例如上述示例),这样做可能有点费解(双关语。)考虑到这一点,我仍将继续使用与上述相同的模型。 如果您了解TensorFlow API的基础知识,那么您将能够看到上述要点中的调用如何转化为开发更多的面向对象的代码,这是本文的主要目的。
When inheriting a tf.keras.Model
class, there are two main steps to consider:
继承tf.keras.Model
类时,需要考虑两个主要步骤:
Initializing the necessary layers in the model — within
__init__
.在
__init__
初始化模型中必要的层。Ordering the model’s forward pass — within
call
.订购模型的前向传递—在
call
。
class MNISTClassifier(tf.keras.Model):
def __init__(self):
# Initialize the necessary components of tf.keras.Model
super(MNISTClassifier, self).__init__()
# Now we initalize the needed layers - order does not matter.
# -----------------------------------------------------------
# Flatten Layer
self.flatten = keras.layers.Flatten()
# First Dense Layer
self.dense1 = keras.layers.Dense(128, activation = tf.nn.relu)
# Output Layer
self.dense2 = keras.layers.Dense(10)
# Forward pass of model - order does matter.
def call(self, inputs):
x = self.flatten(inputs)
x = self.dense1(x)
return self.dense2(x) # Return results of Output Layer
# Initialize classifier like model
classifier = MNISTClassifier()
# Compile model
classifier.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Fit model
classifier.fit(x_train, y_train, epochs = 10)
初始化类:(Initializing Class:)
For __init__
, we have 4 main steps.
对于__init__
,我们有4个主要步骤。
First, we bring in the
__init__
of thesuper
— which in this case istf.keras.Model
.首先,我们引入
super
的__init__
,在本例中为tf.keras.Model
。Second, we initialize the
Flatten
layer.其次,我们初始化
Flatten
层。Third, we initialize the
Dense
layer with128
units and activationtf.nn.relu
. It is important to note that when we called the activation function in the first gist, we used a string ('relu'
as opposed totf.nn.relu
.) When building our own model classes, we must call our activation functions from thetf.nn
module.第三,我们以
128
单位初始化Dense
层并激活tf.nn.relu
。 重要的是要注意,当我们在第一个要点中调用激活函数时,我们使用了一个字符串('relu'
,而不是tf.nn.relu
。)在构建自己的模型类时,必须从tf.nn
模块。Fourth, we initialize the final
Dense
layer with10
units.第四,我们用
10
单位初始化最终的Dense
层。
For coherency, always initialize the __init__
of the super
first. This will ensure that when you call the class in usage, it will load in as a tf.keras.Model
. The order of the initialization of the layers does not matter.
为了保持一致性,请始终首先初始化super
的__init__
。 这样可以确保在使用中调用该类时,该类将作为tf.keras.Model
。 层的初始化顺序无关紧要。
呼叫: (Call:)
When defining call
, we are defining the forward pass of the model. We have parameters inputs
which, when fitting, will be x_train
. Therefore, within call
it will resemble the ordering of the layers in the first gist. However, as opposed to a list of layers — and relying on fit
to determine the forward pass from it — we must explicitly determine x
going in the Flatten
layer first — which is self.flatten
, then pass that into the self.dense1
layer, then finally output the results of the self.dense2
layer.
在定义call
,我们正在定义模型的前向传递。 我们有参数inputs
,拟合时将为x_train
。 因此,在call
内,它将类似于第一个要点中各层的顺序。 但是,与层列表相反,并依靠fit
来确定它的前向传递,我们必须首先明确确定x
进入Flatten
层(即self.flatten
,然后将其传递到self.dense1
层,然后最后输出self.dense2
层的结果。
结论: (Conclusion:)
This article should serve as a general guide to building more object oriented code. Understanding the workflow for custom models allows for more freedom and experimentation in your research. I hope this article was beneficial to you.
本文应作为构建更多面向对象代码的一般指南。 了解自定义模型的工作流程将为您的研究提供更多自由和实验机会。 希望本文对您有所帮助。
Thank you for reading.
感谢您的阅读。
翻译自: https://towardsdatascience.com/tensorflow-class-inheritance-beautiful-code-59d2eb7cdfce
tensorflow 代码