【问题标题】:How to add computation (eg log and sqrt root) to keras vgg16 before softmax layer如何在softmax层之前向keras vgg16添加计算(例如log和sqrt root)
【发布时间】:2019-04-23 19:58:24
【问题描述】:

我正在实现改进的双线性池 (http://vis-www.cs.umass.edu/bcnn/docs/improved_bcnn.pdf),我想在我的模型中添加 softmax 层之前的计算(例如对数和平方根),这是从 keras vgg16 微调的。 我该怎么做?

vgg_16 = keras.applications.vgg16.VGG16(weights='imagenet',include_top=False, input_shape=(224, 224, 3))
vgg_16.layers.pop()

My_Model = Sequential()
for layer in vgg_16.layers:
    My_Model.add(layer)

for layer in My_Model.layers:
    layer.trainable = False
    
# I want to add this function on top of my model then feed the result to a softmax layer
# 

def BILINEAR_POOLING(bottom1, bottom2, sum_pool=True):
    assert(np.all(bottom1.shape[:3] == bottom2.shape[:3]))
    batch_size, height, width = bottom1.shape[:3]
    output_dim = bottom1.shape[-1] * bottom2.shape[-1]

    bottom1_flat = bottom1.reshape((-1, bottom1.shape[-1]))
    bottom2_flat = bottom2.reshape((-1, bottom2.shape[-1]))

    output = np.empty((batch_size*height*width, output_dim), np.float32)
    for n in range(len(output)):
        output[n, ...] = np.outer(bottom1_flat[n], bottom2_flat[n]).reshape(-1)
    output = output.reshape((batch_size, height, width, output_dim))

    if sum_pool:
        output = np.sum(output, axis=(1, 2))
    return output

【问题讨论】:

  • 我只使用带有 conv 层的 vgg16(包括 top = false)。我编写了一个代码将最终张量展平为 2D tansor,然后在其上应用 log 和 sqrt。但是如何将这些功能添加到我的模型中呢?可以使用 keras lambda 吗?

标签: python-3.x tensorflow keras jupyter-notebook


【解决方案1】:

解决方案只是添加一个 keras lambda 层 如下

My_Model.add(Lambda(BILINEAR_POOLING,output_shape=[512,512]))

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2020-10-28
    • 2017-07-31
    • 2021-03-27
    相关资源
    最近更新 更多