Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras input shape error

I'm new to Keras and I am trying to create my network which needs to learn on a card game. It takes 93 binary inputs with a hidden layer with 40 neurons and a single output neuron which computes a score (from 0 to 25).

model = Sequential()
model.add(Dense(input_dim=93, units=40, activation="sigmoid"))
model.add(Dense(units=2, activation="linear"))
sgd = optimizers.SGD(lr=0.01, clipvalue=0.5)
model.compile(loss="mse", optimizer=sgd, learning_rate=0.01)

I'm trying first to compute (do a forward propagation) of the 93 inputs

this is "s.toInputs()"

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 0 1 1 0 0 1 0 0 0 0 1 1 0 1]

model.predict(np.array(s.toInputs())

but i get the error

ValueError: Error when checking : expected dense_1_input to have shape (None, 93) but got array with shape (93, 1)

How do I pass the correct parameters?

like image 566
Ggs Avatar asked May 16 '17 14:05

Ggs


2 Answers

Actually s.toInputs() should look like this

[[0,0,0, etc...],[0,1,0, etc...]]

Basically you have to have an array with the following shape: (n_batches, n_attributes)

You have 93 attributes so this should do the trick if you are using tensorflow

np.array(s.toInputs()).reshape(-1, 93)

Fully working example

model = Sequential()
model.add(Dense(input_dim=93, units=40, activation="sigmoid"))
model.add(Dense(units=2, activation="linear"))
sgd = optimizers.SGD(lr=0.01, clipvalue=0.5)
model.compile(loss="mse", optimizer=sgd, learning_rate=0.01)

# random data
n_batches = 10
data = np.random.randint(0,2,93*n_batches)
data = data.reshape(-1,93)

model.predict(data)
like image 91
Wilmar van Ommeren Avatar answered Oct 11 '22 05:10

Wilmar van Ommeren


The error message tells you, that your data needs to have the shape (None, 93) (Nonehere means, this dimension can have an arbitrary value. It is the number of your samples)

But your input data has the shape (93,1). Note that the dimensions are reversed. You can use transpose to get your data in the right shape:

model.predict(np.array(s.toInputs()).T)
like image 22
sietschie Avatar answered Oct 11 '22 03:10

sietschie