如何使用 Tensorflow 获取层中的变量?
可以使用 Tensorflow 获取层中的变量,方法是使用‘layer.Variables’显示层中的变量,然后使用‘layer.kernel’和‘layer.bias’访问这些变量。
阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?
包含至少一个层的神经网络称为卷积层。我们可以使用卷积神经网络来构建学习模型。
图像分类迁移学习背后的直觉是,如果一个模型是在大型通用数据集上训练的,那么这个模型可以有效地用作视觉世界的通用模型。它会学习特征图,这意味着用户不必从头开始在大型数据集上训练大型模型。
TensorFlow Hub 是一个包含预训练 TensorFlow 模型的存储库。 TensorFlow 可用于微调学习模型。
我们将了解如何将 TensorFlow Hub 中的模型与 tf.keras 结合使用,使用 TensorFlow Hub 中的图像分类模型。 完成此操作后,可以执行迁移学习以微调自定义图像类别的模型。这是通过使用预训练的分类器模型来获取图像并预测其内容来完成的。这可以在不需要任何训练的情况下完成。
我们正在使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,并且不需要任何配置,并且可以免费访问 GPU(图形处理单元)。 Colaboratory 是在 Jupyter Notebook 基础上构建的。
示例
print("The variables in a layer") print(layer.variables) print("Variables can be accessed through nice accessors") print(layer.kernel, layer.bias)
代码来源 −https://www.tensorflow.org/tutorials/customization/custom_layers
输出
The variables in a layer [<tf.Variable 'dense_5/kernel:0' shape=(5, 10) dtype=float32, numpy= array([[-0.05103415, -0.6048388 , -0.09445673, 0.00147319, 0.5958504 , 0.03832638, -0.4617405 , 0.22488767, -0.521616 , -0.4939174 ], [ 0.2143982 , -0.42745167, -0.19899327, 0.011585 , 0.39148778, -0.5193864 , 0.11133379, 0.07244939, -0.42842603, -0.07152319], [ 0.09674573, 0.08572572, -0.44079286, -0.10669523, 0.1977045 , 0.04525411, 0.41716915, 0.2611121 , -0.1167441 , -0.26781783], [ 0.38834113, -0.5396006 , -0.33349523, -0.5882891 , -0.2575687 , -0.33869067, 0.56990904, 0.3368895 , 0.6290985 , -0.31278375], [-0.40759754, 0.18778783, 0.11296159, 0.35683256, -0.16895893, -0.55790913, 0.5088188 , -0.06520861, -0.24566567, -0.15854272]], dtype=float32)>, <tf.Variable 'dense_5/bias:0' shape=(10,) dtype=float32, numpy=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)>] Variables can be accessed through nice accessors <tf.Variable 'dense_5/kernel:0' shape=(5, 10) dtype=float32, numpy= array([[-0.05103415, -0.6048388 , -0.09445673, 0.00147319, 0.5958504 , 0.03832638, -0.4617405 , 0.22488767, -0.521616 , -0.4939174 ], [ 0.2143982 , -0.42745167, -0.19899327, 0.011585 , 0.39148778, -0.5193864 , 0.11133379, 0.07244939, -0.42842603, -0.07152319], [ 0.09674573, 0.08572572, -0.44079286, -0.10669523, 0.1977045 , 0.04525411, 0.41716915, 0.2611121 , -0.1167441 , -0.26781783], [ 0.38834113, -0.5396006 , -0.33349523, -0.5882891 , -0.2575687 , -0.33869067, 0.56990904, 0.3368895 , 0.6290985 , -0.31278375], [-0.40759754, 0.18778783, 0.11296159, 0.35683256, -0.16895893, -0.55790913, 0.5088188 , -0.06520861, -0.24566567, -0.15854272]], dtype=float32)> <tf.Variable 'dense_5/bias:0' shape=(10,) dtype=float32, numpy=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)>
解释
- 层有许多方法。
- 可以使用层中的方法检查所有变量。
- 全连接层将具有权重和偏差变量。