python - 如何获取上一层的形状并将其传递给下一层?

标签 python keras deep-learning

我想采用(无,)形状传递到输入层的输入数据的形状,并出于某种目的在 for 循环中使用它。

这是我的代码实现的一部分:

lst_rfrm = []
Inpt_lyr = keras.Input(shape = (None,))
for k in range(tm_stp):
  F = keras.layers.Lambda(lambda x, i, j: x[:, None, j : j + i])
  F.arguments = {'i' : sub_len, 'j' : k}
  tmp_rfrm = F(Inpt_lyr)
  lst_rfrm.append(tmp_rfrm)
cnctnt_lyr = keras.layers.merge.Concatenate(axis = 1)(lst_rfrm)
#defining other layers ...

因为输入形状是(无,),我不知道给 for 循环什么作为范围(在代码中我用'tm_stp'描述它)。在这种情况下我怎样才能得到输入层的形状(传递给输入层的数据)? 非常感谢任何帮助

最佳答案

您可以尝试不同类型的循环。看来您正在尝试滑动窗口,对吗? 您不知道要运行的“长度”,但您知道窗口大小和要删除多少边框……所以……

Slicing differently

此函数按照该原则获取切片:

windowSize = sub_len
def getWindows(x):
    borderCut = windowSize - 1 #lost length in the length dimension

    leftCut = range(windowSize) #start of sequence
    rightCut = [i - borderCut for i in leftCut] #end of sequence - negative
    rightCut[-1] = None #because it can't be zero for slicing

    croppedSequences = K.stack([x[:, l: r] for l,r in zip(leftCut, rightCut)], axis=-1)
    return croppedSequences

运行测试:

from keras.layers import *
from keras.models import Model
import keras.backend as K
import numpy as np

windowSize = 3
batchSize = 5

randomLength = np.random.randint(5,10)
inputData = np.arange(randomLength * batchSize).reshape((batchSize, randomLength))

def getWindows(x):
    borderCut = windowSize - 1

    leftCut = range(windowSize)
    rightCut = [i - borderCut for i in leftCut]
    rightCut[-1] = None

    croppedSequences = K.stack([x[:, l: r] for l,r in zip(leftCut, rightCut)], axis=-1)
    return croppedSequences

inputs = Input((None,))
outputs = Lambda(getWindows)(inputs)
model = Model(inputs, outputs)

preds = model.predict(inputData)

for i, (inData, pred) in enumerate(zip(inputData, preds)):
    print('sample: ', i)
    print('input sequence: ', inData)
    print('output sequence: \n', pred, '\n\n')

关于python - 如何获取上一层的形状并将其传递给下一层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014671/

相关文章:

python - celery 检查不稳定的行为

python - 选择列表的各种 "Pieces"

python - 在 ubuntu 上从 python 启动 selenium

python - 导入 keras 和 tensorflow 时出错

python - 了解Keras的ImageDataGenerator类中的 `width_shift_range`和 `height_shift_range`参数

python - 在 python 包装器 caffe 上训练网络?

python - Keras:如何减去两个不同模型的输出并输入到另一个模型?

python - 使用 python 将 BigQuery 表数据导出到具有 where 子句的 Google Cloud Storage

python - Keras LSTM 中的初始状态

python - MXNet 打印中间符号值