MNIST softmax——tensorflow初学

花了一上午终于搞定了anaconda,tensorflow,使用spyder IDE写机器学习代码

tensorflow入门 MNIST手写数字识别。模仿着教程的代码写,也算小有收获。

以下代码:

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 14:12:45 2018

@author: czx
"""

# create a softmax regression 

import tensorflow as tf 
from tensorflow.examples.tutorials.mnist import input_data 

#读入数据,由于使用"MNIST_data/"需要,在这里建议先将MNIST数据包下载下来。
#MNIST下载地址http://yann.lecun.com/exdb/mnist/
#将四个文件下载下来放在一个文件夹中即可
mnist = input_data.read_data_sets("E:\桌面上的文件\MNIST", one_hot=True) 

#使用占位符,读入数据组数可变
x = tf.placeholder(tf.float32,[None, 784]) 
W = tf.Variable(tf.zeros([784, 10])) 
b = tf.Variable(tf.zeros([10])) 

#softmax回归,y = x*W+b
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) 

#通过tensorflow进行运算
init = tf.global_variables_initializer() 
sess = tf.Session() 
sess.run(init) 

#循环1w次
for i in range(10000): 
    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, tf.float32)) 

#输出精确度
print(sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels}))

 

你可能感兴趣的:(机器学习)