tensorFlow 基础见前博客

逻辑回归广泛应用在各类分类,回归任务中。本实验介绍逻辑回归在 TensorFlow 上的实现

理论知识回顾

逻辑回归的主要公式罗列如下:

激活函数(activation function):

损失函数(cost function):

其中

损失函数求偏导(derivative cost function):

训练模型

  • 数据准备
    首先我们需要先下载MNIST的数据集。使用以下的命令进行下载:
    wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/t10k-images-idx3-ubyte.gz
    wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/t10k-labels-idx1-ubyte.gz
    wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/train-images-idx3-ubyte.gz
    wget https://devlab-1251520893.cos.ap-guangzhou.myqcloud.com/train-labels-idx1-ubyte.gz

创建代码

#-*- coding:utf-8 -*-
import time
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data MNIST = input_data.read_data_sets("./", one_hot=True) learning_rate = 0.01
batch_size = 128
n_epochs = 25 X = tf.placeholder(tf.float32, [batch_size, 784])
Y = tf.placeholder(tf.float32, [batch_size, 10]) 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(labels=Y, logits=logits)
loss = tf.reduce_mean(entropy) optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess:
sess.run(init)
n_batches = int(MNIST.train.num_examples/batch_size)
for i in range(n_epochs):
for j in range(n_batches):
X_batch, Y_batch = MNIST.train.next_batch(batch_size)
_, loss_ = sess.run([optimizer, loss], feed_dict={ X: X_batch, Y: Y_batch})
print "Loss of epochs[{0}] batch[{1}]: {2}".format(i, j, loss_)

执行结果

Loss of epochs[0] batch[0]: 2.28968191147
Loss of epochs[0] batch[1]: 2.30224704742
Loss of epochs[0] batch[2]: 2.26435565948
Loss of epochs[0] batch[3]: 2.26956915855
Loss of epochs[0] batch[4]: 2.25983452797
Loss of epochs[0] batch[5]: 2.2572259903
......
Loss of epochs[24] batch[420]: 0.393310219049
Loss of epochs[24] batch[421]: 0.309725940228
Loss of epochs[24] batch[422]: 0.378903746605
Loss of epochs[24] batch[423]: 0.472946226597
Loss of epochs[24] batch[424]: 0.259472459555
Loss of epochs[24] batch[425]: 0.290799200535
Loss of epochs[24] batch[426]: 0.256865829229
Loss of epochs[24] batch[427]: 0.250789999962
Loss of epochs[24] batch[428]: 0.328135550022

测试模型

#-*- coding:utf-8 -*-
import time
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data MNIST = input_data.read_data_sets("./", one_hot=True) learning_rate = 0.01
batch_size = 128
n_epochs = 25 X = tf.placeholder(tf.float32, [batch_size, 784])
Y = tf.placeholder(tf.float32, [batch_size, 10]) 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(labels=Y, logits=logits)
loss = tf.reduce_mean(entropy) optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess:
sess.run(init) n_batches = int(MNIST.train.num_examples/batch_size)
for i in range(n_epochs):
for j in range(n_batches):
X_batch, Y_batch = MNIST.train.next_batch(batch_size)
_, loss_ = sess.run([optimizer, loss], feed_dict={ X: X_batch, Y: Y_batch})
print "Loss of epochs[{0}] batch[{1}]: {2}".format(i, j, loss_) 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)
preds = tf.nn.softmax(tf.matmul(X_batch, w) + b)
correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))
accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32)) total_correct_preds += sess.run(accuracy) print "Accuracy {0}".format(total_correct_preds/MNIST.test.num_examples)

执行结果

Accuracy 0.9108

