python - Keras - 嵌入层和 GRU 层形状错误
问题描述
# input_shape = (137861, 21, 1)
# output_sequence_length = 21
# english_vocab_size = 199
# french_vocab_size = 344
def embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
'''
Build and train a RNN model using word embedding on x and y
:param input_shape: Tuple of input shape
:param output_sequence_length: Length of output sequence
:param english_vocab_size: Number of unique English words in the dataset
:param french_vocab_size: Number of unique French words in the dataset
:return: Keras model built, but not trained
'''
learning_rate = 1e-3
model = Sequential()
model.add(Embedding(english_vocab_size, 128, input_length=output_sequence_length, input_shape=input_shape[1:]))
model.add(GRU(units=128, return_sequences=True))
model.add(TimeDistributed(Dense(french_vocab_size)))
model.add(Activation('softmax'))
model.summary()
model.compile(loss=sparse_categorical_crossentropy,
optimizer=Adam(learning_rate),
metrics=['accuracy'])
return model
调用此方法训练模型时,会出现以下错误:
ValueError: Input 0 is incompatible with layer gru_1: expected ndim=3, found ndim=4
如何修复 Embedding Layer 和 GRU Layer 之间的形状错误?
解决方案
问题是嵌入层将二维数组作为输入。但是,输入数组的形状(137861, 21, 1)
使其成为 3D 数组。只需使用squeeze()
numpy 中的方法删除最后一个轴:
data = np.squeeze(data, axis=-1)
作为一个方面,这里没有必要使用TimeDistributed
layer,因为Dense 层是由 defualt 应用在最后一个轴上的。
推荐阅读
- r - 为什么我在 R 中运行 Leiden 算法时得到“假社区”?
- python - PyQt5 .ui 文件未加载
- powerbi - 在 Power BI 中使用 DAX 计算运行平均值
- performance - 树排序性能
- c++ - DirectX12 计算着色器什么都不做?
- reactjs - 如何在本机反应中使用带有多日期选择器的handleChange?
- node.js - macOS 升级后找不到 node/npm/nvm 错误
- html - 在 bootstrap4 中创建带有拆分按钮的下拉菜单
- highcharts - 是否可以创建具有条件着色并显示在图例中的图表?
- sql - ORA-00913“值太多”Oracle SQL