TensorFlow学习---入门(一)-----MNIST机器学习

参考教程:http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html

数据下载地址:http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_download.html

环境:windows+Python3.5+tensorflow

python代码

from tensorflow.examples.tutorials.mnist import input_data

#加载训练数据
MNIST_data_folder=r"D:\WorkSpace\tensorFlow\data"
mnist=input_data.read_data_sets(MNIST_data_folder,one_hot=True)
# print(mnist.train.next_batch(1))

import tensorflow as tf

# 建立抽象模型
x = tf.placeholder("float", [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("float", [None,10])

# 定义损失函数和训练方法
cross_entropy = -tf.reduce_sum(y_*tf.log(y))  # 损失函数为交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)    # 梯度下降法,学习速率为0.01 # 训练目标:最小化损失函数
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
  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}))

 

posted on 2017-09-26 23:27  沧海技术之家  阅读(274)  评论(0编辑  收藏  举报