Python Keras Lambda layers提供ValueError:输入0与层xxx不兼容:预期最小ndim=3,发现ndim=2
当我将lambda层添加到顺序模型时,它给出ValueError:输入0与…不兼容 对于此模型,我得到Python Keras Lambda layers提供ValueError:输入0与层xxx不兼容:预期最小ndim=3,发现ndim=2,python,keras,deep-learning,Python,Keras,Deep Learning,当我将lambda层添加到顺序模型时,它给出ValueError:输入0与…不兼容 对于此模型,我得到ValueError:输入0与层展平不兼容\u 1:预期最小值ndim=3,发现ndim=2 model1 = Sequential() model1.add(Embedding(max_words, embedding_dim, input_length=maxlen)) model1.add(Lambda(lambda x: mean(x, axis=1))) model1.add(Flat
ValueError:输入0与层展平不兼容\u 1:预期最小值ndim=3,发现ndim=2
model1 = Sequential()
model1.add(Embedding(max_words, embedding_dim, input_length=maxlen))
model1.add(Lambda(lambda x: mean(x, axis=1)))
model1.add(Flatten())
model1.add(Bidirectional(LSTM(32)))
model1.add(Dropout(0.6))
model1.add(Dense(2))
如果我删除flant()
我得到:值错误:输入0与层1不兼容:预期ndim=3,发现ndim=2
。但是,如果没有lambda层,模型可以正常工作
任何关于导致此问题的原因以及我如何解决此问题的想法都将不胜感激。谢谢下面生成的图形似乎正确:
from tensorflow.python import keras
from keras.models import Sequential
from keras.layers import *
import numpy as np
max_words = 1000
embedding_dim = 300
maxlen = 10
def mean(x, axis):
"""mean
input_shape=(batch_size, time_slots, ndims)
depending on the axis mean will:
0: compute mean value for a batch and reduce batch size to 1
1: compute mean value across time slots and reduce time_slots to 1
2: compute mean value across ndims an reduce dims to 1.
"""
return K.mean(x, axis=axis, keepdims=True)
model1 = Sequential()
model1.add(Embedding(max_words, embedding_dim, input_length=maxlen))
model1.add(Lambda(lambda x: mean(x, axis=1)))
model1.add(Bidirectional(LSTM(32)))
model1.add(Dropout(0.6))
model1.add(Dense(2))
model1.compile('sgd', 'mse')
model1.summary()
嵌入层使用3个维度(批量大小、最大值、嵌入大小)。
LSTM层也需要3维。因此,lambda应该返回一个兼容的形状,或者需要重塑形状。这里K.mean提供了一个方便的参数(keepdims),可以帮助我们实现这一点。您的
Lambda
层的输出已经被展平,因此这里不需要展平。@Alexi试图用model1重塑模型。添加(重塑((100200)))但get-ValueError:新数组的总大小必须保持不变。请解释为什么这样做?您有一个只返回x的伪函数。当然,这不是平均数应该做的,但为什么这样做呢?编辑了答案,添加了跨时段的平均数。