2017-09-26 8 views
2

그래서 Keras 및 모든 매개 변수 (샘플, 타임 스텝, 기능)에서 LSTM을 사용하는 방법을 연습하려고합니다. 3D 목록이 나를 혼란스럽게합니다.Keras LSTM 입력 기능 및 잘못된 치수 데이터 입력

따라서 재고 데이터가 있고 목록의 다음 항목이 + -2.50 인 임계 값 5보다 높거나 OR 판매를하는 경우 임계 값의 중간에 있으면 내 레이블입니다 : 내 Y.

내 XI의 데이터 샘플은 [500, 1, 3]이며 각 데이터는 1 시간 단위이고 3 개의 기능은 3이므로 각 시간 단계는 1입니다. 하지만이 오류가 발생합니다 :

ValueError: Error when checking model input: expected lstm_1_input to have 3 dimensions, but got array with shape (500, 3) 

어떻게하면이 코드를 수정할 수 있습니까? 무엇이 잘못 되었나요?

import json 
import pandas as pd 
from keras.models import Sequential 
from keras.layers import Dense 
from keras.layers import LSTM 

""" 
Sample of JSON file 
{"time":"2017-01-02T01:56:14.000Z","usd":8.14}, 
{"time":"2017-01-02T02:56:14.000Z","usd":8.16}, 
{"time":"2017-01-02T03:56:15.000Z","usd":8.14}, 
{"time":"2017-01-02T04:56:16.000Z","usd":8.15} 
""" 
file = open("E.json", "r", encoding="utf8") 
file = json.load(file) 

""" 
If the price jump of the next item is > or < +-2.50 the append 'Buy or 'Sell' 
If its in the range of +- 2.50 then append 'Hold' 
This si my classifier labels 
""" 
data = [] 
for row in range(len(file['data'])): 
    row2 = row + 1 
    if row2 == len(file['data']): 
     break 
    else: 
     difference = file['data'][row]['usd'] - file['data'][row2]['usd'] 
     if difference > 2.50: 
      data.append((file['data'][row]['usd'], 'SELL')) 
     elif difference < -2.50: 
      data.append((file['data'][row]['usd'], 'BUY')) 
     else: 
      data.append((file['data'][row]['usd'], 'HOLD')) 

""" 
add the price the time step which si 1 and the features which is 3 
""" 
frame = pd.DataFrame(data) 
features = pd.DataFrame() 
# train LSTM 
for x in range(500): 
    series = pd.Series(data=[500, 1, frame.iloc[x][0]]) 
    features = features.append(series, ignore_index=True) 

labels = frame.iloc[16000:16500][1] 

# test 
#yt = frame.iloc[16500:16512][0] 
#xt = pd.get_dummies(frame.iloc[16500:16512][1]) 


# create LSTM 
model = Sequential() 
model.add(LSTM(3, input_shape=features.shape, activation='relu', return_sequences=False)) 
model.add(Dense(2, activation='relu')) 
model.add(Dense(1, activation='relu')) 

model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) 


model.fit(x=features.as_matrix(), y=labels.as_matrix()) 

""" 
ERROR 
Anaconda3\envs\Final\python.exe C:/Users/Def/PycharmProjects/Ether/Main.py 
Using Theano backend. 
Traceback (most recent call last): 
    File "C:/Users/Def/PycharmProjects/Ether/Main.py", line 62, in <module> 
    model.fit(x=features.as_matrix(), y=labels.as_matrix()) 
    File "\Anaconda3\envs\Final\lib\site-packages\keras\models.py", line 845, in fit 
    initial_epoch=initial_epoch) 
    File "\Anaconda3\envs\Final\lib\site-packages\keras\engine\training.py", line 1405, in fit 
    batch_size=batch_size) 
    File "\Anaconda3\envs\Final\lib\site-packages\keras\engine\training.py", line 1295, in _standardize_user_data 
    exception_prefix='model input') 
    File "\Anaconda3\envs\Final\lib\site-packages\keras\engine\training.py", line 121, in _standardize_input_data 
    str(array.shape)) 
ValueError: Error when checking model input: expected lstm_1_input to have 3 dimensions, but got array with shape (500, 3) 
""" 

감사합니다.

답변

0

이것은 내 첫 번째 게시물 내가 그 내가 가장 잘 keras에서 input_shape 작업을 3 차원 배열을 만들 필요가

먼저 keras 설명서 나이를 볼 수 있습니다 수행하려고합니다 도움이 될 수 있으면 좋겠다 여기에있다 더 좋은 방법 : keras.models 가져 오기 순차적 순차? 선형 스택.

인수

layers: list of layers to add to the model. 

# 참고 순차 모델에 전달 된 제 1 층은 한정된 입력 형상을 가져야한다. 무슨 의미하는 것은 그것이 input_shape 또는 batch_input_shape 인수 를 수신 또는 층의 일부 유형 (재발, ​​밀도 ...) input_dim 인수해야한다는 것이다.

  • 연속 : 3 dimmension에 배열 2 차원 변환하는 방법 그 후

    ```python 
        model = Sequential() 
        # first layer must have a defined input shape 
        model.add(Dense(32, input_dim=500)) 
        # afterwards, Keras does automatic shape inference 
        model.add(Dense(32)) 
    
        # also possible (equivalent to the above): 
        model = Sequential() 
        model.add(Dense(32, input_shape=(500,))) 
        model.add(Dense(32)) 
    
        # also possible (equivalent to the above): 
        model = Sequential() 
        # here the batch dimension is None, 
        # which means any batch size will be accepted by the model. 
        model.add(Dense(32, batch_input_shape=(None, 500))) 
        model.add(Dense(32)) 
    

    는 검사가 예상 한 것보다 더 많은 도움이

    유용한 명령을 np.newaxis ?, -Sequential ??, -print (list (dir (Sequential)))

최고