本文介绍了分割图层输出时,Keras抛出`'Tensor'对象没有属性'_keras_shape'`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个尺寸为2*1*300的句子对的句子嵌入输出X.我想将此输出分为形状为1*300的两个向量,以计算其绝对差和乘积.

I have sentence embedding output X of a sentence pair of dimension 2*1*300. I want to split this output into two vectors of shape 1*300 to calculate its absolute difference and product.

x = MaxPooling2D(pool_size=(1,MAX_SEQUENCE_LENGTH),strides=(1,1))(x)
x_A = Reshape((1,EMBEDDING_DIM))(x[:,0])
x_B = Reshape((1,EMBEDDING_DIM))(x[:,1])

diff = keras.layers.Subtract()([x_A, x_B])
prod = keras.layers.Multiply()([x_A, x_B])


nn = keras.layers.Concatenate()([diff, prod])

当前,当我执行x[:,0]时,会引发错误,提示AttributeError: 'Tensor' object has no attribute '_keras_shape'.我假设张量对象分裂的结果是没有_keras_shape的张量对象.

Currently, when I do x[:,0] it throws an error saying AttributeError: 'Tensor' object has no attribute '_keras_shape'. I assume the result of splitting of tensor object is a tensor object that doesn't have _keras_shape.

有人可以帮我解决这个问题吗?谢谢.

Can someone help me solve this? Thanks.

推荐答案

Keras在层中处理张量时会向张量添加一些信息.由于您是在外部扩展张量,因此它将丢失该信息.

Keras adds some info to tensors when they're processed in layers. Since you're splitting the tensor outside layers, it loses that info.

该解决方案涉及从Lambda层返回分割张量:

The solution involves returning the split tensors from Lambda layers:

x_A = Lambda(lambda x: x[:,0], output_shape=notNecessaryWithTensorflow)(x)
x_B = Lambda(lambda x: x[:,1], output_shape=notNecessaryWithTensorflow)(x)
x_A = Reshape((1,EMBEDDING_DIM))(x_A)
x_B = Reshape((1,EMBEDDING_DIM))(x_B)

这篇关于分割图层输出时,Keras抛出`'Tensor'对象没有属性'_keras_shape'`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:13