尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
TensorFlow(2) 使用TF构建多层感知机预测MNIST数据集
import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data import matplotlib.pyplot as plt #读入数据---------------------------------------------------------------------- mnist input_data.read_data_sets(MNIST_data/,one_hotTrue)#label为one-hot-encoding #查看读入的数据格式------------------------------------------------------------- print(train,mnist.train.num_examples, ,validation,mnist.validation.num_examples, ,test,mnist.test.num_examples) print(train images:,mnist.train.images.shape, labels:,mnist.train.labels.shape) #查看label的值 mnist.train.labels[0] #函数将读入的数据图像显示 def plot_image(image): #上面读入的图像是一维的用reshape转成矩阵输出 plt.imshow(image.reshape(28,28),cmapbinary) plt.show() plot_image(mnist.train.images[0]) #函数输出10张图像带标签label和预测值prediction def plot_images_labels_prediction(images, labels, prediction, idx, num10): figplt.gcf() fig.set_size_inches(12,14) if num25: num25 for i in range(0, num): ax plt.subplot(5,5,1i) ax.imshow(np.reshape(images[idx],(28,28)),cmapbinary) title labelstr(np.argmax(labels[idx])) if len(prediction)0: title,predictionstr(prediction[idx]) ax.set_title(title, fontsize10) ax.set_xticks([]);ax.set_yticks([]) idx1 plt.show() plot_images_labels_prediction(mnist.validation.images, mnist.validation.labels,[],0) #构建MLP模型--------------------------------------------------------------------- #自定义layer def layer(output_dim, input_dim, inputs, activationNone): W tf.Variable(tf.random_normal([input_dim, output_dim])) b tf.Variable(tf.random_normal([1, output_dim])) WXb tf.matmul(inputs,W)b if activation is None: outputs WXb else: outputs activation(WXb) return outputs #两个隐藏层h1、h2一个输入x一个输出y_predict x tf.placeholder(float,[None, 784]) h1 layer(output_dim1000,input_dim784,inputsx,activationtf.nn.relu) h2 layer(output_dim1000,input_dim1000,inputsh1,activationtf.nn.relu) y_predict layer(output_dim10,input_dim1000,inputsh2,activationNone) #定义标签值 y_label tf.placeholder(float,[None,10]) #损失函数 loss_function tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logitsy_predict,labelsy_label)) #优化器使loss最小化学习率为0.001 optimizer tf.train.AdamOptimizer(learning_rate0.001).minimize(loss_function) #预测结果的正确性 correct_prediction tf.equal(tf.argmax(y_label,1),tf.argmax(y_predict,1)) #计算精度cast():转换值的类型,reduce_mean():计算平均值 accuracy tf.reduce_mean(tf.cast(correct_prediction,float)) #开始训练--------------------------------------------------------------------- trainEpochs 15 #epoch batchSize 100 totalBatchs int(len(mnist.train.images)/batchSize) #一个周期总的批次 loss_list[];epoch_list[];accuracy_list[] #记录训练过程的loss,epoch,accuracy from time import time startTime time() sess tf.Session() sess.run(tf.global_variables_initializer()) for epoch in range(trainEpochs): for i in range(totalBatchs): batch_x, batch_y mnist.train.next_batch(batchSize) #读取下一个批次的数据循环读取 sess.run(optimizer, feed_dict{x:batch_x,y_label:batch_y}) loss, acc sess.run([loss_function,accuracy],feed_dict\ {x:mnist.validation.images,y_label:mnist.validation.labels}) epoch_list.append(epoch) loss_list.append(loss) accuracy_list.append(acc) print(Train Epoch:, %02d%(epoch1), Loss,\ {:.9f}.format(loss), Accuary,acc) duration time()-startTime print(Train Finished takes:, duration) #训练结果显示-------------------------------------------------------------------- %matplotlib inline fig plt.gcf()#获取当前的figure图 fig.set_size_inches(4,2) plt.plot(epoch_list, loss_list, labelloss) plt.ylabel(loss) plt.xlabel(epoch) plt.legend([loss], locupper right) plt.plot(epoch_list,accuracy_list,labelaccuracy) fig plt.gcf() fig.set_size_inches(4,2) plt.ylim(0.8,1)#设置y轴范围 plt.ylabel(accuracy) plt.xlabel(epoch) plt.legend([accuarcy], locupper right) #评估------------------------------------------------------------------------------ #测试集test准确率 print(Accuracy:, sess.run(accuracy,feed_dict\ {x:mnist.test.images,y_label:mnist.test.labels})) #预测test prediction_result sess.run(tf.argmax(y_predict,1),feed_dict{x:mnist.test.images}) #显示真实值和预测值及图像 plot_images_labels_prediction(mnist.test.images,mnist.test.labels,prediction_result,0)
RELATED

