mxnet icon indicating copy to clipboard operation
mxnet copied to clipboard

Trying to evaluate MXNet vs TensorFlow but failing to converge a model with same parameters

Open guygeva opened this issue 10 years ago • 5 comments

Hello, I am trying to evaluate MXNet vs Tensorflow. I Created a model with the same parameters for both frameworks for the mNist dataset. For some reason I am able to get an evaluation of 90% on the validation dataset when using TensorFlow, but I only get 10% when using MXNet. I believe that I might be missing something when using the MXNet api. Please help me understand what I am doing wrong.

This is the TensorFlow implementation:

batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
beta1 = 0.005
beta2 = 0.005
drop_rate=1.0

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(
    tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  layer1_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, num_channels, depth], stddev=0.1))
  layer1_biases = tf.Variable(tf.zeros([depth]))
  layer2_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, depth, depth], stddev=0.1))
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
  layer3_weights = tf.Variable(tf.truncated_normal(
      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
  layer4_weights = tf.Variable(tf.truncated_normal(
      [num_hidden, num_labels], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
  keep_prob = tf.placeholder(tf.float32)

  # Model.
  def model(data):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer1_biases)        
    maxpool = tf.nn.max_pool(hidden, [1, 3, 3, 1], [1, 2, 2, 1], padding='SAME')
    conv = tf.nn.conv2d(maxpool, layer2_weights, [1, 1, 1, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    maxpool = tf.nn.max_pool(hidden, [1, 3, 3, 1], [1, 2, 2, 1], padding='SAME')
    shape = maxpool.get_shape().as_list()
    reshape = tf.reshape(maxpool, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    model = tf.matmul(hidden, layer4_weights) + layer4_biases 
    return model

  # Training computation.
  logits = model(tf_train_dataset)
  logits = logits + beta1*tf.nn.l2_loss(layer3_weights) + beta2*tf.nn.l2_loss(layer4_weights)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))


  global_step = tf.Variable(0)  # count the number of steps taken.
  learning_rate = tf.train.exponential_decay(0.05, global_step, 900, 0.25)
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))

  num_steps = 1001

  with tf.Session(graph=graph) as session:
    tf.initialize_all_variables().run()
    print('Initialized')
    for step in range(num_steps):
      offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
      batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
      batch_labels = train_labels[offset:(offset + batch_size), :]
      feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob: drop_rate}
      _, l, predictions = session.run(
        [optimizer, loss, train_prediction], feed_dict=feed_dict)
      if (step % 50 == 0):
        print('Minibatch loss at step %d: %f' % (step, l))
        print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
        print('Validation accuracy: %.1f%%' % accuracy(
          valid_prediction.eval({keep_prob:1.0}), valid_labels))
    print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(feed_dict={keep_prob:1.0}),   test_labels))

This is the MXNet implementation:

import mxnet as mx
import mxnet.misc
import logging
kv = mx.kvstore.create('local')
head = '%(asctime)-15s Node[' + str(kv.rank) + '] %(message)s'
logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG, format=head)
logging.info('startingggg')
logger.setLevel(logging.DEBUG)
logger.info('startingggg')

batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
beta1 = 0.005
beta2 = 0.005
drop_rate=1.0
num_labels = 10

data = mx.symbol.Variable('data')
loc = mx.symbol.Convolution(data=data, kernel=(5,5), num_filter=depth, name="conv1")
loc = mx.symbol.Activation(data = loc, act_type='relu')
loc = mx.symbol.Pooling(data = loc, pool_type="max", kernel=(3,3),stride=(2,2))
loc = mx.symbol.Convolution(data=loc, kernel=(5,5), num_filter=depth, name="conv2")
loc = mx.symbol.Activation(data = loc, act_type='relu')
loc = mx.symbol.Pooling(data = loc, pool_type="max", kernel=(3,3),stride=(2,2))
loc = mx.symbol.Flatten(data=loc)
loc = mx.symbol.FullyConnected(data=loc, num_hidden=num_hidden)
loc = mx.symbol.Activation(data = loc, act_type='relu')
loc = mx.symbol.FullyConnected(data=loc, num_hidden=num_labels)
loc = mx.symbol.SoftmaxOutput(data=loc, name='softmax')
mxmodel = mx.model.FeedForward(symbol=loc, optimizer=mx.optimizer.SGD(wd=beta1,learning_rate=0.05), 
                     lr_scheduler=mx.misc.FactorScheduler(900,0.25), num_epoch=1)
train_dataset= np.reshape(train_dataset,(200000, 1, 28, 28))
valid_dataset=np.reshape(valid_dataset,(10000, 1, 28, 28))

train_iter = mx.io.NDArrayIter(train_dataset, train_labels, batch_size=batch_size, shuffle=True)
valid_iter = mx.io.NDArrayIter(valid_dataset, valid_labels, batch_size=batch_size)

batch_end_callback = []
batch_end_callback.append(mx.callback.Speedometer(batch_size, 50))

mxmodel.fit(train_iter,eval_data=valid_iter, batch_end_callback = batch_end_callback, eval_metric = ['accuracy'])

guygeva avatar Jul 31 '16 08:07 guygeva

maybe the parameters initialization is different between them. there is many reasons, such as, start learning rate, etc. or you code has problem. :laughing:

starimpact avatar Aug 02 '16 06:08 starimpact

I would recommend you to try your code with simple model (such as three fully connected layers), to test whether there's something wrong.

VoVAllen avatar Aug 09 '16 16:08 VoVAllen

I have used mxnet in many networks. there is no any problem.

starimpact avatar Aug 10 '16 01:08 starimpact

Do you have any update for this issues? I am interested on it.

kice avatar Apr 22 '17 22:04 kice

This issue is closed due to lack of activity in the last 90 days. Feel free to ping me to reopen if this is still an active issue. Thanks!

szha avatar Sep 29 '17 22:09 szha