python - 卷积层中的内积(矩阵乘法)
问题描述
我想在同一 CNN 层的特征图之间找到内积(矩阵积)。我创建了一个自定义层来执行此操作并尝试在层之间应用“matmul”操作,但最终出现错误。请协助我应该做什么。
ValueError: 'dim' 输入必须是具有单个值的张量 'inner_product2__test_16/ExpandDims' (op: 'ExpandDims') 输入形状:[2,?,200,240,128], [2] 和计算输入张量:input[ 1] = <-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和张量核心 https:/ /www.tensorflow.org/api_docs/python/tf/expand_dims
推荐阅读
- excel - Excel中的虚拟数组中的分类列
- kibana - 为什么我会从 NLog FileTarget 在 Kibana 中获得部分日志消息?
- html - CSS Grid Item 溢出子和父网格容器(高度)
- javascript - 多表单数据的单表单提交
- html - CSS :last-child 选择器被最后一个孩子忽略
- android - 以编程方式断开任何 VPN 服务
- python - 如何将输入读入不同行中给出的确切长度列表
- r - 在 model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) 中不断出现错误:因子 subj 有新的水平
- variables - 如何在汇编中将 Int 转换为 String
- mysql - Mysql删除带下划线的变量