0

我正在使用CNN开发分类模型,现在我想在我的问题中应用分类算法(Bilinear CNN Models for Fine-grained Visual Recognition Tsung-Yu Lin Aruni RoyChowdhury Subhransu Maji University of Massachusetts, Amherst)。矩阵产品到keras中的两个模型的输出

具体来说,现在我想做两个CNN模型的输出矩阵的外积,并且我已经完成了矩阵的转置,现在我只想把两个矩阵相乘keras,其大小是,512,49)和(无,49,512)。

我尝试使用合并层keras,但有些错误出现了:

当我使用模式,

ValueError: Dimension incompatibility using dot mode: 49 != 512. Layer shapes: (None, 512, 49), (None, 49, 512)

当我使用模式,

ValueError: Only layers of same output shape can be merged using mul mode. Layer shapes: [(None, 512, 49), (None, 49, 512)]

我不知道如何解决它,请帮助 我!这里是我的问题的一些代码:

所有的
t_model = applications.VGG16(weights='imagenet', include_top=False, 
           input_shape=(224, 224, 3)) 
model_a = Sequential() 
model_a.add(t_model) 
def trans_1(conv): 
    conv = tf.reshape(conv, [-1, 49, 512]) 
    return conv 
model_a.add(Lambda(trans_1, output_shape=[49, 512])) 

s_model = applications.VGG16(weights='imagenet', include_top=False, 
           input_shape=(224, 224, 3)) 
model_b = Sequential() 
model_b.add(s_model) 
def trans_2(conv): 
    conv = tf.reshape(conv, [-1, 49, 512]) 
    conv = tf.transpose(conv, perm = [0, 2, 1]) 
    return conv 
model_b.add(Lambda(trans_2, output_shape=[512, 49])) 

f_model = Sequential() 
f_model.add(Merge([model_b, model_a], mode='dot')) 

回答

1

首先,不使用Sequential()当你的模式是不连续的。改为使用functional API

此外,

  • 由于两个VGG16车型共享相同的输入图像,你可以使用input_tensor参数提供共享输入。
  • 请注意,VGG16具有固定的图层名称。您必须更改其中一个模型的图层名称,以防止“所有图层名称应该是唯一的”。错误。
  • Keras有一个内置的Reshape图层,这里不需要使用TF。
  • 使用Dot而不是已弃用的Merge图层。

回到您的问题,Dot中的参数axes指定哪些轴将被缩小。所以你在应用之前不需要调整张量。

input_tensor = Input(shape=(224, 224, 3)) 
t_model = applications.VGG16(weights='imagenet', include_top=False, input_tensor=input_tensor) 
t_output = Reshape((49, 512))(t_model.output) 
s_model = applications.VGG16(weights='imagenet', include_top=False, input_tensor=input_tensor) 
for layer in s_model.layers: 
    layer.name += '_1' 
s_output = Reshape((49, 512))(s_model.output) 
merged = Dot(axes=1)([s_output, t_output]) 
+0

真的很有帮助,非常感谢你! –