gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:30:42 27 4
gpt4 key购买 nike

我想采用(无,)形状传递到输入层的输入数据的形状,并出于某种目的在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com