tensorflow和keras张量切片(slice)

Notes

想将一个向量 x = ( x 1 , x 2 , x 3 , x 4 , x 5 ) T x=\left(x_1,x_2,x_3,x_4,x_5\right)^T x=(x1,x2,x3,x4,x5)T 分割成两部分: a = ( x 1 , x 2 ) T a=\left(x_1,x_2\right)^T a=(x1,x2)T b = ( x 3 , x 4 , x 5 ) T b=\left(x_3,x_4,x_5\right)^T b=(x3,x4,x5)T,操作大概是:
a = [ 1 0 0 0 0 0 0 1 0 0 0 0 ] x a=\left[\begin{matrix} 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 0 \end{matrix}\right]x a=[100100000000]x

b = [ 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 ] x b=\left[\begin{matrix} 0 & 0 & 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 0 & 0 & 1 \end{matrix}\right]x b=000000000100010001x
在 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.]]

References

  1. TensorFlow分割:tf.slice函数
  2. Are there slice layer and split layer in Keras? #890

你可能感兴趣的:(机器学习,python,tensorflow,keras,张量切片)