楼主: ReneeBK
1844 17

【Tutorial】Deep MNIST for Experts [推广有奖]

  • 1关注
  • 62粉丝

VIP

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49497 个
通用积分
53.4454
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57815 点
帖子
4006
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
  1. Deep MNIST for Experts

  2. TensorFlow is a powerful library for doing large-scale numerical computation. One of the tasks at which it excels is implementing and training deep neural networks. In this tutorial we will learn the basic building blocks of a TensorFlow model while constructing a deep convolutional MNIST classifier.

  3. This introduction assumes familiarity with neural networks and the MNIST dataset. If you don't have a background with them, check out the introduction for beginners. Be sure to install TensorFlow before starting.

  4. About this tutorial

  5. The first part of this tutorial explains what is happening in the mnist_softmax.py code, which is a basic implementation of a Tensorflow model. The second part shows some ways to improve the accuracy.

  6. You can copy and paste each code snippet from this tutorial into a Python environment, or you can choose to just read through the code.

  7. What we will accomplish in this tutorial:

  8. Create a softmax regression function that is a model for recognizing MNIST digits, based on looking at every pixel in the image
  9. Use Tensorflow to train the model to recognize digits by having it "look" at thousands of examples (and run our first Tensorflow session to do so)
  10. Check the model's accuracy with our test data
  11. Build, train, and test a multilayer convolutional neural network to improve the results
复制代码

https://www.tensorflow.org/get_started/mnist/pros
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Tutorial experts Expert tutor Tori background building training library learn

沙发
ReneeBK 发表于 2017-2-19 01:19:08 |只看作者 |坛友微信交流群
  1. Load MNIST Data

  2. If you are copying and pasting in the code from this tutorial, start here with these two lines of code which will download and read in the data automatically:

  3. from tensorflow.examples.tutorials.mnist import input_data
  4. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
复制代码

使用道具

藤椅
ReneeBK 发表于 2017-2-19 01:19:31 |只看作者 |坛友微信交流群
  1. Start TensorFlow InteractiveSession

  2. TensorFlow relies on a highly efficient C++ backend to do its computation. The connection to this backend is called a session. The common usage for TensorFlow programs is to first create a graph and then launch it in a session.

  3. Here we instead use the convenient InteractiveSession class, which makes TensorFlow more flexible about how you structure your code. It allows you to interleave operations which build a computation graph with ones that run the graph. This is particularly convenient when working in interactive contexts like IPython. If you are not using an InteractiveSession, then you should build the entire computation graph before starting a session and launching the graph.

  4. import tensorflow as tf
  5. sess = tf.InteractiveSession()
复制代码

使用道具

板凳
ReneeBK 发表于 2017-2-19 01:21:58 |只看作者 |坛友微信交流群
  1. Placeholders

  2. We start building the computation graph by creating nodes for the input images and target output classes.

  3. x = tf.placeholder(tf.float32, shape=[None, 784])
  4. y_ = tf.placeholder(tf.float32, shape=[None, 10])
  5. Here x and y_ aren't specific values. Rather, they are each a placeholder -- a value that we'll input when we ask TensorFlow to run a computation.

  6. The input images x will consist of a 2d tensor of floating point numbers. Here we assign it a shape of [None, 784], where 784 is the dimensionality of a single flattened 28 by 28 pixel MNIST image, and None indicates that the first dimension, corresponding to the batch size, can be of any size. The target output classes y_ will also consist of a 2d tensor, where each row is a one-hot 10-dimensional vector indicating which digit class (zero through nine) the corresponding MNIST image belongs to.

  7. The shape argument to placeholder is optional, but it allows TensorFlow to automatically catch bugs stemming from inconsistent tensor shapes.
复制代码

使用道具

报纸
ReneeBK 发表于 2017-2-19 01:29:02 |只看作者 |坛友微信交流群
  1. Variables

  2. We now define the weights W and biases b for our model. We could imagine treating these like additional inputs, but TensorFlow has an even better way to handle them: Variable. A Variable is a value that lives in TensorFlow's computation graph. It can be used and even modified by the computation. In machine learning applications, one generally has the model parameters be Variables.

  3. W = tf.Variable(tf.zeros([784,10]))
  4. b = tf.Variable(tf.zeros([10]))
  5. We pass the initial value for each parameter in the call to tf.Variable. In this case, we initialize both W and b as tensors full of zeros. W is a 784x10 matrix (because we have 784 input features and 10 outputs) and b is a 10-dimensional vector (because we have 10 classes).

  6. Before Variables can be used within a session, they must be initialized using that session. This step takes the initial values (in this case tensors full of zeros) that have already been specified, and assigns them to each Variable. This can be done for all Variables at once:

  7. sess.run(tf.global_variables_initializer())
