【问题标题】:Predictive model expecting 3 dimension but the array with shape don't match预测模型需要 3 维但形状不匹配的数组
【发布时间】:2020-07-26 18:22:54
【问题描述】:

我正在使用这个公式来预测 Jupyter 中的股票价格:

import keys
import datetime
from binance.client import Client
import pandas as pd

client = Client(keys.APIKey, keys.SecretKey)

symbol= 'BTCUSDT'
BTC= client.get_historical_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_30MINUTE, start_str="1 year ago UTC")

%matplotlib inline

BTC= pd.DataFrame(BTC, columns=['Open time', 'Open', 'High', 'Low', 
                                'Close', 'Volume', 'Close time', 
                                'Quote asset volume','Number of trades',
                                'Taker buy base asset volume', 
                                'Taker buy quote asset volume','Ignore'])

BTC['Open time'] = pd.to_datetime(BTC['Open time'], unit='ms')

BTC.set_index('Open time', inplace=True)
BTC

data= BTC.iloc[:,3:4].astype(float).values
from sklearn.preprocessing import MinMaxScaler

scaler= MinMaxScaler()
data=scaler.fit_transform(data)
training_set= data[:10000]
test_set=data[10000:]

X_train= training_set[0:len(training_set)-1]
y_train= training_set[1:len(training_set)]
X_test= test_set[0:len(test_set)-1]
y_test= test_set[1:len(test_set)]

import numpy as np
X_train = np.reshape(X_train, (len(X_train), 1, X_train.shape[1]))
x_test = np.reshape(X_test, (len(X_test), 1, X_test.shape[1]))

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

model = Sequential()
model.add(LSTM(256, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(LSTM(256))
model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X_train, y_train, epochs=50, batch_size=16, shuffle=False)

predicted_price= model.predict(X_test)
predicted_price= scaler.inverse_transform(predicted_price)
real_price = scaler.inverse_transform(y_test)

但是,我没有得到真实与预测图,而是得到了这个错误:


ValueError Traceback(最近调用 最后)在 ----> 1 predict_price=model.predict([X_test]) 2 predicted_price=scaler.inverse_transform(predicted_price) 3 real_price = scaler.inverse_transform(y_test)

E:\anaconda3\lib\site-packages\keras\engine\training.py 在 预测(自我,x,batch_size,详细,步骤,回调, max_queue_size、workers、use_multiprocessing) 1439 1440

案例 2:符号张量或类似 Numpy 数组。 -> 1441 x, _, _ = self._standardize_user_data(x) 1442 if self.stateful: 1443 if x[0].shape[0] > batch_size 和 x[0].shape[0] % batch_size != 0:

E:\anaconda3\lib\site-packages\keras\engine\training.py 在 _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 第577章 578 check_batch_axis=False, # 不强制批量大小。 --> 579 异常前缀='输入') 580 581 如果 y 不是无:

E:\anaconda3\lib\site-packages\keras\engine\training_utils.py 在 标准化输入数据(数据,名称,形状,check_batch_axis, 异常前缀) 133 ': 预期 ' + names[i] + ' 有 ' + 134 str(len(shape)) + ' 维度,但得到了数组 ' --> 135 '带形状' + str(data_shape)) 136 如果不是 check_batch_axis: 137 数据形状=数据形状[1:]

ValueError:检查输入时出错:预期 lstm_1_input 有 3 尺寸,但得到形状为 (7505, 1) 的数组

即使有这个日志,我也无法指出修复它的根本原因。

【问题讨论】:

标签: python python-3.x tensorflow keras jupyter-notebook


【解决方案1】:

LSTM 模型需要输入 dim = 3:(#samples、timestamp、features)。
因此,例如,如果您有 7505 个音频文件,每个文件有 100 个时间戳,每个时间戳有 578 个特征 - 火车集应该具有当前形状:(3,100,578)。
您的输入形状是 (#samples, features),因此将其重塑为 3 维 - 对于 X_train 和 X_train。

x_train = np.reshape(X_train, (len(X_train), 1, X_train.shape[1]))
x_test = np.reshape(X_test, (len(X_test), 1, X_test.shape[1]))

另外,请确保您调用 fitpredict 并使用重新调整的数据。

model.fit(x_train, y_train, epochs=50, batch_size=16, shuffle=False)
#.....
predicted_price= model.predict(x_test) #<--- Your problem was here! Make sure you use x_test and not X_test.

【讨论】:

  • 你就是那个男人!我会去记录一下 X_test 和 x_test 之间的区别。再次感谢您!
猜你喜欢
  • 2017-12-27
  • 1970-01-01
  • 2018-07-18
  • 2018-11-16
  • 2023-03-09
  • 2021-12-13
  • 2019-09-04
  • 2018-08-21
  • 1970-01-01
相关资源
最近更新 更多