您的位置:首页 > 其它

keras slice layer 层实现方式

2020-06-20 11:47 966 查看

注意的地方: keras中每层的输入输出的tensor是张量, 比如Tensor shape是(N, H, W, C), 对于tf后台, channels_last

Define a slice layer using Lamda layer
def slice(x, h1, h2, w1, w2):
""" Define a tensor slice function
"""
return x[:, h1:h2, w1:w2, :]

定义完slice function之后,利用lambda layer添加到定义的网络中去

# Add slice layer
slice_1 = Lambda(slice, arguments={'h1': 0, 'h2': 6, 'w1': 0, 'w2': 6})(sliced)
# As for tensorfow backend, Lambda doesn't need output shape argument
slice_2 = Lambda(slice, arguments={'h1': 0, 'h2': 6, 'w1': 6, 'w2': 12})(sliced)

补充知识:tensorflow和keras张量切片(slice)

Notes

想将一个向量 分割成两部分: 操作大概是:

在 TensorFlow 中,用 tf.slice 实现张量切片,Keras 中自定义 Lambda 层实现。

TensorFlow

tf.slice(input_, begin, size, name=None)

input_:tf.tensor,被操作的 tensor

begin:list,各个维度的开始下标

size:list,各个维度上要截多长

import tensorflow as tf

with tf.Session() as sess:
a = tf.constant([1, 2, 3, 4, 5])
b = tf.slice(a, [0], [2]) # 第一个维度从 0 开始,截 2 个
c = tf.slice(a, [2], [3]) # 第一个维度从 2 开始,截 3 个
print(a.eval())
print(b.eval())
print(c.eval())

输出

[1 2 3 4 5]
[1 2]
[3 4 5]

Keras

from keras.layers import Lambda
from keras.models import Sequential
import numpy as np

a = np.array([[1, 2, 3, 4, 5]])
model = Sequential([
Lambda(lambda a: a[:, :2], input_shape=[5]) # 第二维截前 2 个
])

print(model.predict(a))

输出

[[1. 2.]]

以上这篇keras slice layer 层实现方式就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  keras slice layer层