来自keras的Model.train_on_batch与来自tensorflow的Session.run([train_optimizer])有什么区别?

时间:2018-11-20 15:19:09

标签: python tensorflow machine-learning keras

在下面的神经网络训练的Keras和Tensorflow实现中,keras实现中的model.train_on_batch([x], [y])与Tensorflow实现中的sess.run([train_optimizer, cross_entropy, accuracy_op], feed_dict=feed_dict)有何不同?特别是:这两条线如何导致训练中的不同计算?:

keras_version.py

input_x = Input(shape=input_shape, name="x")
c = Dense(num_classes, activation="softmax")(input_x)

model = Model([input_x], [c])
opt = Adam(lr)
model.compile(loss=['categorical_crossentropy'], optimizer=opt)

nb_batchs = int(len(x_train)/batch_size)

for epoch in range(epochs):
    loss = 0.0
    for batch in range(nb_batchs):
        x = x_train[batch*batch_size:(batch+1)*batch_size]
        y = y_train[batch*batch_size:(batch+1)*batch_size]

        loss_batch, acc_batch = model.train_on_batch([x], [y])

        loss += loss_batch
    print(epoch, loss / nb_batchs)

tensorflow_version.py

input_x = Input(shape=input_shape, name="x")
c = Dense(num_classes)(input_x)

input_y = tf.placeholder(tf.float32, shape=[None, num_classes], name="label")
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits_v2(labels=input_y, logits=c, name="xentropy"),
    name="xentropy_mean"
)
train_optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(cross_entropy)

nb_batchs = int(len(x_train)/batch_size)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(epochs):
        loss = 0.0
        acc = 0.0

        for batch in range(nb_batchs):
            x = x_train[batch*batch_size:(batch+1)*batch_size]
            y = y_train[batch*batch_size:(batch+1)*batch_size]

            feed_dict = {input_x: x,
                         input_y: y}
            _, loss_batch = sess.run([train_optimizer, cross_entropy], feed_dict=feed_dict)

            loss += loss_batch
        print(epoch, loss / nb_batchs)

注意:Same (?) model converges in Keras but not in Tensorflow后面是这个问题,该问题被认为过于笼统,但在其中我确切地说明了为什么我认为这两个语句有所不同并导致不同的计算。

1 个答案:

答案 0 :(得分:6)

是的,结果可能会有所不同。如果您事先了解以下内容,结果就不会令人惊讶:

  1. 在Tensorflow和Keras中corss-entropy的实现方式有所不同。 Tensorflow假定tf.nn.softmax_cross_entropy_with_logits_v2的输入为未标准化的原始logit,而Keras接受的输入为概率
  2. Keras和Tensorflow中optimizers的实现方式不同。
  3. 可能是因为您要对数据进行混排,而传递的批次顺序不同。尽管长时间运行模型并不重要,但最初的几个时期可能完全不同。确保将相同的批次传递给两个批次,然后比较结果。