如何使用Keras为可变大小的块创建LSTM?

时间:2017-07-21 22:19:16

标签: python keras lstm keras-layer

我正在尝试使用Keras创建一个LSTM,但我正在努力解决这个问题。基本上我有几个时间块,每个时间块都有可变数量的数组,每个数组大小为3.以下是这个图:
| - 时间块 - | - - 数组1 - - | - - 数组2 - - | - - 数组3 - - | ...... | - - - - 1 - - - - - | < 3矢量> | < 3矢量> |
| - - - - 2 - - - - - | < 3矢量> |
| - - - - 3 - - - - - | < 3矢量> | < 3矢量> | < 3矢量> |
...... 每个时间块只是序列中的一个元素,每个时间块中的数组都是任意顺序(它们彼此不对应,如果它们的顺序不同,则应该没有区别)。
此输入的输出应为每个3向量的1或0的数组,例如[[[3,4,2],[2,3,4]],[[1,3,4]]] - > [[1,0],[1]]
以下是我提出的,但它非常缺陷。

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
model = Sequential()
# fixed feature size of 3, unknown number of vectors
model.add(LSTM(64, input_dim=3, input_length=None, return_sequences=True))
model.add(Dropout(0.5))
model.add(LSTM(64, return_sequences=True))
model.add(Dropout(0.5))
# number of outputs is the (previously unknown) number of vectors
model.add(Dense(None, activation='sigmoid')) # obviously this is incorrect...

# Example training phase:
model.compile(optimizer='rmsprop', loss='mean_squared_error', \
    metrics=['accuracy'])
x_train = [np.array([[1, 2, 3], [4,5,6]]), \
           np.array([[4, 1, 4], [1, 1, 5], [3, 2, 1]]), \
           np.array([[3, 2, 1], [2, 3, 2]]), \
           np.array([[7, 4, 3], [2, 6, 4], [2, 5, 7], [3, 8, 5]])]
y_train = [np.array([0, 0]), np.array([0, 1, 0]), \
    np.array([1, 1, 0]), np.array([0, 0, 0, 1])]
model.fit(x_train, y_train, epochs=2000, batch_size=3)
# Testing/evaluating phase would be similar to the above

以上是我的主要问题。此外,在我的训练数据中,由于数据非常不平衡,所以将会有比0更多的1s - 几乎是2500:1的比率(这是实际比率,因此收集更多数据不会改变这一点)。如果这是一个前馈网络,我可以消除一些与0相对应的数据,以平衡它(通过欠采样)。很明显,我不能用LSTM做到这一点 - 那么我该如何训练不平衡类的模型会计呢?

0 个答案:

没有答案