Tensorflow实现softmax regression识别手写数字

一.环境

python3.5.4 + window10 ,亲测正常运行

二.目的

阅读《Tensorflow实战》一书,运行机器学习领域的Hello world任务--MNIST手写数字识别来探索tensorflow,主要说一下数据的获取。之前按照官方文档上下载数据,总是报错,科学上网也不行。。。就很绝望,还好有github

(Tips:刚刚入坑人工智能,接触tensorflow,有错误请指出。)

三.流程

1.定义算法公式

2.定义loss,选定优化器,并指定优化器优化loss

3.迭代训练数据

4.测试数据,并对准确率进行评测


四.实战

1.数据下载

直接从github上下载数据(https://github.com/wlmnzf/tensorflow-train/tree/master/mnist/Mnist_data)


Tensorflow实现softmax regression识别手写数字_第1张图片

2.代码

# -*- coding:UTF-8 -*-

#路径为下载数据后的存放地址

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

print(mnist.train.images.shape, mnist.train.labels.shape)

print(mnist.test.images.shape, mnist.test.labels.shape)

print(mnist.validation.images.shape, mnist.validation.labels.shape)

import tensorflow as tf

sess = tf.InteractiveSession()

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

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

b = tf.Variable(tf.zeros([10]))

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

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

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

tf.global_variables_initializer().run()

for i in range(1000):

batch_xs, batch_ys = mnist.train.next_batch(100)

train_step.run({x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

3.结果


Tensorflow实现softmax regression识别手写数字_第2张图片

五.资源

中文版本:MNIST机器学习入门

http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html

github源码:

https://github.com/wlmnzf/tensorflow-train/tree/master/mnist

你可能感兴趣的:(Tensorflow实现softmax regression识别手写数字)