本文实例为大家分享了tensorflow神经网络实现mnist分类的具体代码,供大家参考,具体内容如下
创新互联是一家专业提供通化县企业网站建设,专注与成都做网站、成都网站建设、H5建站、小程序制作等业务。10年已为通化县众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。只有两层的神经网络,直接上代码
#引入包 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #引入input_data文件 from tensorflow.examples.tutorials.mnist import input_data #读取文件 mnist = input_data.read_data_sets('F:/mnist/data/',one_hot=True) #定义第一个隐藏层和第二个隐藏层,输入层输出层 n_hidden_1 = 256 n_hidden_2 = 128 n_input = 784 n_classes = 10 #由于不知道输入图片个数,所以用placeholder x = tf.placeholder("float",[None,n_input]) y = tf.placeholder("float",[None,n_classes]) stddev = 0.1 #定义权重 weights = { 'w1':tf.Variable(tf.random_normal([n_input,n_hidden_1],stddev = stddev)), 'w2':tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2],stddev=stddev)), 'out':tf.Variable(tf.random_normal([n_hidden_2,n_classes],stddev=stddev)) } #定义偏置 biases = { 'b1':tf.Variable(tf.random_normal([n_hidden_1])), 'b2':tf.Variable(tf.random_normal([n_hidden_2])), 'out':tf.Variable(tf.random_normal([n_classes])), } print("Network is Ready") #前向传播 def multilayer_perceptrin(_X,_weights,_biases): layer1 = tf.nn.sigmoid(tf.add(tf.matmul(_X,_weights['w1']),_biases['b1'])) layer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1,_weights['w2']),_biases['b2'])) return (tf.matmul(layer2,_weights['out'])+_biases['out']) #定义优化函数,精准度等 pred = multilayer_perceptrin(x,weights,biases) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred,labels=y)) optm = tf.train.GradientDescentOptimizer(learning_rate = 0.001).minimize(cost) corr = tf.equal(tf.argmax(pred,1),tf.argmax(y,1)) accr = tf.reduce_mean(tf.cast(corr,"float")) print("Functions is ready") #定义超参数 training_epochs = 80 batch_size = 200 display_step = 4 #会话开始 init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) #优化 for epoch in range(training_epochs): avg_cost=0. total_batch = int(mnist.train.num_examples/batch_size) for i in range(total_batch): batch_xs,batch_ys = mnist.train.next_batch(batch_size) feeds = {x:batch_xs,y:batch_ys} sess.run(optm,feed_dict = feeds) avg_cost += sess.run(cost,feed_dict=feeds) avg_cost = avg_cost/total_batch if (epoch+1) % display_step ==0: print("Epoch:%03d/%03d cost:%.9f"%(epoch,training_epochs,avg_cost)) feeds = {x:batch_xs,y:batch_ys} train_acc = sess.run(accr,feed_dict = feeds) print("Train accuracy:%.3f"%(train_acc)) feeds = {x:mnist.test.images,y:mnist.test.labels} test_acc = sess.run(accr,feed_dict = feeds) print("Test accuracy:%.3f"%(test_acc)) print("Optimization Finished")
分享文章:tensorflow使用神经网络实现mnist分类-创新互联
链接地址:https://www.cdcxhl.com/article6/ccgsig.html
成都网站建设公司_创新互联,为您提供企业建站、电子商务、网站内链、关键词优化、网站制作、标签优化
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联