【问题标题】:Inner Product (Matrix multiplication) in convolution Layers卷积层中的内积(矩阵乘法)
【发布时间】: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


    【解决方案1】:

    张量乘法只是矩阵乘法的推广,矩阵乘法只是向量乘法的推广。

    矩阵乘法定义为:

    ??⋅??=??,? 其中?是??ℎ行,?是??ℎ列,⋅是点积。因此它只是一系列的点积。

    然后可以看到这如何扩展到张量: ??⋅??=??,? 其中 ? 是张量的 ??ℎ 行矩阵,? 是张量的 ??ℎ 列矩阵......因此只是一系列矩阵乘法 - 或一系列点积。

    假设所有张量都是三阶的(可以用三个坐标来描述):

    ?⊗?=??,?⋅??,?=??,?,? 这意味着 ? 的 (?,?)?ℎ 向量乘以? 的 (?,?)?ℎ 向量。 至于您,您的错误显示了一些程序错误,而不是逻辑上的错误..您最好实施 内部 = tf.expand_dims(x,(-2,-1)) 此函数用法来自 python 和 tensor core 提供的文档 在这里 https://www.tensorflow.org/api_docs/python/tf/expand_dims

    【讨论】:

    • 谢谢@Uroosa,你能把可以正常解决我的问题的示例代码发给我吗???
    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多