深度学习:Demo1-MNIST

来源:互联网 发布:自动化行业用单片机吗 编辑:程序博客网 时间:2024/05/29 17:23
import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data#loading datamnist = input_data.read_data_sets("MNIST_data",one_hot=True)  #路径 / one hot vector#every batch size  batch_size = 100#calculate the sum of batchesn_batch = mnist.train.num_examples // batch_size#define placeholderx = tf.placeholder(tf.float32,[None,784])y = tf.placeholder(tf.float32,[None,10])     #拉伸成为一个数组#construct the neural network 没有隐藏层weight = tf.Variable(tf.zeros([784,10]))bias = tf.Variable(tf.zeros([10]))prediction = tf.nn.softmax(tf.matmul(x,weight)+bias)#define loss functionloss = tf.reduce_mean(tf.square(y-prediction))train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)#initializationinit = tf.global_variables_initializer()#布尔型列表中 放置 对比结果correct_predition = tf.equal(tf.arg_max(y,1),tf.arg_max(prediction,1)) #argmax 返回张量中最大的值所在的位置#accuracyaccuracy = tf.reduce_mean(tf.cast(correct_predition,tf.float32)) #格式转换 从 布尔 变成 floatwith tf.Session() as sess:    sess.run(init)    for e in range(21):        for batch in range(n_batch):            batch_xs,batch_ys = mnist.train.next_batch(batch_size)            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})        print("Iter"+str(e)+",Testing Accuracy"+str(acc))#可优化的地方:#批次 的 大小 #添加隐藏层 改变激活函数#权值与偏执址的初始化改变#loss函数改用交叉熵cross-entrpy#学习率改变#使用其他的优化方式#训练次数
原创粉丝点击