在TensorFlow中为Keras模型获取中间激活层

时间:2018-04-24 02:52:08

标签: tensorflow keras convolutional-neural-network

我有一个卷积Keras模型,我正在尝试获得一个TensorFlow图,它会给我中间激活层,但是我没有通过以下方式获得正确的结果:

import skimage.transform as transform
import imageio
import numpy as np

import tensorflow as tf
from keras.applications import VGG16
from keras import models

conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(540, 960, 3))
layer_dict = {layer.name:layer for layer in conv_base.layers}

image = imageio.imread('/home/john/001000.png')
image = transform.resize(image, (540, 960), mode='constant')
image = np.expand_dims(image, axis=0)

#In Keras, I would just do this:
#model = models.Model(inputs=conv_base.input, outputs=layer_dict[layerName])
#prediction = model.predict(image)
#print(np.sum(prediction))

sess = tf.Session()
sess.run(tf.global_variables_initializer())

ans = sess.run(layer_dict['block5_conv2'].output, feed_dict={(conv_base.input): image})
print(np.sum(ans))

我将结果的总和作为一个快速比较。我认为在TensorFlow中初始化变量时,它会重置所有权重,因为我每次都得到一个随机结果。但是,它也不会让我在没有初始化的情况下运行。我这样做是因为我希望能够在Go中执行此操作,因此我首先尝试使用Keras在Python中执行此操作,然后使用TensorFlow直接执行Python,然后使用TensorFlow执行Go。我想如果我能在TensorFlow中使用它,我可以将它保存到Python中的文件中,然后将其加载到Go中。

0 个答案:

没有答案