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))

 

转载于:https://www.cnblogs.com/StevenSun1991/p/10134722.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值