Main question: I define the same model in two different ways. Why do I get different results? They seem to be the same model.
Secondary question (answered below) If I run the code again, I get different results again. I have set the seed at the beginning to fix the randomness. Why is that happening?
import numpy as np
np.random.seed(1)
from keras.models import Model, Sequential
from keras.layers import Input, Dense
model1= Sequential([
Dense(20, activation='sigmoid',kernel_initializer='glorot_normal',
input_shape=(2,)),
Dense(2, activation='linear', kernel_initializer='glorot_normal'),
])
model1.compile(optimizer='adam', loss='mean_squared_error')
ipt = Input(shape=(2,))
x = Dense(20, activation='sigmoid', kernel_initializer='glorot_normal')(ipt)
out = Dense(2, activation='linear', kernel_initializer='glorot_normal')(x)
model2 = Model(ipt, out)
model2.compile(optimizer='adam', loss='mean_squared_error')
x_train=np.array([[1,2],[3,4],[3,4]])
model1.fit(x_train, x_train,epochs=2, validation_split=0.1, shuffle=False)
model2.fit(x_train, x_train,epochs=2, validation_split=0.1, shuffle=False)
The first time, the output is:
2/2 [==============================] - 0s 68ms/step - loss: 14.4394 - val_loss: 21.5747
Epoch 2/2
2/2 [==============================] - 0s 502us/step - loss: 14.3199 - val_loss: 21.4163
Train on 2 samples, validate on 1 samples
Epoch 1/2
2/2 [==============================] - 0s 72ms/step - loss: 11.0523 - val_loss: 17.7059
Epoch 2/2
2/2 [==============================] - 0s 491us/step - loss: 10.9833 - val_loss: 17.5785
The second time, the output is:
2/2 [==============================] - 0s 80ms/step - loss: 14.4394 - val_loss: 21.5747
Epoch 2/2
2/2 [==============================] - 0s 501us/step - loss: 14.3199 - val_loss: 21.4163
Train on 2 samples, validate on 1 samples
Epoch 1/2
2/2 [==============================] - 0s 72ms/step - loss: 11.0523 - val_loss: 17.6733
Epoch 2/2
2/2 [==============================] - 0s 485us/step - loss: 10.9597 - val_loss: 17.5459
Update after reading the answer: By the answer below, one of my questions has been answered. I changed the beginning of my code to:
import numpy as np
np.random.seed(1)
import random
random.seed(2)
import tensorflow as tf
tf.set_random_seed(3)
And, now I am getting the same numbers as before. So, it is stable. But, my main question has remained unanswered. Why at each time, the two equivalent models give different results?
Here is the result I get every time:
results 1:
Epoch 1/2
2/2 [==============================] - 0s 66ms/sample - loss: 11.9794 - val_loss: 18.9925
Epoch 2/2
2/2 [==============================] - 0s 268us/sample - loss: 11.8813 - val_loss: 18.8572
results 2:
Epoch 1/2
2/2 [==============================] - 0s 67ms/sample - loss: 5.4743 - val_loss: 9.3471
Epoch 2/2
2/2 [==============================] - 0s 3ms/sample - loss: 5.4108 - val_loss: 9.2497