Udacity深度学习-深度神经网络-assignment3

六层深度神经网络+SGD+L2正则项+dropout,TensorFlow实现
#NN with SGD, L2
batch_size = 128
layer_cnt = 6#层数
graph = tf.Graph()

with graph.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  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.
  weights = []
  biases = []
  hidden_cur_cnt = 784
  for i in range(layer_cnt - 2):
     if hidden_cur_cnt > 2:
         hidden_next_cnt = int(hidden_cur_cnt / 2)
     else:
         hidden_next_cnt = 2
     hidden_stddev = np.sqrt(2.0 / hidden_cur_cnt)
     weights.append(tf.Variable(tf.truncated_normal([hidden_cur_cnt, hidden_next_cnt], stddev=hidden_stddev)))
     biases.append(tf.Variable(tf.zeros([hidden_next_cnt])))
     hidden_cur_cnt = hidden_next_cnt
  weights.append(tf.Variable(tf.truncated_normal([hidden_cur_cnt, num_labels], stddev=hidden_stddev)))
  biases.append(tf.Variable(tf.zeros([num_labels])))
  
  # Training computation.
  hidden_drop = tf_train_dataset
  keep_prob = 0.5
  for i in range(layer_cnt - 2):
     y1 = tf.matmul(hidden_drop, weights[i]) + biases[i]
     hidden_drop = tf.nn.relu(y1)
     keep_prob += 0.5 * i / (layer_cnt + 1)
     hidden_drop = tf.nn.dropout(hidden_drop, keep_prob)
  
  z3 = tf.matmul(hidden_drop, weights[-1]) + biases[-1]
  l2_loss = tf.Variable(0.0)
  for wi in weights:
        l2_loss += tf.nn.l2_loss(wi)
  loss = tf.reduce_mean(
    tf.add(
        tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=z3),0.001 *  l2_loss) )
  
  # Optimizer.
  global_step = tf.Variable(0)  # count the number of steps taken.
  learning_rate = tf.train.exponential_decay(0.5, global_step, 1000, 0.9)
  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(z3)
  def predict(dataset):
      hidden_drop = dataset
      for i in range(layer_cnt - 2):
         y1 = tf.matmul(hidden_drop, weights[i]) + biases[i]
         hidden_drop = tf.nn.relu(y1)  
      result = tf.matmul(hidden_drop, weights[-1]) + biases[-1]
      
      return result
  
  valid_prediction = tf.nn.softmax(predict(tf_valid_dataset))
  
  test_prediction = tf.nn.softmax(predict(tf_test_dataset))

运行代码:

num_steps = 20001

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 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(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值