实验7-使用TensorFlow完成MNIST手写体识别

news/2024/9/21 22:44:13

VMware虚拟机 Ubuntu20-LTS

python3.6

tensorflow1.15.0

keras2.3.1

运行截图:

 

 

代码:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'import numpy as np
import tensorflow as tf
from tensorflow_core.examples.tutorials.mnist import input_data
import time
#%%
#使用tensorflow自带的工具加载MNIST手写数字集合
mnist = input_data.read_data_sets('./data/mnist', one_hot=True) 
#查看一下数据维度
mnist.train.images.shape
#查看target维度
mnist.train.labels.shape
batch_size = 128
X = tf.placeholder(tf.float32, [batch_size, 784], name='X_placeholder') 
Y = tf.placeholder(tf.int32, [batch_size, 10], name='Y_placeholder')
#%%
w = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name='weights')
b = tf.Variable(tf.zeros([1, 10]), name="bias")
#%%
logits = tf.matmul(X, w) + b 
#%%
# 求交叉熵损失
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y, name='loss')
# 求平均
loss = tf.reduce_mean(entropy)
learning_rate = 0.01
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)
#%%
#迭代总轮次
n_epochs = 30with tf.Session() as sess:# 在Tensorboard里可以看到图的结构writer = tf.summary.FileWriter('./graphs/logistic_reg', sess.graph)start_time = time.time()sess.run(tf.global_variables_initializer())    n_batches = int(mnist.train.num_examples/batch_size)for i in range(n_epochs): # 迭代这么多轮total_loss = 0for _ in range(n_batches):X_batch, Y_batch = mnist.train.next_batch(batch_size)_, loss_batch = sess.run([optimizer, loss], feed_dict={X: X_batch, Y:Y_batch}) total_loss += loss_batchprint('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))print('Total time: {0} seconds'.format(time.time() - start_time))print('Optimization Finished!')# 测试模型preds = tf.nn.softmax(logits)correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))n_batches = int(mnist.test.num_examples/batch_size)total_correct_preds = 0for i in range(n_batches):X_batch, Y_batch = mnist.test.next_batch(batch_size)accuracy_batch = sess.run([accuracy], feed_dict={X: X_batch, Y:Y_batch}) total_correct_preds += accuracy_batch[0]print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))writer.close()

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/31587.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

C121 李超树+DP P4655 [CEOI2017] Building Bridges

视频链接:C121 李超树+DP P4655 [CEOI2017] Building Bridges_哔哩哔哩_bilibili Luogu P4655 [CEOI2017] Building Bridges#include <iostream> #include <cstring> #include <algorithm> using namespace std;#define ll long long #define ls u<&l…

实验1-波士顿房价预测

VMware虚拟机 Ubuntu20-LTS python3.6 tensorflow1.15.0 keras2.3.1 运行截图 代码:from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, LogisticRegression from sklearn.datasets import load_boston from sklearn.model_selection import train_tes…

穿越

题目描述解析 纯搜索,注意不能用 \(dfs\) !!!每次四个方向以及所有传送门,判断 \(rain\) 最早下的时间,判雨;对于兽,如果醒了,等它着再走过去,需要判脚下兽,脚下雨,下一个点的雨。code #include<bits/stdc++.h> #define se second #define fi first using na…

windows下volumetric video conference环境搭建

最近在做volumetric video的rtc,在此记录下相关内容方便之后复习。所采用的end to end平台来自于mmsys24的 Scalable MDC-Based Volumetric Video Delivery for Real-Time One-to-Many WebRTC Conferencing. 源码地址:https://github.com/MatthiasDeFre/webrtc-pc-streaming …

mysql+node.js前后端交互(简单实现注册登录功能)

目录 sql文件 user.js 注册部分 登录部分 对应的表操作 usersql.jsresult.js 用户提交的信息会进行格式化

Linux错误:-bash: Su: command not found

问题:使用 su 命令出错:-bash: Su: command not found解决: 先查看/etc/sudoers.d 文件是否存在find /etc/sudoers.d说明系统已经安装了 sudo,只不过没有配置环境。解决一:使用vi 或 vim 以下命令打开/etc/sudoers文件。vim /etc/sudoers esc --> :wq 保存退出。

【django学习-23】分页功能

前言:当列表界面数据量大的时候,我们一般就要用到分页功能。 下面是已经封装好的组件,使用方法1.分页组件""" 自定义的分页组件,以后如果想要使用这个分页组件,你需要做如下几件事:在视图函数中:def pretty_list(request):# 1.根据自己的情况去筛选自己的…

常见的排序算法——归并排序(三)

本文记述了归并排序的 3 项改进和一份参考实现代码,并在说明了算法的性能后用随机数据进行了验证。 ◆ 思想 本文实现了《算法(第4版)》书中提到的 3 项改进,对小规模子数组使用插入排序。减少在小规模数组中的递归调用能改进整个算法。 测试数组是否已经有序。任意有序的子…