python3 keras获取GRU的每一个时刻的输出,,切分GRU的输出示例

1. keras的GRU很好用,return_sequences,False 返回单个, true 返回全部time step 的 hidden state值。

2. 但是keras的time step是根据输入决定的,这里我们在处理的时候,可能就需要分割以下某一层的数据,然后输入到后面的不同的层中,但是我们在对tensor操作的时候,会产生很多莫名其妙的错误,这里我写一个跟别人写的示例代码,分享给大家:


from keras.models import Model
from keras.layers import Input, Dropout, TimeDistributed, Masking, Dense, Lambda
from keras.layers import BatchNormalization, Embedding, Activation, Reshape,Permute,Bidirectional
from keras.layers.merge import Add,Dot
from keras.layers.recurrent import LSTM, GRU
from keras import backend as K
import tensorflow as tf



image_input = Input(shape=(20, 2048), name='image')
recurrent_network = GRU(units=10,return_sequences=True,
                                    name='recurrent_network')(image_input)

new_inpu=recurrent_network
splits = Lambda(lambda x: tf.split(x, num_or_size_splits=20, axis=1))(new_inpu)
print(splits[0])

list_recur=[]
for i in range(20):
    
    # x = new_inpu[:, i, :]   # AttributeError: 'NoneType' object has no attribute '_inbound_nodes'
    # print(x.shape)
    # x= K.reshape(x,(1,10,)) 
    # x= K.expand_dims(x,axis=-1) 
    # x=Lambda(lambda x: K.expand_dims(x, axis=-1))(x)
    x=Reshape((1,10))(splits[i])
    print(x)
    # x=Permute((2, 1))(x)
    # print(x)
    recurrent_network = GRU(units=10,return_sequences=True,
                                    name='recurrent_network{}'.format(i))(x)
    # print(recurrent_network)
    list_recur.append(recurrent_network)

decoder_outputs = Lambda(lambda x: K.concatenate(x, axis=1))(list_recur)

# recurrent_network = GRU(units=10,return_sequences=True,
#                                     name='recurrent_network')(image_input)
# print(decoder_outputs)
# output = TimeDistributed(Dense(units=20,
#                                     activation='softmax'),
#                                     name='output')(decoder_outputs)


model = Model(inputs=image_input, outputs=decoder_outputs)

print(model.summary()

参考文献

[1].Keras Multi-inputs AttributeError: 'NoneType' object has no attribute 'inbound_nodes'.https://stackoverflow.com/questions/44627977/keras-multi-inputs-attributeerror-nonetype-object-has-no-attribute-inbound-n%EF%BC%89%EF%BC%8C

[2].理解LSTM在keras API中参数return_sequences和return_state. https://blog.csdn.net/u011327333/article/details/78501054

[3].tf.split.https://www.tensorflow.org/api_docs/python/tf/split

[4].Are there slice layer and split layer in Keras?.https://github.com/keras-team/keras/issues/890

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值