python - 如何在 Tensorflow 2 中获取 Conv2D 内核值

标签 python tensorflow keras google-cloud-platform

问题

我有一个Conv2D层:

l0 = tf.keras.layers.Conv2D(1, 3, activation=None, input_shape=(36,36,3))

我想找出所使用的过滤器/内核矩阵中的确切值(不仅仅是它们的数量)。 如何访问内核矩阵值?


解决方案尝试

import tensorflow as tf
import numpy as np

我创建了一个 numpy 数组:

x_core = np.array([[1,0,0,1],
                   [0,0,0,0],
                   [0,0,0,0],
                   [1,0,0,1]],dtype=float)

将其类型转换成形状(1,4,4,1)张量:

x = tf.expand_dims(tf.expand_dims(tf.convert_to_tensor(x_core),axis=0),axis=3)

申请Conv2D使用 strides=(2,2) 对其进行分层。这意味着输出将是一个 2 x 2 矩阵,其中左上角的值将等于内核矩阵中左上角的值,结果的右上角将等于内核矩阵的右上角,等等在。 (x_core 中的特定零和一实现了这一点。)

y = tf.keras.layers.Conv2D(1, 2, strides=(2,2), activation=None, input_shape=x.shape[1:])(x)

但是,y如果我重新运行代码,就会发生变化,即过滤器不是恒定的,这表明内核矩阵是从分布中提取的。


类似问题

类似但不同的问题:How to get CNN kernel values in Tensorflow - 此方法仅适用于 Tensorflow 1。它的问题:

  • gr = tf.get_default_graph()给出AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

  • 如果我替换 get_default_graphGraph (我相信这是较新的等效项),输入 name="conv1"我的图层定义:conv_layer_1 = tf.keras.layers.Conv2D(1, 2, strides=(2,2), activation=None, input_shape=x.shape[1:],name="conv1")然后运行conv1_kernel_val = tf.Graph().get_tensor_by_name('conv1/kernel:0').eval()按照建议,我得到:

KeyError: "The name 'conv1/kernel:0' refers to a Tensor which does not exist. The operation, 'conv1/kernel', does not exist in the graph."

最佳答案

import tensorflow as tf

input_shape = (4, 28, 28, 3)
x = tf.random.normal(input_shape)
model = tf.keras.layers.Conv2D(2, 3, activation='relu', input_shape=input_shape[1:])
y = model(x)
print(model.kernel)

关于python - 如何在 Tensorflow 2 中获取 Conv2D 内核值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70413900/

相关文章:

python - 在 NumPy 中将 2D float 数组转换为 2D int 数组

python - 平方和的微小数值差异取决于所使用的 numpy 过程调用

python - 使用 RNN 和 Layer 类在 Keras 中实现最小的 LSTMCell

python - Tensorboard 找不到 .runfiles 目录错误

tensorflow - 我们在YOLO的输出层使用哪个激活函数?

deep-learning - 在 Keras 中将 VGG 函数模型转换为顺序模型

python - 如何在 openpyxl 中使用字段名或列标题?

python - 从相对路径导入模块

python - 恢复keras seq2seq模型

keras - 如何在 ImageDataGenerator 中将 featurewise_center=True 与 flow_from_directory 一起使用?