复制代码

使用道具

地板
ReneeBK 发表于 2017-2-19 01:30:07 |只看作者 |坛友微信交流群
  1. Predicted Class and Loss Function

  2. We can now implement our regression model. It only takes one line! We multiply the vectorized input images x by the weight matrix W, add the bias b.

  3. y = tf.matmul(x,W) + b
  4. We can specify a loss function just as easily. Loss indicates how bad the model's prediction was on a single example; we try to minimize that while training across all the examples. Here, our loss function is the cross-entropy between the target and the softmax activation function applied to the model's prediction. As in the beginners tutorial, we use the stable formulation:

  5. cross_entropy = tf.reduce_mean(
  6.     tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
  7. Note that tf.nn.softmax_cross_entropy_with_logits internally applies the softmax on the model's unnormalized model prediction and sums across all classes, and tf.reduce_mean takes the average over these sums.
复制代码

使用道具

7
ReneeBK 发表于 2017-2-19 01:31:04 |只看作者 |坛友微信交流群
  1. Train the Model

  2. Now that we have defined our model and training loss function, it is straightforward to train using TensorFlow. Because TensorFlow knows the entire computation graph, it can use automatic differentiation to find the gradients of the loss with respect to each of the variables. TensorFlow has a variety of built-in optimization algorithms. For this example, we will use steepest gradient descent, with a step length of 0.5, to descend the cross entropy.

  3. train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  4. What TensorFlow actually did in that single line was to add new operations to the computation graph. These operations included ones to compute gradients, compute parameter update steps, and apply update steps to the parameters.

  5. The returned operation train_step, when run, will apply the gradient descent updates to the parameters. Training the model can therefore be accomplished by repeatedly running train_step.

  6. for _ in range(1000):
  7.   batch = mnist.train.next_batch(100)
  8.   train_step.run(feed_dict={x: batch[0], y_: batch[1]})
  9. We load 100 training examples in each training iteration. We then run the train_step operation, using feed_dict to replace the placeholder tensors x and y_ with the training examples. Note that you can replace any tensor in your computation graph using feed_dict -- it's not restricted to just placeholders.
复制代码

使用道具

8
ReneeBK 发表于 2017-2-19 01:35:28 |只看作者 |坛友微信交流群
  1. Evaluate the Model

  2. How well did our model do?

  3. First we'll figure out where we predicted the correct label. tf.argmax is an extremely useful function which gives you the index of the highest entry in a tensor along some axis. For example, tf.argmax(y,1) is the label our model thinks is most likely for each input, while tf.argmax(y_,1) is the true label. We can use tf.equal to check if our prediction matches the truth.

  4. correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
  5. That gives us a list of booleans. To determine what fraction are correct, we cast to floating point numbers and then take the mean. For example, [True, False, True, True] would become [1,0,1,1] which would become 0.75.

  6. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  7. Finally, we can evaluate our accuracy on the test data. This should be about 92% correct.

  8. print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
复制代码

使用道具

9
ReneeBK 发表于 2017-2-19 01:36:21 |只看作者 |坛友微信交流群
  1. Weight Initialization

  2. To create this model, we're going to need to create a lot of weights and biases. One should generally initialize weights with a small amount of noise for symmetry breaking, and to prevent 0 gradients. Since we're using ReLU neurons, it is also good practice to initialize them with a slightly positive initial bias to avoid "dead neurons". Instead of doing this repeatedly while we build the model, let's create two handy functions to do it for us.

  3. def weight_variable(shape):
  4.   initial = tf.truncated_normal(shape, stddev=0.1)
  5.   return tf.Variable(initial)

  6. def bias_variable(shape):
  7.   initial = tf.constant(0.1, shape=shape)
  8.   return tf.Variable(initial)
复制代码

使用道具

10
ReneeBK 发表于 2017-2-19 01:36:59 |只看作者 |坛友微信交流群
  1. Convolution and Pooling

  2. TensorFlow also gives us a lot of flexibility in convolution and pooling operations. How do we handle the boundaries? What is our stride size? In this example, we're always going to choose the vanilla version. Our convolutions uses a stride of one and are zero padded so that the output is the same size as the input. Our pooling is plain old max pooling over 2x2 blocks. To keep our code cleaner, let's also abstract those operations into functions.

  3. def conv2d(x, W):
  4.   return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

  5. def max_pool_2x2(x):
  6.   return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
  7.                         strides=[1, 2, 2, 1], padding='SAME')
复制代码

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-10-6 22:34