使用tensorflow的softmax进行mnist识别

tensorflow真是方便,看来深度学习需要怎么使用框架、如何建模~

 1 '''
 2 softmax classifier for mnist  
 3 
 4 created on 2019.9.28
 5 author: vince
 6 '''
 7 import math
 8 import logging
 9 import numpy  
10 import random
11 import matplotlib.pyplot as plt
12 import tensorflow as tf
13 from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
14 from sklearn.metrics import accuracy_score
15 
16 def main(): 
17     logging.basicConfig(level = logging.INFO,
18             format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
19             datefmt = '%a, %d %b %Y %H:%M:%S');
20             
21     logging.info("trainning begin.");
22 
23     mnist = read_data_sets('../data/MNIST',one_hot=True)    # MNIST_data指的是存放数据的文件夹路径,one_hot=True 为采用one_hot的编码方式编码标签
24 
25     x = tf.placeholder(tf.float32, [None, 784]);
26     w = tf.Variable(tf.zeros([784, 10]));
27     b = tf.Variable(tf.zeros([10]));
28     y = tf.matmul(x, w) + b;
29 
30     y_ = tf.placeholder(tf.float32, [None, 10]);
31 
32     cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = y, labels = y_));
33     train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy);
34 
35     sess = tf.InteractiveSession();
36     tf.global_variables_initializer().run();
37     for _ in range(1000):
38         batch_xs, batch_ys = mnist.train.next_batch(100);
39         sess.run(train_step, feed_dict = {x : batch_xs, y_ : batch_ys});
40 
41     logging.info("trainning end.");
42     logging.info("testing begin.");
43 
44     correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1));
45     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32));
46     print(sess.run(accuracy, feed_dict = {x : mnist.test.images, y_:mnist.test.labels}));
47 
48     logging.info("testing end.");
49 
50 if __name__ == "__main__":
51     main();

猜你喜欢

转载自www.cnblogs.com/thsss/p/11695304.html