首页 > 其他分享 >keras SegNet使用池化索引(pooling indices)

keras SegNet使用池化索引(pooling indices)

时间:2022-10-27 13:00:25浏览次数:60  
标签:keras self mask shape pooling SegNet input output size


keras中不能直接使用池化索引。最近学习到SegNet(网上许多错的,没有用池化索引),其中下采样上采样用到此部分。此处用到自定义层。

keras SegNet使用池化索引(pooling indices)_池化


完整测试代码如下。

"""
@author: LiShiHang
@software: PyCharm
@file: utils.py
@time: 2018/12/18 14:58
"""
from keras.engine import Layer
import keras.backend as K


class MaxPoolingWithArgmax2D(Layer):

def __init__(
self,
pool_size=(2, 2),
strides=(2, 2),
padding='same',
**kwargs):
super(MaxPoolingWithArgmax2D, self).__init__(**kwargs)
self.padding = padding
self.pool_size = pool_size
self.strides = strides

def call(self, inputs, **kwargs):
padding = self.padding
pool_size = self.pool_size
strides = self.strides
if K.backend() == 'tensorflow':
ksize = [1, pool_size[0], pool_size[1], 1]
padding = padding.upper()
strides = [1, strides[0], strides[1], 1]
output, argmax = K.tf.nn.max_pool_with_argmax(
inputs,
ksize=ksize,
strides=strides,
padding=padding)
else:
errmsg = '{} backend is not supported for layer {}'.format(
K.backend(), type(self).__name__)
raise NotImplementedError(errmsg)
argmax = K.cast(argmax, K.floatx())
return [output, argmax]

def compute_output_shape(self, input_shape):
ratio = (1, 2, 2, 1)
output_shape = [
dim // ratio[idx]
if dim is not None else None
for idx, dim in enumerate(input_shape)]
output_shape = tuple(output_shape)
return [output_shape, output_shape]

def compute_mask(self, inputs, mask=None):
return 2 * [None]


class MaxUnpooling2D(Layer):
def __init__(self, up_size=(2, 2), **kwargs):
super(MaxUnpooling2D, self).__init__(**kwargs)
self.up_size = up_size

def call(self, inputs, output_shape=None):

updates, mask = inputs[0], inputs[1]
with K.tf.variable_scope(self.name):
mask = K.cast(mask, 'int32')
input_shape = K.tf.shape(updates, out_type='int32')
# calculation new shape
if output_shape is None:
output_shape = (
input_shape[0],
input_shape[1] * self.up_size[0],
input_shape[2] * self.up_size[1],
input_shape[3])

# calculation indices for batch, height, width and feature maps
one_like_mask = K.ones_like(mask, dtype='int32')
batch_shape = K.concatenate(
[[input_shape[0]], [1], [1], [1]],
axis=0)
batch_range = K.reshape(
K.tf.range(output_shape[0], dtype='int32'),
shape=batch_shape)
b = one_like_mask * batch_range
y = mask // (output_shape[2] * output_shape[3])
x = (mask // output_shape[3]) % output_shape[2]
feature_range = K.tf.range(output_shape[3], dtype='int32')
f = one_like_mask * feature_range

# transpose indices & reshape update values to one dimension
updates_size = K.tf.size(updates)
indices = K.transpose(K.reshape(
K.stack([b, y, x, f]),
[4, updates_size]))
values = K.reshape(updates, [updates_size])
ret = K.tf.scatter_nd(indices, values, output_shape)
return ret

def compute_output_shape(self, input_shape):
mask_shape = input_shape[1]
return (
mask_shape[0],
mask_shape[1] * self.up_size[0],
mask_shape[2] * self.up_size[1],
mask_shape[3]
)


if __name__ == '__main__':

import keras
import numpy as np

# input = keras.layers.Input((4, 4, 3))
# o = MaxPoolingWithArgmax2D()(input)
# model = keras.Model(inputs=input, outputs=o) # outputs=o
# model.compile(optimizer="adam", loss='categorical_crossentropy')
# x = np.random.randint(0, 100, (3, 4, 4, 3)) # 调试此处
# m = model.predict(x) # 调试此处
# print(m)

input = keras.layers.Input((4, 4, 3))
o = MaxPoolingWithArgmax2D()(input)
o2 = MaxUnpooling2D()(o)
model = keras.Model(inputs=input, outputs=o2) # outputs=o
model.compile(optimizer="adam", loss='categorical_crossentropy')
x = np.random.randint(0, 100, (3, 4, 4, 3)) # 调试此处
m = model.predict(x) # 调试此处
print(m)

感兴趣的可调试注释处。

keras SegNet使用池化索引(pooling indices)_池化_02


标签:keras,self,mask,shape,pooling,SegNet,input,output,size
From: https://blog.51cto.com/u_15847885/5800839

相关文章

  • keras FCN实现(2)
    FCN-8/FCN-16Add了底层特征。FCN-8的实现,承接​​上篇​​。代码位置:​​​https://github.com/lsh1994/keras-segmentation​​结构:训练曲线:可视化结果:......
  • anaconda 下安装tensorflow & keras
    首先,同胞们要记住,你要做什么?该怎么做?你的目标是什么?千万不要因为中间遇到的连带问题,而忘记了你要做什么?一下开始介绍:????下载:官网速度很慢,容易断线:https://www.......
  • Keras搭建CNN进行人脸识别系列(四)--为模型训练准备人脸数据
          机器学习最本质的地方就是基于海量数据统计的学习,说白了,机器学习其实就是在模拟人类儿童的学习行为。举一个简单的例子,成年人并没有主动教孩子学习语言,但随着......
  • Keras搭建CNN进行人脸识别系列(三)--利用haar级联检测器识别出人脸
    人脸识别原理        从实时视频流中识别出人脸区域,从原理上看,其依然属于机器学习的领域之一,本质上与谷歌利用深度学习识别出猫没有什么区别。程序通过大量的......
  • keras分类猫狗数据(中)使用CNN分类模型
    ​​keras分类猫狗数据(上)数据预处理​​​​​​keras分类猫狗数据(中)使用CNN分类模型​​​​​​keras分类猫狗数据(下)迁移学习​​​​​​keras分类猫狗数据(番外篇)深度......
  • keras分类猫狗数据(下)finetune
    ​​keras分类猫狗数据(上)数据预处理​​​​​​keras分类猫狗数据(中)使用CNN分类模型​​​​​​keras分类猫狗数据(下)迁移学习​​​​​​keras分类猫狗数据(番外篇)深度......
  • keras中的History对象
    keras中的​​fit_generator​​​和​​fit​​函数均返回History对象,那么History怎么用呢?事实上History对象已经记录了运行输出。在了解之前,我们甚至自己定义回调函数记录......
  • keras使用预训练模型inception_v3识别图片
    本文使用keras中inception_v3预训练模型识别图片。结合官方源码,如下内容。其中,数据输入借助opencv-python,程序运行至​​model=InceptionV3()​​​时按需(如果不存在就)下载......
  • 使用Keras生成可变尺寸输入数据的神经网络
    本教程发布于博客园,转载请注明出处!问题:在使用神经网络处理实际数据时,往往遇到数据尺寸不相同的情况。例如:训练得到一个图片去雾模型后,需要对不同尺寸的照片去雾。解决方......
  • Keras--卷积层
    关于卷积层,包括:Conv1D,Conv2D,SeparableConv2D,Conv2DTranspose,Conv3D,Cropping1D,Cropping2D,Cropping3D,UpSampling1D,UpSampling2D,UpSampleing3D,ZeroPaddi......