如何使用 Keras 和 Tensorflow 在 Python 的 LSTM 网络中获得多个输出?
How can I get multiple outputs in an LSTM network in Python with Keras and Tensorflow?
我第一次使用 Keras 中的 LSTM 和 Python 中的 Tensorflow,我想创建一个具有一些层并提供 10 个输出值的神经网络。我在神经网络中生成了多个层,并创建了一个包含 10 个元素的输出 DenseLayer。我有下一个代码:
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from math import sqrt
from matplotlib import pyplot
import numpy
from numpy import array
import math
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return numpy.array(dataX), numpy.array(dataY)
look_back = 10
epochs = 1000
batch_size = 50
data = data.astype('float32')
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(data)
# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(100, activation = 'tanh', inner_activation = 'hard_sigmoid', return_sequences=True))#, input_shape=(1, look_back)))
model.add(LSTM(50, activation = 'tanh', inner_activation = 'hard_sigmoid', return_sequences=True))
model.add(LSTM(25, activation = 'tanh', inner_activation = 'hard_sigmoid'))
# I want 10 outputs
model.add(Dense(10))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=epochs, batch_size=batch_size, verbose=2)
但是当我执行代码时,我收到下一条错误消息:
ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
我该怎么做才能解决这个问题?我想对接下来的 10 个元素进行预测,这就是我放置最后一层 10 个元素的原因。
从您上面所说的错误 ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
是由于您的目标有问题:
- 您有一个作为目标的值列表。
- 您尝试预测十个值,但只有一个值可以与之比较。
您需要修改 trainY 矩阵以包含您希望预测的每个值。
例如,如果您希望预测最近的未来的 5 个值,您需要一个大小为 5 的目标线(即每个元素),包括所有值。
因此,您将训练网络预测 5 个未来值。
我会尽力为您提供代码,但这只是为了获得未来价值而进行的重塑。
更准确地说,对于 1 X(一个输入),您需要 y=[v1,v2,v3,v4,v5]
所以如果你有 train = [X1,X2,..]
那么 Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]
我第一次使用 Keras 中的 LSTM 和 Python 中的 Tensorflow,我想创建一个具有一些层并提供 10 个输出值的神经网络。我在神经网络中生成了多个层,并创建了一个包含 10 个元素的输出 DenseLayer。我有下一个代码:
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from math import sqrt
from matplotlib import pyplot
import numpy
from numpy import array
import math
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return numpy.array(dataX), numpy.array(dataY)
look_back = 10
epochs = 1000
batch_size = 50
data = data.astype('float32')
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(data)
# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(100, activation = 'tanh', inner_activation = 'hard_sigmoid', return_sequences=True))#, input_shape=(1, look_back)))
model.add(LSTM(50, activation = 'tanh', inner_activation = 'hard_sigmoid', return_sequences=True))
model.add(LSTM(25, activation = 'tanh', inner_activation = 'hard_sigmoid'))
# I want 10 outputs
model.add(Dense(10))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=epochs, batch_size=batch_size, verbose=2)
但是当我执行代码时,我收到下一条错误消息:
ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
我该怎么做才能解决这个问题?我想对接下来的 10 个元素进行预测,这就是我放置最后一层 10 个元素的原因。
从您上面所说的错误 ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
是由于您的目标有问题:
- 您有一个作为目标的值列表。
- 您尝试预测十个值,但只有一个值可以与之比较。
您需要修改 trainY 矩阵以包含您希望预测的每个值。 例如,如果您希望预测最近的未来的 5 个值,您需要一个大小为 5 的目标线(即每个元素),包括所有值。
因此,您将训练网络预测 5 个未来值。 我会尽力为您提供代码,但这只是为了获得未来价值而进行的重塑。
更准确地说,对于 1 X(一个输入),您需要 y=[v1,v2,v3,v4,v5]
所以如果你有 train = [X1,X2,..]
那么 Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]