文章目录

  • 1.前言
  • 2.程序详细讲解
    • 环境设定
    • 数据读取
    • 准备好placeholder,开好容器来装数据
    • 准备好参数/权重
    • 拿到每个类别的score
    • 计算多分类softmax的loss function
    • 准备好optimizer
    • 在session里执行graph里定义的运算
  • 3.总代码
  • 4.输出结果
  • 5.可视化
    • Scalars
    • Graphs

1.前言

解决分类问题里最普遍的baseline model就是逻辑回归,简单同时可解释性好,使得它大受欢迎,我们来用tensorflow完成这个模型的搭建。
在这篇文章中我们使用的是MNIST手写数字识别图像的数据集。
模型搭建的步骤和代码如下:

2.程序详细讲解

环境设定

import numpy as np
import tensorflow as tf
from tensorflow.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

准备好placeholder,开好容器来装数据

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')#其实可以用下面这种方式,在不知道数据集大小的时候,传入的数据大小不固定,后面再根据实际情况来指定
# X = tf.placeholder(tf.float32, [None, 784], name='X_placeholder')
# Y = tf.placeholder(tf.int32, [None, 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")

拿到每个类别的score

logits = tf.matmul(X, w) + b

计算多分类softmax的loss function

# 求交叉熵损失
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y, name='loss')
# 求平均
loss = tf.reduce_mean(entropy)    #此处使用的是求平均值的方式

准备好optimizer

这里的最优化用的是随机梯度下降,我们可以选择AdamOptimizer这样的优化器。Adam.Optimiter()是一个带动量的梯度下降,不会很快陷到局部最低点,它会找到一个接近全局最优解的低点,但不保证会找到全局最优解.

learning_rate = 0.01
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)

在session里执行graph里定义的运算

#迭代总轮次
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!')

由于此数据集有测试集,不同于上面两篇文章中自己生成的数据,因此需要用测试集来测试模型的准确率

    # 测试模型,也需要放到session里面来运行。preds = tf.nn.softmax(logits)   #通过softmax()来计算每个样本类别的概率值correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))   #此处得出的是一个一阶张量,由一串0,1数字组成,表示的是每个样本是否预测预测准确accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))  #对预测是否准确的列表求平均值 ,cast()函数是将整型数据转化为浮点型数据   n_batches = int(mnist.test.num_examples/batch_size) #输入数据的批次total_correct_preds = 0#对测试集每个batch求accuracyfor 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]#对每个batch求平均值print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))writer.close()

3.总代码

