다음은 LSTM을 교육하기 위해 시계열 데이터를 설정하는 예입니다.모델 생성 방법을 보여주기 위해 모델 출력을 설정하기 만하면 모델 출력은 엉뚱한 것입니다.
import pandas as pd
import numpy as np
# Get some time series data
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv")
df.head()
시간 시리즈 dataframe : 당신은 벡터에 넣어 입력을 구축하고 시계열의 순서를 구축 팬더에게 .cumsum()
기능을 사용할 수 있습니다
Date A B C D E F G
0 2008-03-18 24.68 164.93 114.73 26.27 19.21 28.87 63.44
1 2008-03-19 24.18 164.89 114.75 26.22 19.07 27.76 59.98
2 2008-03-20 23.99 164.63 115.04 25.78 19.01 27.04 59.61
3 2008-03-25 24.14 163.92 114.85 27.41 19.61 27.84 59.41
4 2008-03-26 24.44 163.45 114.84 26.86 19.53 28.02 60.09
:
# Put your inputs into a single list
df['single_input_vector'] = df[input_cols].apply(tuple, axis=1).apply(list)
# Double-encapsulate list so that you can sum it in the next step and keep time steps as separate elements
df['single_input_vector'] = df.single_input_vector.apply(lambda x: [list(x)])
# Use .cumsum() to include previous row vectors in the current row list of vectors
df['cumulative_input_vectors'] = df.single_input_vector.cumsum()
출력 유사한 방식으로 설정할 수 있지만 시퀀스 대신 단일 벡터가됩니다 :
# If your output is multi-dimensional, you need to capture those dimensions in one object
# If your output is a single dimension, this step may be unnecessary
df['output_vector'] = df[output_cols].apply(tuple, axis=1).apply(list)
입력 시퀀스는 모델을 통해 실행할 수있는 같은 길이로, 그래서 당신은 그들이 당신의 누적 벡터의 최대 길이로 패드에 필요
# Pad your sequences so they are the same length
from keras.preprocessing.sequence import pad_sequences
max_sequence_length = df.cumulative_input_vectors.apply(len).max()
# Save it as a list
padded_sequences = pad_sequences(df.cumulative_input_vectors.tolist(), max_sequence_length).tolist()
df['padded_input_vectors'] = pd.Series(padded_sequences).apply(np.asarray)
훈련 데이터가에서 가져온 할 수있다 데이터 프레임과 numpy 배열에 넣어. 데이터 프레임에서 나오는 입력 데이터는 3D 배열을 만들지 않습니다. 동일한 배열이 아닌 배열 배열을 만듭니다.
hstack 및 reshape를 사용하여 3D 입력 배열을 만들 수 있습니다.
# Extract your training data
X_train_init = np.asarray(df.padded_input_vectors)
# Use hstack to and reshape to make the inputs a 3d vector
X_train = np.hstack(X_train_init).reshape(len(df),max_sequence_length,len(input_cols))
y_train = np.hstack(np.asarray(df.output_vector)).reshape(len(df),len(output_cols))
그것을 증명하려면, 당신은 훈련 데이터가 있으면
>>> print(X_train_init.shape)
(11,)
>>> print(X_train.shape)
(11, 11, 6)
>>> print(X_train == X_train_init)
False
당신이 당신의 입력 레이어 및 출력 레이어의 크기를 정의 할 수 있습니다.
# Get your input dimensions
# Input length is the length for one input sequence (i.e. the number of rows for your sample)
# Input dim is the number of dimensions in one input vector (i.e. number of input columns)
input_length = X_train.shape[1]
input_dim = X_train.shape[2]
# Output dimensions is the shape of a single output vector
# In this case it's just 1, but it could be more
output_dim = len(y_train[0])
빌드 모델 :
from keras.models import Model, Sequential
from keras.layers import LSTM, Dense
# Build the model
model = Sequential()
# I arbitrarily picked the output dimensions as 4
model.add(LSTM(4, input_dim = input_dim, input_length = input_length))
# The max output value is > 1 so relu is used as final activation.
model.add(Dense(output_dim, activation='relu'))
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['accuracy'])
마지막으로 당신이 모델을 학습과 역사와 교육의 로그를 저장할 수 있습니다
이
# Set batch_size to 7 to show that it doesn't have to be a factor or multiple of your sample size
history = model.fit(X_train, y_train,
batch_size=7, nb_epoch=3,
verbose = 1)
출력 : 그것을
Epoch 1/3
11/11 [==============================] - 0s - loss: 3498.5756 - acc: 0.0000e+00
Epoch 2/3
11/11 [==============================] - 0s - loss: 3498.5755 - acc: 0.0000e+00
Epoch 3/3
11/11 [==============================] - 0s - loss: 3498.5757 - acc: 0.0000e+00
입니다 . 을 사용하십시오. X
은 X_train
과 동일한 형식 (샘플 수 제외)을 사용하여 모델에서 예측을 수행하십시오.
질문에 예제 데이터 세트를 추가 할 수 있습니까? 어떤 입력 시퀀스가 모델에서 어떤 종류의 목표 출력을 만들지는 분명하지 않기 때문에. – mertyildiran
@mertyildiran 유감스럽게도 지금은 예제를 쉽게 만들 수 없습니다. 그러나 모든 회귀 입력, 즉 y에 대한 하나의 timeseries 및 x에 대한 시계입니다. – dreamer
하나의 관찰을위한 형식 또는 데이터 유형을 설명 할 수 있습니까? 그것은 하나의 숫자 값, 일련의 값 또는 다른 것입니까? – Andrew