ramy  2017-12-04 08:11:32  机器学习 |   查看评论   

   这个是基于原生tensorflow的一版代码,好长而且看着比较麻烦一点,还load了caffe里面生成的网络模型,比较麻烦

  1.  # 输入数据
  2.  import input_data
  3.  mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

  4.  import tensorflow as tf

  5.  # 定义网络超参数
  6.  learning_rate = 0.001
  7.  training_iters = 200000
  8.  batch_size = 64
  9.  display_step = 20

  10.  # 定义网络参数
  11.  n_input = 784 # 输入的维度
  12.  n_classes = 10 # 标签的维度
  13.  dropout = 0.8 # Dropout 的概率

  14.  # 占位符输入
  15.  x = tf.placeholder(tf.types.float32, [None, n_input])
  16.  y = tf.placeholder(tf.types.float32, [None, n_classes])
  17.  keep_prob = tf.placeholder(tf.types.float32)

  18.  # 卷积操作
  19.  def conv2d(name, l_input, w, b):
  20.      return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, 1, 1, 1], padding='SAME'),b), name=name)

  21.  # 最大下采样操作
  22.  def max_pool(name, l_input, k):
  23.      return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME', name=name)

  24.  # 归一化操作
  25.  def norm(name, l_input, lsize=4):
  26.      return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)

  27.  # 定义整个网络 
  28.  def alex_net(_X, _weights, _biases, _dropout):
  29.      # 向量转为矩阵
  30.      _X = tf.reshape(_X, shape=[-1, 28, 28, 1])

  31.      # 卷积层
  32.      conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])
  33.      # 下采样层
  34.      pool1 = max_pool('pool1', conv1, k=2)
  35.      # 归一化层
  36.      norm1 = norm('norm1', pool1, lsize=4)
  37.      # Dropout
  38.      norm1 = tf.nn.dropout(norm1, _dropout)

  39.      # 卷积
  40.      conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])
  41.      # 下采样
  42.      pool2 = max_pool('pool2', conv2, k=2)
  43.      # 归一化
  44.      norm2 = norm('norm2', pool2, lsize=4)
  45.      # Dropout
  46.      norm2 = tf.nn.dropout(norm2, _dropout)

  47.      # 卷积
  48.      conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'])
  49.      # 下采样
  50.      pool3 = max_pool('pool3', conv3, k=2)
  51.      # 归一化
  52.      norm3 = norm('norm3', pool3, lsize=4)
  53.      # Dropout
  54.      norm3 = tf.nn.dropout(norm3, _dropout)

  55.      # 全连接层,先把特征图转为向量
  56.      dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]]) 
  57.      dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1') 
  58.      # 全连接层
  59.      dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') # Relu activation

  60.      # 网络输出层
  61.      out = tf.matmul(dense2, _weights['out']) + _biases['out']
  62.      return out

  63.  # 存储所有的网络参数
  64.  weights = {
  65.      'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
  66.      'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
  67.      'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
  68.      'wd1': tf.Variable(tf.random_normal([4\*4\*256, 1024])),
  69.      'wd2': tf.Variable(tf.random_normal([1024, 1024])),
  70.      'out': tf.Variable(tf.random_normal([1024, 10]))
  71.  }
  72.  biases = {
  73.      'bc1': tf.Variable(tf.random_normal([64])),
  74.      'bc2': tf.Variable(tf.random_normal([128])),
  75.      'bc3': tf.Variable(tf.random_normal([256])),
  76.      'bd1': tf.Variable(tf.random_normal([1024])),
  77.      'bd2': tf.Variable(tf.random_normal([1024])),
  78.      'out': tf.Variable(tf.random_normal([n_classes]))
  79.  }

  80.  # 构建模型
  81.  pred = alex_net(x, weights, biases, keep_prob)

  82.  # 定义损失函数和学习步骤
  83.  cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  84.  optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

  85.  # 测试网络
  86.  correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  87.  accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

  88.  # 初始化所有的共享变量
  89.  init = tf.initialize_all_variables()

  90.  # 开启一个训练
  91.  with tf.Session() as sess:
  92.      sess.run(init)
  93.      step = 1
  94.      # Keep training until reach max iterations
  95.      while step \* batch_size < training_iters:
  96.          batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  97.          # 获取批数据
  98.          sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
  99.          if step % display_step == 0:
  100.              # 计算精度
  101.              acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
  102.              # 计算损失值
  103.              loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
  104.              print "Iter " + str(step\*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
  105.          step += 1
  106.      print "Optimization Finished!"
  107.      # 计算测试精度
  108.      print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.})

  基于mnist 构建alexnet,这里的input可以去tensorflow的github上去找找,这一版代码比较简单。

  
 

除特别注明外,本站所有文章均为 人工智能学习网 原创,转载请注明出处来自机器学习进阶笔记之三 | 深入理解Alexnet

留言与评论(共有 0 条评论)
   
验证码: