Keras - 模块
正如我们之前所学,Keras 模块包含了预定义的 class、function 和变量,这些对深度学习算法非常有用。本章我们来学习 Keras 提供的模块。
可用模块
让我们先来看看 Keras 中可用的模块列表。
Initializers − 提供了一系列 initializer function。我们可以在 Keras 层章节中详细学习它们,在机器学习模型创建阶段使用。
Regularizers − 提供了一系列 regularizer function。我们可以在 Keras Layers 章节中详细学习。
Constraints − 提供了一系列 constraint function。我们可以在 Keras Layers 章节中详细学习。
Activations − 提供了一系列 activation function。我们可以在 Keras Layers 章节中详细学习。
Losses − 提供了一系列 loss function。我们可以在 模型训练 章节中详细学习。
Metrics − 提供了一系列 metrics function。我们可以在 模型训练 章节中详细学习。
Optimizers − 提供了一系列 optimizer function。我们可以在 模型训练 章节中详细学习。
Callback − 提供了一系列 callback function。我们可以在训练过程中使用它们来打印中间数据,或者根据某些条件停止训练本身(如 EarlyStopping 方法)。
Text processing − 提供将文本转换为适合机器学习的 NumPy array 的 function。我们可以在机器学习的数据准备阶段使用。
Image processing − 提供将图像转换为适合机器学习的 NumPy array 的 function。我们可以在机器学习的数据准备阶段使用。
Sequence processing − 提供从给定输入数据生成时间序列数据的 function。我们可以在机器学习的数据准备阶段使用。
Backend − 提供后端库(如 TensorFlow 和 Theano)的 function。
Utilities − 提供了大量在深度学习中实用的 utility function。
本章我们来看 backend 模块和 utils 模块。
backend 模块
backend 模块 用于 Keras backend 操作。默认情况下,Keras 运行在 TensorFlow backend 之上。如果需要,可以切换到其他 backend,如 Theano 或 CNTK。默认 backend 配置定义在根目录下的 .keras/keras.json 文件中。
Keras backend 模块可以通过以下代码导入
>>> from keras import backend as k
如果使用默认 backend TensorFlow,则以下函数将返回如下的 TensorFlow 相关信息 −
>>> k.backend() 'tensorflow' >>> k.epsilon() 1e-07 >>> k.image_data_format() 'channels_last' >>> k.floatx() 'float32'
让我们简要了解一些用于数据分析的重要 backend 函数 −
get_uid()
它是默认图的标识符。定义如下 −
>>> k.get_uid(prefix='') 1 >>> k.get_uid(prefix='') 2
reset_uids
用于重置 uid 值。
>>> k.reset_uids()
现在,再次执行 get_uid()。它将被重置并重新变为 1。
>>> k.get_uid(prefix='') 1
placeholder
用于实例化一个占位符 tensor。以下是一个用于保存 3-D 形状的简单占位符示例 −
>>> data = k.placeholder(shape = (1,3,3)) >>> data <tf.Tensor 'Placeholder_9:0' shape = (1, 3, 3) dtype = float32> 如果使用 int_shape(),它将显示形状。 >>> k.int_shape(data) (1, 3, 3)
dot
用于两个 tensor 的乘法运算。假设 a 和 b 是两个 tensor,c 是 a 和 b 乘积的结果。假设 a 的形状为 (4,2),b 的形状为 (2,3)。定义如下,
>>> 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
用于将所有元素初始化为 1 值。
>>> res = k.ones(shape = (2,2)) #print the value >>> k.eval(res) array([[1., 1.], [1., 1.]], dtype = float32)
batch_dot
用于对批次中的两个数据执行乘积运算。输入维度必须为 2 或更高。如以下所示 −
>>> 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
用于初始化一个 variable。让我们在这个 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 访问 −
>>> 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)
用于检查 tensor 是否为稀疏 tensor。
>>> 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()
用于将稀疏 tensor 转换为稠密 tensor。
>>> b = k.to_dense(a)
>>> print(b) Tensor("SparseToDense:0", shape = (2, 2), dtype = float32)
>>> print(k.is_sparse(b)) False
random_uniform_variable
使用 均匀分布 概念进行初始化。
k.random_uniform_variable(shape, mean, scale)
其中,
shape − 以元组格式表示行数和列数。
mean − 均匀分布的均值。
scale − 均匀分布的标准差。
以下是示例用法 −
>>> 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 模块
utils 为深度学习提供了实用的工具函数。utils 模块提供的一些方法如下 −
HDF5Matrix
用于以 HDF5 格式表示输入数据。
from keras.utils import HDF5Matrix data = HDF5Matrix('data.hdf5', 'data')
to_categorical
用于将类别向量转换为二进制类别矩阵。
>>> 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
用于打印模型的摘要。
from keras.utils import print_summary print_summary(model)
plot_model
用于创建模型的 dot 格式表示并保存到文件。
from keras.utils import plot_model plot_model(model,to_file = 'image.png')
此 plot_model 将生成一张图像,以了解模型的性能。