官方教程代码如下:

 import gzip
import os
import tempfile import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets mnist = read_data_sets("MNIST_data/", one_hot=True) x = tf.placeholder(tf.float32,[None, 784]) #图像输入向量
W = tf.Variable(tf.zeros([784,10])) #权重,初始化值为全零
b = tf.Variable(tf.zeros([10])) #偏置,初始化值为全零 #进行模型计算,y是预测,y_ 是实际
y = tf.nn.softmax(tf.matmul(x,W) + b) y_ = tf.placeholder("float", [None,10]) #计算交叉熵
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#接下来使用BP算法来进行微调,以0.01的学习速率
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #上面设置好了模型,添加初始化创建变量的操作
init = tf.global_variables_initializer()
#启动创建的模型,并初始化变量
sess = tf.Session()
sess.run(init)
#开始训练模型,循环训练1000次
for i in range(1000):
#随机抓取训练数据中的100个批处理数据点
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={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, "float"))
#计算所学习到的模型在测试数据集上面的正确率
print( sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels}) )

运行出现错误,不能导入数据,解决方案如下:

1..坑爹的GWF,严重阻碍人工智能的发展,与习大大十九大报告背道而驰,只能靠爱国青年曲线救国。方法为修改mnist.py文件(tensorflow.contrib.learn.python.learn.datasets.mnist),SOURCE_URL从 'https://storage.googleapis.com/cvdf-datasets/mnist/'改为 'http://yann.lecun.com/exdb/mnist/',如此就能运行了。

2.手动下载 http://yann.lecun.com/exdb/mnist/,处理代码如下,注意一定要把图片像素除以255,否则正确率只有0.098

 import tensorflow as tf
import struct
import numpy as np with open('train-labels.idx1-ubyte','rb') as lb:
magic,n=struct.unpack('>II',lb.read(8))
labels = np.fromfile(lb,dtype=np.uint8) with open('train-images.idx3-ubyte','rb') as img:
magic,num,rows,cols=struct.unpack('>IIII',img.read(16))
images = np.fromfile(img,dtype=np.uint8).reshape(-1,784)
images = images.astype(np.float32)
images = np.multiply(images, 1.0 / 255.0) with open('t10k-labels.idx1-ubyte','rb') as lb:
magic,n=struct.unpack('>II',lb.read(8))
testlabels = np.fromfile(lb,dtype=np.uint8) with open('t10k-images.idx3-ubyte','rb') as img:
magic,num,rows,cols=struct.unpack('>IIII',img.read(16))
testimages = np.fromfile(img,dtype=np.uint8).reshape(-1,784)
testimages = testimages.astype(np.float32)
testimages = np.multiply(testimages, 1.0 / 255.0) 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_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) sess = tf.InteractiveSession()
tf.global_variables_initializer().run() labels = sess.run(tf.one_hot(labels,10))
testlabels = sess.run(tf.one_hot(testlabels,10)) for _ in range(1000):
a=np.random.permutation(np.arange(60000))
bx = images[a[:100]]
by = labels[a[:100]]
sess.run(train_step,feed_dict={x:bx,y_:by}) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x:testimages, y_:testlabels}))

执行后结果约为0.92.

另外下列onehot方法非常好用:

