【发布时间】:2019-12-16 13:48:11
【问题描述】:
我想找到同一 CNN 层的特征图之间的内积(矩阵积)。我创建了一个自定义层来执行此操作并尝试在层之间应用“matmul”操作,但最终出现错误。请协助我应该做什么。
ValueError: 'dim' 输入必须是具有单个值的张量 'inner_product2__test_16/ExpandDims' (op: 'ExpandDims') 输入形状:[2,?,200,240,128], [2] 和计算输入张量: 输入[1] = .
我的自定义图层代码是:
# Custom Inner Product Layer of 4D tensor
class InnerProduct2_Test(Layer):
def __init__(self, **kwargs):
self.input_spec = [InputSpec(ndim='4+')]
self.out_dim = None
super(InnerProduct2_Test, self).__init__(**kwargs)
def build(self, input_shape):
""" Build the model based on input shape: """
assert len(input_shape) == 2
assert input_shape[0] == input_shape[1]
self.out_dim = input_shape[1]
self.built == True
def compute_output_shape(self, input_shape):
if not all(input_shape[1:]):
raise Exception('Number of inputs is supposed to be two bu found another value')
assert input_shape[0] == input_shape[1]
return input_shape
def get_config(self):
'''No any configuration file for now'''
def call(self, x, mask=None):
"""
4D tensor with same shape as input
"""
if K.backend() == 'theano':
raise ValueError("InnerProduct not supported for Theano")
else:
if self.built:
import tensorflow as tf
inner = tf.expand_dims(x,(-2,-1))
Product = tf.matmul(inner, inner)
return Product
else:
raise RuntimeError("Something is wrong")'''
在CNN上应用内积:
from keras.layers import Conv2D, MaxPooling2D, Dense, Lambda,Flatten,Softmax,dot,
Activation,Cropping2D
import keras.backend as K
from keras.models import Model,Input
import tensorflow as tf
import numpy as np
from keras.engine import Layer, InputSpec
InputsL=Input(shape=(200,240,3))
x=Conv2D(128,(3,3),activation='relu',padding='same')(InputsL)
x=InnerProduct2_Test()([x,x])
x=Conv2D(64,(3,3),activation='relu',padding='same')(x)
x=MaxPooling2D(2,2)(x)
x=InnerProduct2_Test()([x,x])
x=Activation('softmax')(x)
x=Cropping2D((2,2))(x)
x=InnerProduct2_Test()([x,x])
x=Flatten()(x)
Model2=Model(inputs=inputsL,outputs=x)
`'''
【问题讨论】:
标签: python tensorflow matrix keras multiplication