machine-learning - Keras LSTM 输入特征和错误的维度数据输入

标签 machine-learning neural-network keras lstm

所以我正在尝试练习如何在 Keras 和所有参数(样本、时间步长、特征)中使用 LSTM。 3D 列表让我感到困惑。

所以我有一些股票数据,如果列表中的下一个项目高于 5 的阈值(即 +-2.50),则它会买入或卖出,如果它位于所持有的阈值的中间,则这些是我的标签:我的Y。

对于我的 X 特征,我的 500 个样本的数据帧为 [500, 1, 3],每个时间步长为 1,因为每个数据都是 1 小时增量,3 个特征为 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)
"""

谢谢。

最佳答案

这是我在这里发表的第一篇文章,我希望它有用,我会尽力做到最好

首先,您需要创建 3 维数组以在 keras 中使用 input_shape 您可以在 keras 文档中或以更好的方式观看此内容: 从 keras.models 导入顺序 顺序的? 线性堆叠层。

参数

layers: list of layers to add to the model.

# 注意 第一层传递给顺序模型 应该有一个定义的输入形状。那是什么 意思是它应该收到一个 input_shape 或batch_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))

之后如何将 2 维数组转换为 3 维数组 检查 np.newaxis

有用的命令对您的帮助超出您的预期:

  • 顺序?, -顺序??, -print(列表(dir(顺序)))

最佳

关于machine-learning - Keras LSTM 输入特征和错误的维度数据输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46437058/

相关文章:

artificial-intelligence - 在本体中审查二手知识

Matlab 神经网络模拟直至隐藏层

machine-learning - 神经网络的命名约定

python-3.x - OpenBLAS blas_thread_init : pthread_create: Resource temporarily unavailable

matlab - 如何使用 Matlab 的 quadprog 实现 soft-margin SVM 模型?

python - 安装 mlxtend 时权限被拒绝 (Python 3)

c++ - 自定义caffe windows cpp中的卷积层

python - 如何在Python中保存所有深度学习模型参数?

python - 在没有互联网连接的情况下安装tensorflow

r - 根据变量是否在列表中对数据进行子集化