[我正在尝试在Python中使用嵌入层和keras
中的小批量训练在文本上使用嵌入层和mini-batch训练来训练LSTM主题模型(多对一问题)。我正在努力以与嵌入层格式兼容的方式来格式化输入和输出。
我的输入包含成批tensorflow
文本令牌,后填充到50个单元格中。我的输出是对应4种类别之一的iteger标签的向量,同样后填充到50个单元中。
这是示例输入向量:
count-vectorized
这是相应的输出向量:
array([2777, 2879, 114, 207, 2879, 3031, 1831, 565, 1961, 161, 1503,
1485, 1036, 3380, 3255, 2879, 3243, 2152, 2406, 653, 3122, 3053,
623, 1145, 2152, 3255, 2529, 3210, 119, 944, 161, 2879, 1282,
2846, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0], dtype=int32)
作为一个整体,我的输入和输出均包含一个填充数组列表。接下来,我按如下方式初始化我的模型架构:
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0], dtype=int32)
我的from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
model = Sequential()
model.add(Embedding(20000, 100, input_length=50))
model.add(LSTM(100))
model.add(Dense(4, activation='sigmoid'))
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam', metrics=['accuracy'])
具有三个参数:(1)输入维度为20000,对应于我的词汇量;(2)输出维度为100,这是密集嵌入的任意维度;(3)输入长度为50,这是我的后填充向量的最大长度。
embedding layer
[为简化批处理问题,我在print(model.summary())
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_1 (Embedding) (None, 50, 100) 2000000
_________________________________________________________________
lstm_1 (LSTM) (None, 100) 80400
_________________________________________________________________
dense_1 (Dense) (None, 4) 101
=================================================================
Total params: 2,080,501
Trainable params: 2,080,501
Non-trainable params: 0
循环中训练我的模型,一次传递一批。因此,现在可以正确地将我的输入指定为嵌入层所需的2D模式(按照我先前尝试将其重塑为3D后出现的错误,指出for
。)>
expected embedding_1_input to have 2 dimensions
[当我尝试拟合模型时,出现此错误:
for X, y in data: model.fit(X, y, epochs=1, batch_size=1, verbose=0)
这确实令人困惑,因为当我仔细检查输入的尺寸时,它们的确是(50,)!
ValueError: Error when checking input: expected embedding_1_input to have shape (50,) but got array with shape (1,)
转置一维向量没有任何区别,因此我不确定如何进行此操作。有什么建议吗?
[我也注意到np.shape(data[0][0])
> (50,)
帖子有一个类似的问题,但是到目前为止,没有人试图回答它。预先感谢!
我正在尝试使用嵌入层和在keras中使用mini-batch训练在Python上使用tensorflow后端在文本上训练LSTM主题模型(多对一问题)。我正在努力格式化我的...
我不太确定您要如何进行此重塑,但是this层希望使用2D张量,而不是您要尝试通过此层的3D张量。