Tensorflow Practice 3-2

Posted stevensun1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tensorflow Practice 3-2相关的知识,希望对你有一定的参考价值。

Tensorflow practice lesson 3-2

 1 import tensorflow as tf
 2 from tensorflow.examples.tutorials.mnist import input_data
 3 
 4 # 载入数据集
 5 mnist = input_data.read_data_sets("MNIST_data", one_hot=True, source_url=http://yann.lecun.com/exdb/mnist/)
 6 
 7 # 定义两个变量,表示每个批次的大小,在进行算法训练的过程中,将会加载一个批次的文件进行训练
 8 batch_size = 100
 9 # 计算批次的数量
10 n_batch = mnist.train.num_examples // batch_size
11 
12 # 定义两个placeholder
13 x = tf.placeholder(tf.float32, [None, 784])
14 y = tf.placeholder(tf.float32, [None, 10])
15 
16 # 创建一个简单的神经元网络
17 W = tf.Variable(tf.zeros([784, 10]))
18 b = tf.Variable(tf.zeros([10]))
19 prediction = tf.nn.softmax(tf.matmul(x, W) + b)
20 
21 # 二次代价函数
22 loss = tf.reduce_mean(tf.square(y - prediction))
23 # 使用梯度下降法最小化loss的值
24 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
25 
26 # 初始化变量
27 init = tf.global_variables_initializer()
28 
29 # 结果存放在一个布尔型的列表中
30 # arg_max 返回一维张量中最大值所在的位置
31 correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(prediction, 1))
32 
33 # 求准确率
34 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
35 
36 # 进行训练
37 with tf.Session() as sess:
38     sess.run(init)
39     for epoch in range(21):
40         for batch in range(n_batch):
41              batch_xs, batch_ys = mnist.train.next_batch(batch_size)
42              sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
43         acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
44         print("Iter " + str(epoch) + ", Test Accuracy " + str(acc))

 

以上是关于Tensorflow Practice 3-2的主要内容,如果未能解决你的问题,请参考以下文章

Tensorflow Practice 2-3

Tensorflow Practice 2-2

Tensorflow Practice 2-4

[ModuleNotFoundError尝试导入Tensorflow

优维低代码:Best Practice

Third practice 5