显示的错误是 无法转换类型类为'tensorflow.python.keras.layers.pooling.MaxPooling2D'的对象 到张量。 我已经尝试了很多事情,但是无法对这个错误进行排序。
```class Mixed_pooling():
def __init__(self, **kwargs):
super(Mixed_pooling, self).__init__(**kwargs)
def build(self, input_shape):
self.alpha = self.add_weight(
name='alpha', shape=(1,),
initializer='random_normal',
trainable=True
)
super(Mixed_pooling, self).build(input_shape)
def call(self, x):
x1 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
x2 = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
outputs = tf.add(tf.multiply(x1, self.alpha), tf.multiply(x2, (1-self.alpha)))
return outputs```
即使在注释部分(感谢Slowpoke)中存在此解决方案(答案部分),在此处提供该解决方案,都是为了社区的利益。
由于tf.keras.layers.MaxPooling2D()
和tf.keras.layers.AveragePooling2D()
是类对象,因此需要在build
函数中实例化这些对象,然后在call
函数中使用它们。
修改的代码-
import tensorflow as tf
class Mixed_pooling():
def __init__(self, **kwargs):
super(Mixed_pooling, self).__init__(**kwargs)
def build(self, input_shape):
self.alpha = self.add_weight(
name='alpha', shape=(1,),
initializer='random_normal',
trainable=True
)
self.maxpool=tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
self.avgpool = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), strides=(2,2), padding='VALID')
super(Mixed_pooling, self).build(input_shape)
def call(self, x):
x1 = self.maxpool(x)
x2 = self.avgpool(x)
outputs = tf.add(tf.multiply(x1, self.alpha), tf.multiply(x2, (1-self.alpha)))
return outputs
layer1 = Mixed_pooling()
print(layer1)
输出-
<__main__.Mixed_pooling object at 0x7fce31e46550>
希望这能回答您的问题。祝您学习愉快。