相关推荐

3个维度重塑你的英雄联盟体验:League Akari如何成为你的智能游戏伙伴

3个维度重塑你的英雄联盟体验:League Akari如何成为你的智能游戏伙伴

3个维度重塑你的英雄联盟体验:League Akari如何成为你的智能游戏伙伴 【免费下载链接】League-Toolkit An all-in-one toolkit for LeagueClient. Gathering power 🚀. 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 当英雄联盟的…

📅 2026/11/8 14:55:07
中欧 PHP 开发者大会因多元化争议而取消

中欧 PHP 开发者大会因多元化争议而取消

没有女性的演讲者名单导致提倡多元化的男性演讲者退出会议,最终使得计划于德国举办的中欧 PHP 开发者大会宣布取消。 上周末,原定于 10 月 4 日至 6 日在德国德累斯顿举行的 PHP 会议 PHP Central Europe developer conference (PHP.CE) 因多元化争议宣布…

📅 2026/10/5 11:49:07
SpringBoot在线投稿系统开发与优化实践

SpringBoot在线投稿系统开发与优化实践

1. 项目概述 在线投稿系统是学术期刊、会议和内容平台的核心基础设施,它直接关系到内容生产的效率和质量管控。基于SpringBoot框架开发的投稿系统,能够为编辑部、审稿人和作者提供全流程的数字化解决方案。这个毕业设计项目采用Java技术栈实现&#xff0…

📅 2026/11/3 19:02:25
MORE NEWS

更多资讯

📰

在南京地方办理电工证到期换证流程

南京地方办理电工证真实经历:工地太忙根本没时间复习考试怎么办? 工地太忙根本没时间复习考试,这话说得实在,我身边不少电工兄弟都遇到过这个问题。前年我在河南一个小工地当技术员,亲眼看着一个老电工因为没时间复习,考试挂了两次,差点连项目都干不下…

📰

杭州特种工实操成绩怎么查?保姆级教程帮你搞定

杭州特种工实操成绩怎么查?保姆级教程帮你搞定 工地太忙根本没时间复习考试,很多人在拿到杭州特种工实操成绩后,不知道怎么查,或者查了之后不知道怎么处理。今天就从一个三门峡房建工程从业者的角度,手把手教你怎么查杭州特种工实操成绩,还有备考和报名…

📰

昆山千灯电工证怎么报名实操考试心里没底怕挂科?手把手教你搞定

昆山千灯电工证怎么报名实操考试心里没底怕挂科?手把手教你搞定 实操考试心里没底怕挂科?你不是一个人。尤其是昆山千灯电工证这种含金量高的证书,一旦挂科,不仅浪费时间和精力,还可能影响你的职业发展。很多人报考前最担心的就是: 怎么报名…

📰

电工证小邵老师直播间多久拿证?三门峡转岗电工必看干货

电工证小邵老师直播间多久拿证?三门峡转岗电工必看干货 你是不是正在为找工作发愁?手里没有电工证,连面试机会都没有。现在找工作门槛越来越高, 急需特种作业证才能上岗找工作…

📰

滨州哪里补办电工证内部消息:证书过期了不知道怎么复审延期?手把手教你搞定

滨州哪里补办电工证内部消息:证书过期了不知道怎么复审延期?手把手教你搞定 证书过期了不知道怎么复审延期?你不是一个人。很多人在特种作业行业干了多年,却因为疏忽或不了解流程,导致电工证过期,影响工作甚至被单位辞退。现在, 内部消息…

📰

初级电工证考操作吗网上查询全攻略:过期了怎么办别慌

初级电工证考操作吗网上查询全攻略:过期了怎么办别慌 证书过期了不知道怎么复审延期,别急,这篇文章能帮你搞定。如果你是平顶山的应届工程类毕业生,正打算考初级电工证,或者已经拿到了,但不知道是不是要考操作,更不知道怎么网上查询证书状态,那么你来…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