keras error:Error when checking target: expected dense_2 to have shape (2,) but got array with shape (1,)Error when checking model target: expected dense_24 to have shape…but got array with shape… in KerasValueError: Error when checking target: expected dense_2 to have shape (None, 2) but got array with shape (1, 1)Error when checking target: expected dense_2 to have shape (None, 256) but got array with shape (16210, 4096)How does Keras read input data?Error when checking target: expected dense_2 to have shape (7,) but got array with shape (4,)ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (500,) [Sentiment Analysis]Resolving differences between Keras and scikit-learn for simple fully-connected neural networkIs it possible to train a CNN starting at an intermediate layer (in general and in Keras)?ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (14,)'Sequential' object has no attribute 'loss' - When I used GridSearchCV to tuning my Keras model
Science writing - exact, precise, or accurate
Is Arc Length always irrational between two rational points?
Was the Ford Model T black because of the speed black paint dries?
Why was hardware diversification an asset for the IBM PC ecosystem?
Can I intentionally omit previous work experience or pretend it doesn't exist when applying for jobs?
Bronze Age Underwater Civilization
Extract an attribute value from XML
Correct use of ergeben?
Shortest distance around a pyramid?
As a DM, how to avoid unconscious metagaming when dealing with a high AC character?
Can I play a first turn Simic Growth Chamber to have 3 mana available in the second turn?
Robbers: The Hidden OEIS Substring
Why isn't there research to build a standard lunar, or Martian mobility platform?
Is Trump personally blocking people on Twitter?
Are there any intersection of Theory A and Theory B?
QGIS Welcome page: What is 'pin to list' for?
How do I take a fraction to a negative power?
Why did my rum cake turn black?
Why does the autopilot disengage even when it does not receive pilot input?
How can I deal with a player trying to insert real-world mythology into my homebrew setting?
How the name "craqueuhhe" is read
Is an acid a salt or not?
What's the point of this scene involving Flash Thompson at the airport?
How does Fury know about this in Spider-Man: Far From Home?
keras error:Error when checking target: expected dense_2 to have shape (2,) but got array with shape (1,)
Error when checking model target: expected dense_24 to have shape…but got array with shape… in KerasValueError: Error when checking target: expected dense_2 to have shape (None, 2) but got array with shape (1, 1)Error when checking target: expected dense_2 to have shape (None, 256) but got array with shape (16210, 4096)How does Keras read input data?Error when checking target: expected dense_2 to have shape (7,) but got array with shape (4,)ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (500,) [Sentiment Analysis]Resolving differences between Keras and scikit-learn for simple fully-connected neural networkIs it possible to train a CNN starting at an intermediate layer (in general and in Keras)?ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (14,)'Sequential' object has no attribute 'loss' - When I used GridSearchCV to tuning my Keras model
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have tried to write some example with keras,but some error happenError when checking target: expected dense_2 to have shape (2,) but got array with shape (1,)
I have tried to change the input_shape but it doesn't work
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import numpy
print "hello"
input=[[1],[2],[3],[4],[5],[6],[7],[8]]
input=numpy.array(input, dtype="float")
# input=input.reshape(8,1)
output=[[1],[0],[1],[0],[1],[0],[1],[0]]
output=numpy.array(output, dtype="float")
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
lb = LabelBinarizer()
trainy=lb.fit_transform(trainy)
testy=lb.transform(testy)
model=Sequential()
model.add(Dense(4,input_shape=(1,),activation="sigmoid"))
# model.add(Dense(4,activation="sigmoid"))
# print len(lb.classes_)
model.add(Dense(len(lb.classes_),activation="softmax",input_shape=(4,)))
INIT_LR = 0.01
EPOCHS = 20
print("[INFO] training network...")
opt = SGD(lr=INIT_LR)
model.compile(loss="categorical_crossentropy", optimizer=opt,metrics=["accuracy"])
H = model.fit(trainx, trainy, validation_data=(testx, testy),epochs=EPOCHS, batch_size=2)
python-2.7 keras
add a comment |
I have tried to write some example with keras,but some error happenError when checking target: expected dense_2 to have shape (2,) but got array with shape (1,)
I have tried to change the input_shape but it doesn't work
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import numpy
print "hello"
input=[[1],[2],[3],[4],[5],[6],[7],[8]]
input=numpy.array(input, dtype="float")
# input=input.reshape(8,1)
output=[[1],[0],[1],[0],[1],[0],[1],[0]]
output=numpy.array(output, dtype="float")
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
lb = LabelBinarizer()
trainy=lb.fit_transform(trainy)
testy=lb.transform(testy)
model=Sequential()
model.add(Dense(4,input_shape=(1,),activation="sigmoid"))
# model.add(Dense(4,activation="sigmoid"))
# print len(lb.classes_)
model.add(Dense(len(lb.classes_),activation="softmax",input_shape=(4,)))
INIT_LR = 0.01
EPOCHS = 20
print("[INFO] training network...")
opt = SGD(lr=INIT_LR)
model.compile(loss="categorical_crossentropy", optimizer=opt,metrics=["accuracy"])
H = model.fit(trainx, trainy, validation_data=(testx, testy),epochs=EPOCHS, batch_size=2)
python-2.7 keras
add a comment |
I have tried to write some example with keras,but some error happenError when checking target: expected dense_2 to have shape (2,) but got array with shape (1,)
I have tried to change the input_shape but it doesn't work
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import numpy
print "hello"
input=[[1],[2],[3],[4],[5],[6],[7],[8]]
input=numpy.array(input, dtype="float")
# input=input.reshape(8,1)
output=[[1],[0],[1],[0],[1],[0],[1],[0]]
output=numpy.array(output, dtype="float")
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
lb = LabelBinarizer()
trainy=lb.fit_transform(trainy)
testy=lb.transform(testy)
model=Sequential()
model.add(Dense(4,input_shape=(1,),activation="sigmoid"))
# model.add(Dense(4,activation="sigmoid"))
# print len(lb.classes_)
model.add(Dense(len(lb.classes_),activation="softmax",input_shape=(4,)))
INIT_LR = 0.01
EPOCHS = 20
print("[INFO] training network...")
opt = SGD(lr=INIT_LR)
model.compile(loss="categorical_crossentropy", optimizer=opt,metrics=["accuracy"])
H = model.fit(trainx, trainy, validation_data=(testx, testy),epochs=EPOCHS, batch_size=2)
python-2.7 keras
I have tried to write some example with keras,but some error happenError when checking target: expected dense_2 to have shape (2,) but got array with shape (1,)
I have tried to change the input_shape but it doesn't work
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import numpy
print "hello"
input=[[1],[2],[3],[4],[5],[6],[7],[8]]
input=numpy.array(input, dtype="float")
# input=input.reshape(8,1)
output=[[1],[0],[1],[0],[1],[0],[1],[0]]
output=numpy.array(output, dtype="float")
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
lb = LabelBinarizer()
trainy=lb.fit_transform(trainy)
testy=lb.transform(testy)
model=Sequential()
model.add(Dense(4,input_shape=(1,),activation="sigmoid"))
# model.add(Dense(4,activation="sigmoid"))
# print len(lb.classes_)
model.add(Dense(len(lb.classes_),activation="softmax",input_shape=(4,)))
INIT_LR = 0.01
EPOCHS = 20
print("[INFO] training network...")
opt = SGD(lr=INIT_LR)
model.compile(loss="categorical_crossentropy", optimizer=opt,metrics=["accuracy"])
H = model.fit(trainx, trainy, validation_data=(testx, testy),epochs=EPOCHS, batch_size=2)
python-2.7 keras
python-2.7 keras
asked Mar 26 at 4:00
samliusamliu
1
1
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Since you have two classes, you can have a single neuron in the final Dense layer and use sigmoid activation. Or if you want to use softmax, you need to create a one hot encoding of y like this.
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
trainy = keras.utils.to_categorical(trainy, 2)
testy = keras.utils.to_categorical(testy, 2)
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
add a comment |
You should use "from tensorflow.python.keras.xx" instead of "from keras.xx". It prevents it from receiving the error like: "AttributeError: module 'tensorflow' has no attribute 'get_default_graph"
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%2f55349650%2fkeras-errorerror-when-checking-target-expected-dense-2-to-have-shape-2-but%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Since you have two classes, you can have a single neuron in the final Dense layer and use sigmoid activation. Or if you want to use softmax, you need to create a one hot encoding of y like this.
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
trainy = keras.utils.to_categorical(trainy, 2)
testy = keras.utils.to_categorical(testy, 2)
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
add a comment |
Since you have two classes, you can have a single neuron in the final Dense layer and use sigmoid activation. Or if you want to use softmax, you need to create a one hot encoding of y like this.
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
trainy = keras.utils.to_categorical(trainy, 2)
testy = keras.utils.to_categorical(testy, 2)
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
add a comment |
Since you have two classes, you can have a single neuron in the final Dense layer and use sigmoid activation. Or if you want to use softmax, you need to create a one hot encoding of y like this.
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
trainy = keras.utils.to_categorical(trainy, 2)
testy = keras.utils.to_categorical(testy, 2)
Since you have two classes, you can have a single neuron in the final Dense layer and use sigmoid activation. Or if you want to use softmax, you need to create a one hot encoding of y like this.
(trainx,testx,trainy,testy)=train_test_split(input, output, test_size=0.25, random_state=42)
trainy = keras.utils.to_categorical(trainy, 2)
testy = keras.utils.to_categorical(testy, 2)
answered Mar 26 at 5:59
Manoj MohanManoj Mohan
2,3195 silver badges13 bronze badges
2,3195 silver badges13 bronze badges
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
add a comment |
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
It doesn't work.But I tried to use the np_utils.to_categorical to do a one-hot Encode.It works.But in another project I used LabelBinarizer to encode. So I feel very confued.
– samliu
Mar 26 at 10:28
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
From the documentation of Labelbinarizer, 'Shape will be [n_samples, 1] for binary problems.'. Hence you saw the shape error. In the other project, probably it was more than two classes.
– Manoj Mohan
Mar 26 at 10:59
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
keras.utils.to_categorical == keras.utils.np_utils.to_categorical. github.com/keras-team/keras/blob/master/keras/utils/__init__.py
– Manoj Mohan
Mar 26 at 11:02
add a comment |
You should use "from tensorflow.python.keras.xx" instead of "from keras.xx". It prevents it from receiving the error like: "AttributeError: module 'tensorflow' has no attribute 'get_default_graph"
add a comment |
You should use "from tensorflow.python.keras.xx" instead of "from keras.xx". It prevents it from receiving the error like: "AttributeError: module 'tensorflow' has no attribute 'get_default_graph"
add a comment |
You should use "from tensorflow.python.keras.xx" instead of "from keras.xx". It prevents it from receiving the error like: "AttributeError: module 'tensorflow' has no attribute 'get_default_graph"
You should use "from tensorflow.python.keras.xx" instead of "from keras.xx". It prevents it from receiving the error like: "AttributeError: module 'tensorflow' has no attribute 'get_default_graph"
answered Mar 26 at 4:40
Neda NavidiNeda Navidi
11 bronze badge
11 bronze badge
add a comment |
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%2f55349650%2fkeras-errorerror-when-checking-target-expected-dense-2-to-have-shape-2-but%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