0

I am making a simple model which predicts sum of two values given in input. I have also flattened the array into shape (2,) but still the model is predicting two values. In predict function I am getting the shape of (4,2) instead of (4,1). why is this happening?

xs = np.array([[[[1.0],[2.0]]],[[[2.0],[6.0]]],[[[3.0], [4.0]]],[[[5.0], [6.0]]]],dtype=float)
    
ys = np.array([[3.0],[8.0],[7.0],[11.0]], dtype=float)
    
tf.random.set_seed(12)
    
model=tf.keras.Sequential([tf.keras.layers.Dense(1,tf.keras.layers.Flatten(input_shape=(2,)))])
    
model.compile(loss="mean_squared_error",optimizer=tf.keras.optimizers.Adam(learning_rate=0.1))

model.fit(xs,ys, epochs=500, verbose=False)
    
    
model.predict([[[[1.0],[2.0]]],[[[2.0],[6.0]]],[[[3.0],[4.0]]],[[[5.0],[6.0]]]])

The predictions are coming as follows:

array([[ 3.9273381,  5.193098 ],
       [ 5.193098 , 10.256137 ],
       [ 6.4588575,  7.724617 ],
       [ 8.990376 , 10.256137 ]], dtype=float32)

1 Answer 1

1

You should add the flatten layer before your dense layer, so something like this:

model=tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(2,)),
                           tf.keras.layers.Dense(1)])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the solution. In my previous code, I have put flatten function into dense layer. was my code actually flattening the array after calculating the weighted sum in that layer?
I'm actually not sure, lol. Some weird things happen when you pass layers as arguments into other layers I guess

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.