def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = numpy.arange(num_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot

tensorflow MNIST新手教程的更多相关文章

  1. Tensorflow的CNN教程解析

    之前的博客我们已经对RNN模型有了个粗略的了解.作为一个时序性模型,RNN的强大不需要我在这里重复了.今天,让我们来看看除了RNN外另一个特殊的,同时也是广为人知的强大的神经网络模型,即CNN模型.今 ...

  2. TensorFlow MNIST(手写识别 softmax)实例运行

    TensorFlow MNIST(手写识别 softmax)实例运行 首先要有编译环境,并且已经正确的编译安装,关于环境配置参考:http://www.cnblogs.com/dyufei/p/802 ...

  3. Mac tensorflow mnist实例

    Mac tensorflow mnist实例 前期主要需要安装好tensorflow的环境,Mac 如果只涉及到CPU的版本,推荐使用pip3,傻瓜式安装,一行命令!代码使用python3. 在此附上 ...

  4. Tensorflow 官方版教程中文版

    2015年11月9日,Google发布人工智能系统TensorFlow并宣布开源,同日,极客学院组织在线TensorFlow中文文档翻译.一个月后,30章文档全部翻译校对完成,上线并提供电子书下载,该 ...

  5. Web项目的发布新手教程

    ASP.NET服务器发布新手教程 ——本文仅赠予第一次做Web项目,需要发布的新手们,转载的请注明出处. 首先我们说一下我们的需要的一个环境.我使用的是Visual Studio 2010,版本.NE ...

  6. APP设计尺寸规范大全,APP界面设计新手教程【官方版】(转)

    正值25学堂一周年之际,同时站长和APP设计同仁们在群里(APP界面设计 UI设计交流群,APP界面设计⑥群 APPUI设计③群58946771 APP设计资源⑤群 386032923欢迎大家加入交流 ...

  7. ROS探索总结(三)——ROS新手教程【转】

    转自:http://blog.csdn.net/hcx25909/article/details/8811313 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 一ROS的 ...

  8. 新手教程之使用Xib自定义UITableViewCell

    新手教程之使用Xib自定义UITableViewCell 前言 首先:什么是UITableView?看图 其次:什么是cell? 然后:为什么要自定cell,UITableView不是自带的有cell ...

  9. MATLAB新手教程

    MATLAB新手教程   .MATLAB的基本知识 1-1.基本运算与函数    在MATLAB下进行基本数学运算,仅仅需将运算式直接打入提示号(>>)之後,并按入Enter键就可以.比如 ...

随机推荐

  1. poj2689Prime Distance(大区间筛素数)

    Prime Distance Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 19635   Accepted: 5273 D ...

  2. HDU X mod f(x)(题解注释)

    X mod f(x) Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  3. 桌面消息通知:HTML5 Notification

    先上一段完整代码 //注册权限 Notification.requestPermission(function (status) { // 这将使我们能在 Chrome/Safari 中使用 Noti ...

  4. 蓝桥杯-算法训练--ALGO-4 结点选择

    本人是一个刚刚接触C++不久的傻学生~记录一些自己的学习过程.大神路过可以批评指正~ 刚学动态规划,水平还很渣,一下子不知道从何下手,借鉴了一下这位大哥的文章 http://www.cnblogs.c ...

  5. css3 滚动条出现 页面不跳动

    .wrap-outer { margin-left: calc(100vw - 100%); }   .wrap-outer { padding-left: calc(100vw - 100%); } ...

  6. Python的property装饰器的基本用法

    Python的@property装饰器用来把一个类的方法变成类的属性调用,然后@property本身又创建了另一个装饰器,用一个方法给属性赋值.下面是在类中使用了@property后,设置类的读写属性 ...

  7. linux操作系统基础篇(五)

    Linux网络以及rpm安装yum源的配置 1.Linux网络 1. 使用ifconfig命令来维护网络1) fconfig命令的功能:显示所有正在启动的网卡的详细信息或设定系统中网卡的IP地址.2) ...

  8. mysql全日志(general log)的命令名称

    在源码sql/sql_parse.cc中定义 const LEX_STRING command_name[]={ { C_STRING_WITH_LEN("Sleep") }, { ...

  9. JavaScript学习笔记(七)——函数的定义与调用

    在学习廖雪峰前辈的JavaScript教程中,遇到了一些需要注意的点,因此作为学习笔记列出来,提醒自己注意! 如果大家有需要,欢迎访问前辈的博客https://www.liaoxuefeng.com/ ...

  10. 去除HTML选择——兼容IE、FireFox(document.onselectstart,样式)

    引之:http://taoistwar.iteye.com/blog/278963 今天做一个拖动效果,在网上找了个模板,作发后发现一拖动就会选择其它页面部分,需要去除这个效果, 找了个模板看了下发现 ...