How can I get multiple outputs in an LSTM network in Python with Keras and Tensorflow?
I am working by first time with LSTMs in Keras and Tensorflow in Python, and I want to create a neural network with some layers and which gives 10 output values. I generated multiple layers in a neural network, and I created an output DenseLayer of 10 elements. I have the next code:
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)
But when I execute the code I get the next error message:
ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
What can I do to solve the problem? I want to give me predictions for the next 10 elements, that is the reason why I put a final layer of 10 elements.
python tensorflow keras layer prediction
add a comment |
I am working by first time with LSTMs in Keras and Tensorflow in Python, and I want to create a neural network with some layers and which gives 10 output values. I generated multiple layers in a neural network, and I created an output DenseLayer of 10 elements. I have the next code:
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)
But when I execute the code I get the next error message:
ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
What can I do to solve the problem? I want to give me predictions for the next 10 elements, that is the reason why I put a final layer of 10 elements.
python tensorflow keras layer prediction
what's the shape of the target (trainyY)?
– Alexis
Nov 20 '18 at 9:07
This is an example of a trainY array: array([0.5125213 , 0.52500796, 0.53751385, ..., 0.52500796, 0.5250104 ,0.56250316], dtype=float32)
– jartymcfly
Nov 20 '18 at 9:38
this is the trainY array or an element of the train array? if it's the trainY array, then the error is here, else i don't know yet
– Alexis
Nov 20 '18 at 9:50
Yes, this is the trainY array.
– jartymcfly
Nov 20 '18 at 9:52
But, how could I fix it? Do I must to reshape the trainY also, as I did with trainX?
– jartymcfly
Nov 20 '18 at 9:58
add a comment |
I am working by first time with LSTMs in Keras and Tensorflow in Python, and I want to create a neural network with some layers and which gives 10 output values. I generated multiple layers in a neural network, and I created an output DenseLayer of 10 elements. I have the next code:
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)
But when I execute the code I get the next error message:
ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
What can I do to solve the problem? I want to give me predictions for the next 10 elements, that is the reason why I put a final layer of 10 elements.
python tensorflow keras layer prediction
I am working by first time with LSTMs in Keras and Tensorflow in Python, and I want to create a neural network with some layers and which gives 10 output values. I generated multiple layers in a neural network, and I created an output DenseLayer of 10 elements. I have the next code:
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)
But when I execute the code I get the next error message:
ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
What can I do to solve the problem? I want to give me predictions for the next 10 elements, that is the reason why I put a final layer of 10 elements.
python tensorflow keras layer prediction
python tensorflow keras layer prediction
asked Nov 20 '18 at 8:54
jartymcflyjartymcfly
5112724
5112724
what's the shape of the target (trainyY)?
– Alexis
Nov 20 '18 at 9:07
This is an example of a trainY array: array([0.5125213 , 0.52500796, 0.53751385, ..., 0.52500796, 0.5250104 ,0.56250316], dtype=float32)
– jartymcfly
Nov 20 '18 at 9:38
this is the trainY array or an element of the train array? if it's the trainY array, then the error is here, else i don't know yet
– Alexis
Nov 20 '18 at 9:50
Yes, this is the trainY array.
– jartymcfly
Nov 20 '18 at 9:52
But, how could I fix it? Do I must to reshape the trainY also, as I did with trainX?
– jartymcfly
Nov 20 '18 at 9:58
add a comment |
what's the shape of the target (trainyY)?
– Alexis
Nov 20 '18 at 9:07
This is an example of a trainY array: array([0.5125213 , 0.52500796, 0.53751385, ..., 0.52500796, 0.5250104 ,0.56250316], dtype=float32)
– jartymcfly
Nov 20 '18 at 9:38
this is the trainY array or an element of the train array? if it's the trainY array, then the error is here, else i don't know yet
– Alexis
Nov 20 '18 at 9:50
Yes, this is the trainY array.
– jartymcfly
Nov 20 '18 at 9:52
But, how could I fix it? Do I must to reshape the trainY also, as I did with trainX?
– jartymcfly
Nov 20 '18 at 9:58
what's the shape of the target (trainyY)?
– Alexis
Nov 20 '18 at 9:07
what's the shape of the target (trainyY)?
– Alexis
Nov 20 '18 at 9:07
This is an example of a trainY array: array([0.5125213 , 0.52500796, 0.53751385, ..., 0.52500796, 0.5250104 ,0.56250316], dtype=float32)
– jartymcfly
Nov 20 '18 at 9:38
This is an example of a trainY array: array([0.5125213 , 0.52500796, 0.53751385, ..., 0.52500796, 0.5250104 ,0.56250316], dtype=float32)
– jartymcfly
Nov 20 '18 at 9:38
this is the trainY array or an element of the train array? if it's the trainY array, then the error is here, else i don't know yet
– Alexis
Nov 20 '18 at 9:50
this is the trainY array or an element of the train array? if it's the trainY array, then the error is here, else i don't know yet
– Alexis
Nov 20 '18 at 9:50
Yes, this is the trainY array.
– jartymcfly
Nov 20 '18 at 9:52
Yes, this is the trainY array.
– jartymcfly
Nov 20 '18 at 9:52
But, how could I fix it? Do I must to reshape the trainY also, as I did with trainX?
– jartymcfly
Nov 20 '18 at 9:58
But, how could I fix it? Do I must to reshape the trainY also, as I did with trainX?
– jartymcfly
Nov 20 '18 at 9:58
add a comment |
1 Answer
1
active
oldest
votes
From what you have said above the error ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
is due to a problem in your target:
- you have a list of values that are the targets.
- you try to predict ten values while having only one to compare to.
you need to rework the trainY matrx to include every value you wish to predict.
for example if you wish to predict the 5 values in the closest futur, you'll need a target line (ie each element) of size 5 including all values.
as such you'll train the network to predict the 5 futur values.
i'll try to get you the code howerver it's just a reshaping with a roll to get futur values.
to be more precise, for 1 X (one input) you'll need a y=[v1,v2,v3,v4,v5]
so if you have train = [X1,X2,..]
then Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]
1
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389331%2fhow-can-i-get-multiple-outputs-in-an-lstm-network-in-python-with-keras-and-tenso%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
From what you have said above the error ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
is due to a problem in your target:
- you have a list of values that are the targets.
- you try to predict ten values while having only one to compare to.
you need to rework the trainY matrx to include every value you wish to predict.
for example if you wish to predict the 5 values in the closest futur, you'll need a target line (ie each element) of size 5 including all values.
as such you'll train the network to predict the 5 futur values.
i'll try to get you the code howerver it's just a reshaping with a roll to get futur values.
to be more precise, for 1 X (one input) you'll need a y=[v1,v2,v3,v4,v5]
so if you have train = [X1,X2,..]
then Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]
1
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
add a comment |
From what you have said above the error ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
is due to a problem in your target:
- you have a list of values that are the targets.
- you try to predict ten values while having only one to compare to.
you need to rework the trainY matrx to include every value you wish to predict.
for example if you wish to predict the 5 values in the closest futur, you'll need a target line (ie each element) of size 5 including all values.
as such you'll train the network to predict the 5 futur values.
i'll try to get you the code howerver it's just a reshaping with a roll to get futur values.
to be more precise, for 1 X (one input) you'll need a y=[v1,v2,v3,v4,v5]
so if you have train = [X1,X2,..]
then Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]
1
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
add a comment |
From what you have said above the error ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
is due to a problem in your target:
- you have a list of values that are the targets.
- you try to predict ten values while having only one to compare to.
you need to rework the trainY matrx to include every value you wish to predict.
for example if you wish to predict the 5 values in the closest futur, you'll need a target line (ie each element) of size 5 including all values.
as such you'll train the network to predict the 5 futur values.
i'll try to get you the code howerver it's just a reshaping with a roll to get futur values.
to be more precise, for 1 X (one input) you'll need a y=[v1,v2,v3,v4,v5]
so if you have train = [X1,X2,..]
then Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]
From what you have said above the error ValueError: Error when checking target: expected dense_1 to have shape (10,) but got array with shape (1,)
is due to a problem in your target:
- you have a list of values that are the targets.
- you try to predict ten values while having only one to compare to.
you need to rework the trainY matrx to include every value you wish to predict.
for example if you wish to predict the 5 values in the closest futur, you'll need a target line (ie each element) of size 5 including all values.
as such you'll train the network to predict the 5 futur values.
i'll try to get you the code howerver it's just a reshaping with a roll to get futur values.
to be more precise, for 1 X (one input) you'll need a y=[v1,v2,v3,v4,v5]
so if you have train = [X1,X2,..]
then Y = [[v1,v2,v3,v4,v5],[v2,v3,v4,v5,v6]
answered Nov 20 '18 at 10:01
AlexisAlexis
1,005313
1,005313
1
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
add a comment |
1
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
1
1
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
Perfect! It seems it works! Thank you :)
– jartymcfly
Nov 20 '18 at 10:19
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389331%2fhow-can-i-get-multiple-outputs-in-an-lstm-network-in-python-with-keras-and-tenso%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
what's the shape of the target (trainyY)?
– Alexis
Nov 20 '18 at 9:07
This is an example of a trainY array: array([0.5125213 , 0.52500796, 0.53751385, ..., 0.52500796, 0.5250104 ,0.56250316], dtype=float32)
– jartymcfly
Nov 20 '18 at 9:38
this is the trainY array or an element of the train array? if it's the trainY array, then the error is here, else i don't know yet
– Alexis
Nov 20 '18 at 9:50
Yes, this is the trainY array.
– jartymcfly
Nov 20 '18 at 9:52
But, how could I fix it? Do I must to reshape the trainY also, as I did with trainX?
– jartymcfly
Nov 20 '18 at 9:58