2017-09-26 310 views
2

所以我想練習如何在Keras和所有參數(樣本,時間步長,功能)使用LSTMs。 3D列表令我困惑。Keras LSTM輸入功能和不正確的三維數據輸入

因此,我有一些股票數據,如果列表中的下一個項目高於5的門檻值+2.50,它會購買或出售,如果它處於該閾值的中間,則這些是我的標籤:我的Y.

對於我的特徵我的XI具有[500,1,3]爲我的500個樣本的數據幀和每個時步爲1,因爲每個數據爲3個特徵1小時增量和3。但我得到這個錯誤:

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

這是我的第一篇文章在這裏,我想這可能是有用的,我會盡我的最佳

首先,你需要創建3維數組與keras input_shape工作,你可以在keras文檔或者觀看這個一個更好的辦法: 從keras.models導入順序 順序? 線性疊層。

參數
layers: list of layers to add to the model. 

#注意 傳遞到順序模型 第一層應具有定義的輸入形狀。 意味着它應該收到一個input_shapebatch_input_shape變元, 或某些類型的層(經常性,密集...) 和input_dim變元。

```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)) 

這之後如何改變陣列在3 dimmension 2名維 檢查np.newaxis

有用的命令可以幫助你,比你預期:

  • 順序?, -Sequential ??, -print(清單(目錄(順序)))

最好