由于Numpy返回对象而导致值错误

时间:2018-07-27 23:24:26

标签: numpy keras time-series cntk stockquotes

我正在尝试在最终运行时编写以下代码。

但是,当我尝试拟合模型时出现以下错误: “ ValueError:设置具有序列的数组元素。”

我正在尝试使用RNN预测未来5天的价格。因此,在函数create_ts中,我试图创建两个时间序列,一个具有前X个项目,另一个具有X + 1,X + 2,X + 3,X + 4和X + 5-这五个项目是我接下来要预测的五天价格。

我怀疑问题出在这里:

def create_ts(ds, series, day_gap):
      x, y = [], []
      for i in range(len(ds) - series - 1):
        item = ds[i:(i+series),0]
        x.append(item)
        next_item = ds[i+series:(i+series+day_gap), 0]
        y.append(next_item)
      #print(type(np.array(x)), type(np.array(y)))
      return np.array(x), np.array(y).reshape(-1,1)

series = 5
predict_days = 5

train_x, train_y = create_ts(stock_train, series, predict_days)
test_x, test_y = create_ts(stock_test, series, predict_days)

#reshape into LSTM format - samples, steps, features
train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 1))
test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 1))

#build model
model = Sequential()
model.add(LSTM(4,input_shape = (series, 1)))
model.add(Dense(1))
model.compile(loss='mse', optimizer = 'adam')
#fit model
model.fit(train_x, train_y, epochs = 100, batch_size = 32)

在此先感谢您的帮助!

下面是完整的代码段:

from keras import backend as k
import os
from importlib import reload

def set_keras_backend(backend):
  if k.backend() != backend:
    os.environ['KERAS_BACKEND'] = backend
    reload(k)
    assert k.backend() == backend


set_keras_backend("cntk")

import numpy as np
import pandas as pd
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import math

np.random.seed(7)

#load dataset
fileloc = "C:\\Stock Data\\CL1.csv"

stock_data = pd.read_csv(fileloc)
stock_data.head()

stock_data.dtypes

stock_data['Date'] = pd.to_datetime(stock_data['Date'])
stock_data['Price'] = pd.to_numeric(stock_data['Price'], downcast = 'float')

stock_data.set_index('Date', inplace=True)

stock_close = stock_data['Price']

stock_close = stock_close.values.reshape(len(stock_close), 1)
plt.plot(stock_close)

#normalize data
scaler = MinMaxScaler(feature_range = (0,1))
stock_close = scaler.fit_transform(stock_close)

#split data into a train, test set
train_size = int(len(stock_close)*0.7)
test_size = len(stock_close) - train_size

stock_train, stock_test = stock_close[0:train_size, :], stock_close[train_size:len(stock_close), :]

#convert the data into a time series looking back over a period fo days

def create_ts(ds, series, day_gap):
  x, y = [], []
  for i in range(len(ds) - series - 1):
    item = ds[i:(i+series),0]
    x.append(item)
    next_item = ds[i+series:(i+series+day_gap), 0]
    y.append(next_item)
  #print(type(np.array(x)), type(np.array(y)))
  return np.array(x), np.array(y).reshape(-1,1)

series = 5
predict_days = 5

train_x, train_y = create_ts(stock_train, series, predict_days)
test_x, test_y = create_ts(stock_test, series, predict_days)

#reshape into LSTM format - samples, steps, features
train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 1))
test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 1))

#build model
model = Sequential()
model.add(LSTM(4,input_shape = (series, 1)))
model.add(Dense(1))
model.compile(loss='mse', optimizer = 'adam')
#fit model
model.fit(train_x, train_y, epochs = 100, batch_size = 32)

0 个答案:

没有答案