首页 > 其他分享 >实验7-使用TensorFlow完成MNIST手写体识别

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

时间:2024-05-14 21:52:12浏览次数:21  
标签:loss preds batch tf mnist time 手写体 TensorFlow MNIST

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 = 30

with 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 = 0

        for _ 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_batch
        print('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 = 0
    
    for 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()

 

标签:loss,preds,batch,tf,mnist,time,手写体,TensorFlow,MNIST
From: https://www.cnblogs.com/liucaizhi/p/18192341

相关文章

  • SciTech-BigDataAIML-TensorFlow-Model: 模型建立与训练
    TensorFlow模型建立与训练TensorFlow模型建立与训练本章介绍如何使用TensorFlow快速搭建动态模型。模型的构建:tf.keras.Model和tf.keras.layers模型的损失函数:tf.keras.losses模型的优化器:tf.keras.optimizer模型的评估:tf.keras.metrics前置知识Python-{zh-......
  • SciTech-BigDataAIML-TensorFlow-Model的编译:设置(LossFunction+Optimizer+Metrics)与
    机器学习|model.compile()用法model.compile()的作用:为经过设计的Model(神经网络模型)设置好:loss损失函数、optimizer优化器、metrics准确性评价函数。并且进行编译;Optimizers优化器:Optimizer的主要功能是作用在GD(梯度下降)的过程,使得Gradient(梯度)更快(快速......
  • 机器学习包keras skiti-learn tensorflow pytorh yolov6 tensorboad seaborn numpy p
    这些是一些常用的Python库和框架,它们在机器学习、深度学习、数据科学和可视化等领域中被广泛使用。下面是每个库的简要介绍以及一个应用示例:Keras:Keras是一个高级神经网络API,可以运行在TensorFlow、MicrosoftCognitiveToolkit(CNTK)或Theano之上。它提供了简单而灵活......
  • SciTech-BigDataAIML-Tensorflow-Keras API-Layers的API
    https://keras.io/api/layers/KeraslayersAPILayersarethebasicbuildingblocksofneuralnetworksinKeras.Alayerconsistsofatensor-intensor-outcomputationfunction(thelayer'scallmethod)andsomestate,heldinTensorFlowvariables(th......
  • SciTech-BigDataAIML-Tensorflow-Keras是用在Tensorflow的高层API
    [https://tensorflow.google.cn/guide/keras](Keras:Thehigh-levelAPIforTensorFlow)https://tensorflow.google.cn/guide/kerasThecoredatastructuresofKerasarelayersandmodels.Alayerisasimpleinput/outputtransformation,andamodelisadirec......
  • Tensorflow object detection API (ubuntu18.04) 安装和踩坑;
    踩坑:将slim和models路径加入虚拟环境中;将slim和models路径加入系统路径中;(加入系统路径的时候,这个pwd) qit(持续更新)具体安装流程:(很多问题)2.0版本;(继续更新)condacreate-ntf_obj_det_api_v2python=3.8 (很丝滑)重新尝试tf1.0版本;参考:https://blog.csdn......
  • 张量计算框架的学习 pytorch和tensorflow
    要实现一些模型或者算法,可以直接用pytorch库或者tensorflow库,但是也可以再深入一些也就是对库本身进行一些扩展。找到两篇文章觉得不错:知乎上分享的万字综述,核心开发者全面解读PyTorch内部机制https://zhuanlan.zhihu.com/p/67834038探索TensorFlow的运行原理:TensorFlow是如......
  • Python-与-TensorFlow2-生成式-AI(五)
    Python与TensorFlow2生成式AI(五)原文:zh.annas-archive.org/md5/d06d282ea0d9c23c57f0ce31225acf76译者:飞龙协议:CCBY-NC-SA4.0第十二章:用生成式人工智能玩视频游戏:GAIL在之前的章节中,我们已经看到如何使用生成式人工智能来生成简单的(受限玻尔兹曼机器)和复杂的(变分自动......
  • 实验14-1使用cnn完成MNIST手写体识别(tf)+实验14-2使用cnn完成MNIST手写体识别(keras)
    版本python3.7tensorflow版本为tensorflow-gpu版本2.6实验14-1使用cnn完成MNIST手写体识别(tf)运行结果: 代码:importtensorflowastf#Tensorflow提供了一个类来处理MNIST数据fromtensorflow.examples.tutorials.mnistimportinput_dataimporttime#载入数据集mn......
  • 安装TensorFlow时timeout
    运行pip3install--upgradetensorflow时一直会报错 我看了看,报错落在timeout上 解决方法(用下面这句,用的清华镜像)pip3install--default-timeout=100tensorflow-ihttps://pypi.tuna.tsinghua.edu.cn/simple 参考——https://blog.csdn.net/weixin_43938599/artic......