【发布时间】:2021-08-31 06:53:34
【问题描述】:
具有 10 天的传感器事件序列和一个真/假标签,指定传感器是否在 10 天内触发警报:
| sensor_id | timestamp | feature_1 | feature_2 | 10_days_alert_label |
|---|---|---|---|---|
| 1 | 2020-12-20 01:00:34.565 | 0.23 | 0.1 | 1 |
| 1 | 2020-12-20 01:03:13.897 | 0.3 | 0.12 | 1 |
| 2 | 2020-12-20 01:00:34.565 | 0.13 | 0.4 | 0 |
| 2 | 2020-12-20 01:03:13.897 | 0.2 | 0.9 | 0 |
95% 的传感器不会触发警报,因此数据不平衡。我正在考虑使用自动编码器模型来检测异常(触发警报的传感器)。由于我对解码整个序列不感兴趣,只是 LSTM 学习了上下文向量,所以我在想类似下图的东西,其中解码器正在重建编码器输出:
我搜索了一下,发现了这个简单的 LSTM 自动编码器示例:
# lstm autoencoder recreate sequence
from numpy import array
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import RepeatVector
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.utils import plot_model
# define input sequence
sequence = array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
# reshape input into [samples, timesteps, features]
n_in = len(sequence)
sequence = sequence.reshape((1, n_in, 1))
# define model
model = Sequential()
model.add(LSTM(100, activation='relu', input_shape=(n_in,1)))
model.add(RepeatVector(n_in))
model.add(LSTM(100, activation='relu', return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.compile(optimizer='adam', loss='mse')
# fit model
model.fit(sequence, sequence, epochs=300, verbose=0)
plot_model(model, show_shapes=True, to_file='reconstruct_lstm_autoencoder.png')
# demonstrate recreation
yhat = model.predict(sequence, verbose=0)
print(yhat[0,:,0])
我想修改上面的示例,以便将第一个 LSTM 输出用作解码器目标。比如:
# lstm autoencoder recreate sequence
from numpy import array
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import RepeatVector
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.utils import plot_model
# define input sequence
sequence = array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
# reshape input into [samples, timesteps, features]
n_in = len(sequence)
sequence = sequence.reshape((1, n_in, 1))
# define model
model = Sequential()
model.add(LSTM(100, activation='relu', input_shape=(n_in,1)))
model.add(Dense(100, activation='relu')) # First LSTM output
model.add(Dense(32, activation='relu')) # Bottleneck
model.add(Dense(100, activation='sigmoid')) # Decoded vector
model.compile(optimizer='adam', loss='mse')
# fit model
model.fit(sequence, FIRST_LSTM_OUTPUT, epochs=300, verbose=0) # <--- ???
问:我可以使用第一个 LSTM 输出向量作为目标吗?
【问题讨论】:
标签: python tensorflow machine-learning keras lstm