需要先去下载MNIST数据
MNIST数据集的官网是Yann LeCun's website。在这里,我们提供了一份python源代码用于自动下载和安装这个数据集。你可以下载这份代码,然后用下面的代码导入到你的项目里面,也可以直接复制粘贴到你的代码文件里面。
import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
对应的文件以及需要下载的数据连接:https://download.csdn.net/download/qq_28767927/10638494
每一个MNIST数据单元有两部分组成:一张包含手写数字的图片和一个对应的标签。我们把这些图片设为“xs”,把这些标签设为“ys”。训练数据集和测试数据集都包含xs和ys,比如训练数据集的图片是 mnist.train.images
,训练数据集的标签是 mnist.train.labels
。
数学基础比较差,所以分析部分跳过,很多博客都有了,直接实现部分
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) sesses = tf.InteractiveSession() # x不是一个特定的值,而是一个占位符placeholder,我们在TensorFlow运行计算时输入这个值。 # 我们希望能够输入任意数量的MNIST图像,每一张图展平成784维的向量。 # 我们用2维的浮点数张量来表示这些图,这个张量的形状是[None,784 ]。 # (这里的None表示此张量的第一个维度可以是任何长度的。) x = tf.placeholder(tf.float32,[None,784]) # 我们赋予tf.Variable不同的初值来创建不同的Variable:在这里, # 我们都用全为零的张量来初始化W和b。因为我们要学习W和b的值,它们的初值可以随意设置。 w = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) # 用tf.matmul(X,W)表示x乘以W,这里x是一个2维张量拥有多个输入。然后再加上b,把和输入到tf.nn.softmax函数里面。 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(2000): batch_xs,batch_ys = mnist.train.next_batch(100) train_step.run(feed_dict={x:batch_xs,y_:batch_ys}) corrent_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(corrent_prediction,tf.float32)) print(accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels}))
好了,恶补统计先