M. Zayyan
M. Zayyan

Reputation: 13

Multiclassification in Python using keras error

I am new to python and try multiclassification on iris.csv dataset having 100 instances and 9 columns .I got this error and search this error and apply solution but nothing work for me.. please help

Traceback (most recent call last): File "iris.py", line 48, in model.fit(X, dummy_y, epochs=200, batch_size=5) File "C:\Users\HP\Anaconda2\lib\site-packages\keras\models.py", line 871, in fit initial_epoch=initial_epoch) File "C:\Users\HP\Anaconda2\lib\site-packages\keras\engine\training.py", line 1525, in fit batch_size=batch_size) File "C:\Users\HP\Anaconda2\lib\site-packages\keras\engine\training.py", line 1383, in _standardize_user_data exception_prefix='target') File "C:\Users\HP\Anaconda2\lib\site-packages\keras\engine\training.py", line 144, in _standardize_input_data str(array.shape)) ValueError: Error when checking target: expected dense_2 to have shape (None, 1) but got array with shape (100L, 3L)

here is my code

import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.cross_validation import cross_val_score, KFold
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load dataset
dataframe = pandas.read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:8].astype(float)
Y = dataset[:,8]
print(X)
print(Y)

#encode class values as integers
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)


# convert integers to dummy variables (hot encoded)
dummy_y = np_utils.to_categorical(encoded_Y)
print(dummy_y)


# create model
model = Sequential()
model.add(Dense(8, input_dim=8, activation='relu'))
model.add(Dense(3, activation='sigmoid'))


# Compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])


#model.fit
model.fit(X, dummy_y, epochs=200, batch_size=5)


#print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))

Upvotes: 1

Views: 251

Answers (1)

Matin H
Matin H

Reputation: 900

Solution 1: Change your loss function to categorical_crossentropy.

Solution 2: Use encoded_Y to train your model. sparse_categorical_crossentropy doesn't need hot encoded labels.

Upvotes: 2

Related Questions