Keras 简明教程
Keras - Modules
正如我们先前了解的,Keras 模块包含预定义的类、函数和变量,它们对深度学习算法非常有用。让我们在本节中了解 Keras 提供的模块。
As we learned earlier, Keras modules contains pre-defined classes, functions and variables which are useful for deep learning algorithm. Let us learn the modules provided by Keras in this chapter.
Available modules
让我们首先查看 Keras 中可用模块的列表。
Let us first see the list of modules available in the Keras.
-
Initializers − Provides a list of initializers function. We can learn it in details in Keras layer chapter. during model creation phase of machine learning.
-
Regularizers − Provides a list of regularizers function. We can learn it in details in Keras Layers chapter.
-
Constraints − Provides a list of constraints function. We can learn it in details in Keras Layers chapter.
-
Activations − Provides a list of activator function. We can learn it in details in Keras Layers chapter.
-
Losses − Provides a list of loss function. We can learn it in details in Model Training chapter.
-
Metrics − Provides a list of metrics function. We can learn it in details in Model Training chapter.
-
Optimizers − Provides a list of optimizer function. We can learn it in details in Model Training chapter.
-
Callback − Provides a list of callback function. We can use it during the training process to print the intermediate data as well as to stop the training itself (EarlyStopping method) based on some condition.
-
Text processing − Provides functions to convert text into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning.
-
Image processing − Provides functions to convert images into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning.
-
Sequence processing − Provides functions to generate time based data from the given input data. We can use it in data preparation phase of machine learning.
-
Backend − Provides function of the backend library like TensorFlow and Theano.
-
Utilities − Provides lot of utility function useful in deep learning.
让我们在本节中了解 backend 模块和 utils 模型。
Let us see backend module and utils model in this chapter.
backend module
backend module 用于 keras 后台操作。默认情况下,keras 在 TensorFlow 后台上运行。如果您愿意,您可以切换到其他后端,如 Theano 或 CNTK。Deufalt 后台配置在您的根目录下的 .keras/keras.json 文件中定义。
backend module is used for keras backend operations. By default, keras runs on top of TensorFlow backend. If you want, you can switch to other backends like Theano or CNTK. Defualt backend configuration is defined inside your root directory under .keras/keras.json file.
可以使用以下代码导入 Keras 后台模块
Keras backend module can be imported using below code
>>> from keras import backend as k
如果我们使用默认后端 TensorFlow,那么以下函数将返回如下指定的基于 TensorFlow 的信息 −
If we are using default backend TensorFlow, then the below function returns TensorFlow based information as specified below −
>>> k.backend()
'tensorflow'
>>> k.epsilon()
1e-07
>>> k.image_data_format()
'channels_last'
>>> k.floatx()
'float32'
让我们简要了解一些用于数据分析的重要后台函数 −
Let us understand some of the significant backend functions used for data analysis in brief −
get_uid()
它是默认图形的标识符。它在下面定义 −
It is the identifier for the default graph. It is defined below −
>>> k.get_uid(prefix='')
1
>>> k.get_uid(prefix='') 2
reset_uids
它用于重置 uid 值。
It is used resets the uid value.
>>> k.reset_uids()
现在,再次执行 get_uid()。这将被重置,并再次变为 1。
Now, again execute the get_uid(). This will be reset and change again to 1.
>>> k.get_uid(prefix='')
1
placeholder
用于实例化占位符张量。简单的占位符以保存 3D 形状的示例如下 −
It is used instantiates a placeholder tensor. Simple placeholder to hold 3-D shape is shown below −
>>> data = k.placeholder(shape = (1,3,3))
>>> data
<tf.Tensor 'Placeholder_9:0' shape = (1, 3, 3) dtype = float32>
If you use int_shape(), it will show the shape.
>>> k.int_shape(data) (1, 3, 3)
dot
它用于将两个张量相乘。考虑 a 和 b 是两个张量,而 c 将是 ab 乘法的结果。假定 a 的形状是 (4,2),而 b 的形状是 (2,3)。它在下面定义,
It is used to multiply two tensors. Consider a and b are two tensors and c will be the outcome of multiply of ab. Assume a shape is (4,2) and b shape is (2,3). It is defined below,
>>> a = k.placeholder(shape = (4,2))
>>> b = k.placeholder(shape = (2,3))
>>> c = k.dot(a,b)
>>> c
<tf.Tensor 'MatMul_3:0' shape = (4, 3) dtype = float32>
>>>
ones
它用于将所有内容初始化为 one 值。
It is used to initialize all as one value.
>>> res = k.ones(shape = (2,2))
#print the value
>>> k.eval(res)
array([[1., 1.], [1., 1.]], dtype = float32)
batch_dot
它用于对批次中的两个数据执行乘积。输入维度必须为 2 或更高。如下所示:
It is used to perform the product of two data in batches. Input dimension must be 2 or higher. It is shown below −
>>> a_batch = k.ones(shape = (2,3))
>>> b_batch = k.ones(shape = (3,2))
>>> c_batch = k.batch_dot(a_batch,b_batch)
>>> c_batch
<tf.Tensor 'ExpandDims:0' shape = (2, 1) dtype = float32>
variable
它用于初始化变量。让我们在这个变量中执行简单的转置操作。
It is used to initializes a variable. Let us perform simple transpose operation in this variable.
>>> data = k.variable([[10,20,30,40],[50,60,70,80]])
#variable initialized here
>>> result = k.transpose(data)
>>> print(result)
Tensor("transpose_6:0", shape = (4, 2), dtype = float32)
>>> print(k.eval(result))
[[10. 50.]
[20. 60.]
[30. 70.]
[40. 80.]]
如果你希望从 numpy 访问:
If you want to access from numpy −
>>> data = np.array([[10,20,30,40],[50,60,70,80]])
>>> print(np.transpose(data))
[[10 50]
[20 60]
[30 70]
[40 80]]
>>> res = k.variable(value = data)
>>> print(res)
<tf.Variable 'Variable_7:0' shape = (2, 4) dtype = float32_ref>
is_sparse(tensor)
它用于检查张量是否是稀疏张量。
It is used to check whether the tensor is sparse or not.
>>> a = k.placeholder((2, 2), sparse=True)
>>> print(a) SparseTensor(indices =
Tensor("Placeholder_8:0",
shape = (?, 2), dtype = int64),
values = Tensor("Placeholder_7:0", shape = (?,),
dtype = float32), dense_shape = Tensor("Const:0", shape = (2,), dtype = int64))
>>> print(k.is_sparse(a)) True
to_dense()
它用于将稀疏张量转换为稠密张量。
It is used to converts sparse into dense.
>>> b = k.to_dense(a)
>>> print(b) Tensor("SparseToDense:0", shape = (2, 2), dtype = float32)
>>> print(k.is_sparse(b)) False
random_uniform_variable
它用于在 uniform distribution 概念下初始化。
It is used to initialize using uniform distribution concept.
k.random_uniform_variable(shape, mean, scale)
在此,
Here,
-
shape − denotes the rows and columns in the format of tuples.
-
mean − mean of uniform distribution.
-
scale − standard deviation of uniform distribution.
让我们看一下下面的示例用法:
Let us have a look at the below example usage −
>>> a = k.random_uniform_variable(shape = (2, 3), low=0, high = 1)
>>> b = k. random_uniform_variable(shape = (3,2), low = 0, high = 1)
>>> c = k.dot(a, b)
>>> k.int_shape(c)
(2, 2)
utils module
utils 提供了深度学习的有用实用程序函数。 utils 模块提供的一些方法如下:
utils provides useful utilities function for deep learning. Some of the methods provided by the utils module is as follows −
HDF5Matrix
它用于以 HDF5 格式表示输入数据。
It is used to represent the input data in HDF5 format.
from keras.utils import HDF5Matrix data = HDF5Matrix('data.hdf5', 'data')
to_categorical
它用于将类别向量转换为二进制类别矩阵。
It is used to convert class vector into binary class matrix.
>>> from keras.utils import to_categorical
>>> labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> to_categorical(labels)
array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]], dtype = float32)
>>> from keras.utils import normalize
>>> normalize([1, 2, 3, 4, 5])
array([[0.13483997, 0.26967994, 0.40451992, 0.53935989, 0.67419986]])
print_summary
它用于打印模型摘要。
It is used to print the summary of the model.
from keras.utils import print_summary print_summary(model)
plot_model
它用于创建 dot 格式的模型表示形式并将其保存到文件中。
It is used to create the model representation in dot format and save it to file.
from keras.utils import plot_model
plot_model(model,to_file = 'image.png')
此 plot_model 将生成图像以了解模型的性能。
This plot_model will generate an image to understand the performance of model.