尝试可视化Tensorflow中的激活

时间:2020-09-07 06:55:29

标签: tensorflow deep-learning

我创建了一个简单的cnn以检测自定义数字,并且试图可视化我的图层的激活。当我运行以下代码layer_outputs = [layer.output for layer in model.layers[:9]]时,出现错误Layer conv2d has no inbound nodes
当我在线搜索时,它说要定义第一层的输入形状,但是我已经做到了,而且我不确定为什么会这样。下面是我的模型。

class myModel(Model):
def __init__(self):
    super().__init__()
    self.conv1 = Conv2D(filters=32, kernel_size=(3,3), activation='relu', padding='same',
                        input_shape=(image_height, image_width, num_channels))
    self.maxPool1 = MaxPool2D(pool_size=(2,2))
    
    self.conv2 = Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same')
    self.maxPool2 = MaxPool2D(pool_size=(2,2))
    
    self.conv3 = Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same')
    self.maxPool3 = MaxPool2D(pool_size=(2,2))
    
    
    self.flatten = Flatten()
    self.d1 = Dense(128, activation='relu')
    self.d2 = Dense(10, activation='softmax')
    
def call(self, x):
    x = self.conv1(x)
    x = self.maxPool1(x)
    x = self.conv2(x)
    x = self.maxPool2(x)
    x = self.conv3(x)
    x = self.maxPool3(x)
    x = self.flatten(x)
    x = self.d1(x)
    x = self.d2(x)
    return x

1 个答案:

答案 0 :(得分:0)

基于您所陈述的目标和您发布的内容,我认为这里的问题是对TensorFlow API的工作方式稍有(也是可以理解的)误解。模型对象及其组成部分仅存储模型的状态,而不存储模型的评估,例如,您设置的超参数以及模型在馈入训练数据时学习的参数。即使您设法解决所尝试的问题,作为模型一部分的.output图层对象也不会返回您要可视化的激活。相反,它返回TensorFlow图中代表计算部分的部分。

对于您要执行的操作,您需要操作一个对象,该对象是在已设置和训练的模型上调用.predict函数的结果。或者,您可以下降到Keras抽象的下面并直接操纵张量。

如果我考虑得更多,可能有一种相当不错的方法,只需评估您的图形(即调用.predict)一次,但是最明显的天真的方法是实例化几个新模型(或模型的几个子类),并将每个感兴趣的层作为终端输出,这应该可以让您得到想要的东西。

例如,您可以对您感兴趣的每个输出层执行以下操作:

my_test_image = # get an image
input = Input(shape=(None, 256, 256, 3)) # input size will need to be set according to the relevant model
outputs_of_interest = Model(input, my_model.layers[-2].output)
outputs_of_interest.predict(my_test_image) # <=== this has the output you want
相关问题