Machine learning Keras LSTM输入特征和不正确的尺寸数据输入

Machine learning Keras LSTM输入特征和不正确的尺寸数据输入,machine-learning,neural-network,keras,lstm,Machine Learning,Neural Network,Keras,Lstm,因此,我试图练习如何在Keras和所有参数(示例、时间步、特性)中使用LSTMs。3D列表让我困惑 p>所以我有一些股票数据,如果列表中的下一个项目在5的阈值以上,即+-2.50,它购买或卖出,如果它在该阈值的中间,它是我的标签:Y../P> 对于我的功能我的X,我的500个样本的数据帧为[500,1,3],每个时间步为1,因为每个数据是1小时增量,3个功能为3。但我得到了这个错误: ValueError: Error when checking model input: expected l

因此,我试图练习如何在Keras和所有参数(示例、时间步、特性)中使用LSTMs。3D列表让我困惑

<> p>所以我有一些股票数据,如果列表中的下一个项目在5的阈值以上,即+-2.50,它购买或卖出,如果它在该阈值的中间,它是我的标签:Y../P> 对于我的功能我的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)
"""
导入json
作为pd进口熊猫
从keras.models导入顺序
从keras.layers导入稠密
从keras.layers导入LSTM
"""
JSON文件示例
{“时间”:“2017-01-02T01:56:14.000Z”,“美元”:8.14},
{“时间”:“2017-01-02T02:56:14.000Z”,“美元”:8.16},
{“时间”:“2017-01-02T03:56:15.000Z”,“美元”:8.14},
{“时间”:“2017-01-02T04:56:16.000Z”,“美元”:8.15}
"""
file=open(“E.json”,“r”,encoding=“utf8”)
file=json.load(文件)
"""
如果下一个项目的价格涨幅大于或<+-2.50,则追加“买入”或“卖出”
如果其在+-2.50范围内,则附加“保持”
这是我的分类标签
"""
数据=[]
对于范围(len(文件['data'])中的行:
行2=行+1
如果行2==len(文件['data']):
打破
其他:
差异=文件['data'][行]['usd']-文件['data'][行2]['usd']
如果差值>2.50:
data.append((文件['data'][row]['usd'],'SELL'))
elif差值<-2.50:
data.append((文件['data'][行]['usd'],'BUY'))
其他:
data.append((文件['data'][行]['usd'],'HOLD'))
"""
将价格加上si 1的时间步长和si 3的特征
"""
frame=pd.DataFrame(数据)
features=pd.DataFrame()
#列车LSTM
对于范围(500)内的x:
series=pd.series(数据=[500,1,frame.iloc[x][0]]
features=features.append(系列,忽略索引=True)
labels=frame.iloc[16000:16500][1]
#试验
#yt=frame.iloc[16500:16512][0]
#xt=pd.get_假人(frame.iloc[16500:16512][1])
#创建LSTM
模型=顺序()
添加(LSTM(3,输入形状=特征.shape,激活='relu',返回顺序=False))
model.add(密集(2,activation='relu'))
model.add(密集(1,activation='relu'))
compile(loss='mse',optimizer='adam',metrics=['accurity'])
model.fit(x=特征.as_矩阵(),y=标签.as_矩阵())
"""
错误
Anaconda3\envs\Final\python.exe C:/Users/Def/PycharmProjects/Ether/Main.py
使用Theano后端。
回溯(最近一次呼叫最后一次):
文件“C:/Users/Def/PycharmProjects/Ether/Main.py”,第62行,在
model.fit(x=特征.as_矩阵(),y=标签.as_矩阵())
文件“\Anaconda3\envs\Final\lib\site packages\keras\models.py”,第845行,格式为fit
初始_历元=初始_历元)
文件“\Anaconda3\envs\Final\lib\site packages\keras\engine\training.py”,第1405行,适合
批次大小=批次大小)
文件“\Anaconda3\envs\Final\lib\site packages\keras\engine\training.py”,第1295行,在用户数据中
异常(前缀为“模型输入”)
文件“\Anaconda3\envs\Final\lib\site packages\keras\engine\training.py”,第121行,输入数据
str(array.shape))
ValueError:检查模型输入时出错:预期lstm_1_输入有3个维度,但得到了形状为(500,3)的数组
"""

谢谢。

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

首先,您需要创建三维数组,以便在keras中使用输入_形状。您可以在keras文档中或以更好的方式查看: 从keras.models导入顺序 顺序的 层的线性堆叠

论据 #注意 第一层传递给顺序模型 应具有定义的输入形状。那是什么 这意味着它应该已经收到一个
输入\u形状
batch\u input\u shape
参数, 或者对于某些类型的层(重复、密集…) 一个
输入\u dim
参数。

例子 之后,如何在三维空间中变换二维数组 检查np.newaxis

帮助您的有用命令比您预期的要多:

  • 连续的?, -顺序的??, -打印(列表(目录(顺序)))
最好的

layers: list of layers to add to the model.
```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))