【Tensorflow】Mnist初步实践

 1. 首先下载MNIST (这里采用离线下载再读取的方法。在线安装由于SSL权限的问题,可以参考

http://www.tensorfly.cn/tfdoc/tutorials/mnist_download.html )

2.读入MNIST

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

MNIST_dir = 'C:\\Users\\HAPPY\\Desktop\\mnist'  #MNIST文件夹目录
mnist = input_data.read_data_sets(MNIST_dir, one_hot=True)

3.训练代码(此处训练10000次,设置学习率为0.03,最后调出的识别准确率为89%左右)

# coding:utf-8
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
MNIST_dir = 'C:\\Users\\HAPPY\\Desktop\\mnist'

mnist = input_data.read_data_sets(MNIST_dir, one_hot=True)

x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])

w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, w) + b)

loss = -tf.reduce_mean(y_ * tf.log(y))
train_steps = tf.train.GradientDescentOptimizer(0.03).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for i in range(10000):
        batch_x, batch_y = mnist.train.next_batch(100)
        sess.run(train_steps, {x: batch_x, y_: batch_y})
        if i % 1000 == 0:
            print("now steps: %d" % int(i))
    correct_prediction = tf.equal(tf.arg_max(y, 1), tf.argmax(y_, 1)) #测试最后的准确率
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print(sess.run(accuracy, {x: mnist.test.images, y_: mnist.test.labels}))

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值