官方教程代码如下:

 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

最新文章

  1. POJ 2226二分图最大匹配
  2. SQL Server 数据库的维护(三)__事务(transaction)和锁
  3. ECharts-基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表
  4. Linux驱动开发——__stringify
  5. BZOJ 3110 【Zjoi2013】 K大数查询
  6. Mysql学习笔记(一)
  7. 【转载】C#之int与Java之Integer的区别
  8. POJ 2777 Count Color(线段树染色,二进制优化)
  9. git 第一次初始化
  10. 九度oj 1528 最长回文子串
  11. 【网络】TCP三次握手
  12. 闭包在python中的应用,translate和maketrans方法详解
  13. lib和dll的例子
  14. 致vi老大 2011.1
  15. Maven项目的目录结构
  16. 实时控制软件第一次作业--CNC软件系统分析
  17. 【转】iOS 开发者必不可少的 75 个工具
  18. php自动运行
  19. 【js】【图片显示】js控制html页面显示图片方式
  20. 作业二:构建swap函数

热门文章

  1. Codeforces Round #203 (Div. 2)B Resort
  2. Building roads
  3. 1.Nginx 简介
  4. Matrix 矩阵
  5. .Net Core2.0秒杀CMS部署到Centos7.3遇到的坑,酸爽呀
  6. express的学习,与使用
  7. linux下mysql启动出错
  8. javaScript函数提升及作用域
  9. .NET读取Excel文件的三种方法的区别
  10. [转载] 布隆过滤器(Bloom Filter)详解