tensorFlow(三)逻辑回归的更多相关文章

  1. 机器学习 (三) 逻辑回归 Logistic Regression

    文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人 ...

  2. 利用Tensorflow实现逻辑回归模型

    官方mnist代码: #下载Mnist数据集 import tensorflow.examples.tutorials.mnist.input_data mnist = input_data.read ...

  3. tensorflow之逻辑回归模型实现

    前面一篇介绍了用tensorflow实现线性回归模型预测sklearn内置的波士顿房价,现在这一篇就记一下用逻辑回归分类sklearn提供的乳腺癌数据集,该数据集有569个样本,每个样本有30维,为二 ...

  4. tensorflow 实现逻辑回归——原以为TensorFlow不擅长做线性回归或者逻辑回归,原来是这么简单哇!

    实现的是预测 低 出生 体重 的 概率.尼克·麦克卢尔(Nick McClure). TensorFlow机器学习实战指南 (智能系统与技术丛书) (Kindle 位置 1060-1061). Kin ...

  5. 深度学习原理与框架-Tensorflow基本操作-mnist数据集的逻辑回归 1.tf.matmul(点乘操作) 2.tf.equal(对应位置是否相等) 3.tf.cast(将布尔类型转换为数值类型) 4.tf.argmax(返回最大值的索引) 5.tf.nn.softmax(计算softmax概率值) 6.tf.train.GradientDescentOptimizer(损失值梯度下降器)

    1. tf.matmul(X, w) # 进行点乘操作 参数说明:X,w都表示输入的数据, 2.tf.equal(x, y) # 比较两个数据对应位置的数是否相等,返回值为True,或者False 参 ...

  6. Stanford大学机器学习公开课(三):局部加权回归、最小二乘的概率解释、逻辑回归、感知器算法

    (一)局部加权回归 通常情况下的线性拟合不能很好地预测所有的值,因为它容易导致欠拟合(under fitting).如下图的左图.而多项式拟合能拟合所有数据,但是在预测新样本的时候又会变得很糟糕,因为 ...

  7. 10分钟搞懂Tensorflow 逻辑回归实现手写识别

    1. Tensorflow 逻辑回归实现手写识别 1.1. 逻辑回归原理 1.1.1. 逻辑回归 1.1.2. 损失函数 1.2. 实例:手写识别系统 1.1. 逻辑回归原理 1.1.1. 逻辑回归 ...

  8. 逻辑回归,附tensorflow实现

    本文旨在通过二元分类问题.多元分类问题介绍逻辑回归算法,并实现一个简单的数字分类程序 在生活中,我们经常会碰到这样的问题: 根据苹果表皮颜色判断是青苹果还是红苹果 根据体温判断是否发烧 这种答案只有两 ...

  9. 利用TensorFlow实现多元逻辑回归

    利用TensorFlow实现多元逻辑回归,代码如下: import tensorflow as tf import numpy as np from sklearn.linear_model impo ...

随机推荐

  1. haier周的计算原则

    现使用oracle的sql表示出haier周, 经过对其生成结果的分析,发现海尔周是以周日到周六分别作为一周的始末, 用到的oracle sql中会涉及到calendar week的定义,还涉及到了I ...

  2. 利用tcp三次握手,使用awl伪装MAC地址进行多线程SYN洪水攻击

    SYN洪水攻击概述:SYN洪水攻击主要源于: tcp协议的三次握手机制tcp协议面向链接的协议SYN洪水攻击的过程:在服务端返回一个确认的SYN-ACK包的时候有个潜在的弊端,如果发起的客户是一个不存 ...

  3. Django简单实例

    一.前戏-MVC框架与MTV框架 1.MVC MVC(Model View Controller),是一种软件工程开发的架构模式,不仅适用于软件开发,而且适用于其他广泛的设计和组织工作,主要思想通过分 ...

  4. scanperiod 不生效

    注意:要改 target 目录下的,真正运行时加载的 logback-spring.xml

  5. python locust 性能测试:locust参数-保证并发测试数据唯一性,循环取数据

    from locust import TaskSet, task, HttpLocustimport queue class UserBehavior(TaskSet): @task def test ...

  6. Linux基础命令---lp打印文件

    lp lp指令用来打印文件,也可以修改存在的打印任务.使用该指令可以指定打印的页码.副本等. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.openSUSE.SU ...

  7. Future 示例

    public static Object send(RequestClient request) future.channel().writeAndFlush(JSONObject.toJSONStr ...

  8. 隐藏非选中的checkBox

    //隐藏非选中的checkBox function onlyCheckBox(){ $("#dtlTable tr:gt(0)").each(function(i) { var c ...

  9. Linux命令(一)

    一:命令介绍,目录结构,基本格式 linux命令格式:   command [-options] [parameter1] ...    带-就是选项,不带-就是参数 ls ---文件显示    ls ...

  10. FutureBuilder的使用以及防止FutureBuilder不必要重绘的两种方法

    https://blog.csdn.net/u011272795/article/details/83010974 https://segmentfault.com/a/119000001421934 ...