# -*- coding: utf-8 -*-
'''
A logistic regression learning algorithm example using TensorFlow library.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''from __future__ import print_functionimport tensorflow as tf# Import MNIST data(下载数据)
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)# 参数:学习率,训练次数,
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))# softmax模型
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax# Minimize error using cross entropy(损失函数用cross entropy)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
# Gradient Descent(梯度下降优化)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)# Initializing the variables
init = tf.global_variables_initializer()# Launch the graph
with tf.Session() as sess:sess.run(init)# Training cyclefor epoch in range(training_epochs):avg_cost = 0.total_batch = int(mnist.train.num_examples/batch_size)# Loop over all batchesfor i in range(total_batch):batch_xs, batch_ys = mnist.train.next_batch(batch_size)# Run optimization op (backprop) and cost op (to get loss value)_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,y: batch_ys})# Compute average lossavg_cost += c / total_batch# Display logs per epoch stepif (epoch+1) % display_step == 0:print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))print("Optimization Finished!")# Test modelcorrect_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))# Calculate accuracyaccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

4.输出结果

5.可视化

使用tensorBoard方法 在这片文章中
https://blog.csdn.net/weixin_43838785/article/details/104433504

Scalars


2.00k次左右已经稳定

Graphs

Tensorflow【实战Google深度学习框架】—Logistic regression逻辑回归模型实例讲解相关推荐

  1. 免费教材丨第55期:Python机器学习实践指南、Tensorflow 实战Google深度学习框架

    小编说  时间过的好快啊,小伙伴们是不是都快进入寒假啦?但是学习可不要落下哦!  本期教材  本期为大家发放的教材为:<Python机器学习实践指南>.<Tensorflow 实战G ...

  2. 《Tensorflow 实战google深度学习框架》第二版源代码

    <<Tensorflow 实战google深度学习框架–第二版>> 完整资料github地址: https://github.com/caicloud/tensorflow-t ...

  3. 06.图像识别与卷积神经网络------《Tensorflow实战Google深度学习框架》笔记

    一.图像识别问题简介及经典数据集 图像识别问题希望借助计算机程序来处理.分析和理解图片中的内容,使得计算机可以从图片中自动识别各种不同模式的目标和对象.图像识别问题作为人工智能的一个重要领域,在最近几 ...

  4. 学习《TensorFlow实战Google深度学习框架 (第2版) 》中文PDF和代码

    TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用.<TensorFlow:实战Google深度学习框架(第2版)>为TensorFlow入门参考书,帮助快速. ...

  5. 说说TensorFlow实战Google深度学习框架

    说说TensorFlow实战Google深度学习框架 事情是这样的,博主买了这本书,但是碍于想在电脑上边看边码,想找找PDF版本,然后各种百度,Google,百度网盘,最后找到的都是很多200M的,百 ...

  6. (转)Tensorflow 实战Google深度学习框架 读书笔记

    本文大致脉络: 读书笔记的自我说明 对读书笔记的摘要 具体章节的摘要: 第一章 深度学习简介 第二章 TensorFlow环境搭建 第三章 TensorFlow入门 第四章 深层神经网络 第五章 MN ...

  7. TensorFlow实战Google深度学习框架

    TensorFlow是谷歌2015年开源的主流深度学习框架.科技届的聚光灯已经从"互联网+"转到了"AI+": 掌握深度学习需要较强的理论功底,用好Tensor ...

  8. TensorFlow实战Google深度学习框架5-7章学习笔记

    目录 第5章 MNIST数字识别问题 第6章 图像识别与卷积神经网络 第7章 图像数据处理 第5章 MNIST数字识别问题 MNIST是一个非常有名的手写体数字识别数据集,在很多资料中,这个数据集都会 ...

  9. tensorflow实战google深度学习框架在线阅读

    https://max.book118.com/html/2019/0317/7112141026002014.shtm

最新文章

  1. debian文本配置网络备忘:/etc/network/interfaces
  2. 从网络、编码、内容感知、存储、分发看视频云端到端技术实践
  3. cypress 的错误消息 - the element has become detached or removed from the dom
  4. 请画图说明tcp/ip协议栈_5年Android程序员面试字节跳动两轮后被完虐,请查收给你的面试指南 - Android木子李老师...
  5. 2017软件工程实践总结
  6. mysql 命令行 主从复制_MySQL 的主从复制(高级篇)
  7. 2019年网络规划设计师下午真题及答案解析
  8. 简述php和web交互过程,PHP与Web页面交互操作实例分析
  9. DeFi衍生品协议dFuture未来5日将通过公测奖励100万枚DFT
  10. 为什么越普通的男人越自信?
  11. ssh相关命令Linux,Linux SSH常用命令 [长期更新]...
  12. 如何使用WindowsPerformanceToolKit对程序进行分析
  13. 各厂家服务器存储默认登录信息
  14. SQL 基础教程 (第2版)
  15. Ubuntu20.04更换阿里源教程
  16. Qt之调用笔记本摄像头录像功能
  17. 用Python批量修改图片名称及后缀名
  18. 初识Java ~ (二) # Java 中程序的执行流程,(万字长文)特别细~ 可收藏~
  19. 常用HTML转义字符
  20. ad被锁定的账户_如何在AD中方便查询被锁定的帐号状态和特定条件的查询被锁定的帐号...

热门文章

  1. ninja Compiling the C compiler identification source file CMakeCCompilerId.c failed
  2. python判断是否有属性
  3. 高达82 fps的实时文本检测,可微分二值化模块
  4. ssd手 和方向检测
  5. c1xx: fatal error C1356: 无法找到 mspdbcore.dll
  6. Windows下编译tensorflow-gpu教程
  7. Haar Adaboost 视频车辆检测代码和样本
  8. android ndk常见的问题及解决的方法
  9. 微娱推客——青龙羊毛
  10. 76.Zabbix添加图形和聚合图形