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. HBase 笔记3

    数据模型 Namespace 表命名空间: 多个表分到一个组进行统一的管理,需要用到表命名空间 表命名空间主要是对表分组,对不同组进行不同环境设定,如配额管理  安全管理 保留表空间: HBase中有 ...

  2. 退出unity运行

    public void GetExit()//退出运行 { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false;//用于退 ...

  3. caffe运行报错:datum channel>0(0:0)

    caffe在运行的时候报错:datum channel>0(0:0) 错误原因:数据通道错误,caffe不能识别 解决方案:不告诉你

  4. bootloader研究最后一关(中)

    2011-03-12 17:04:13 今天的目的是要把bin文件烧录到nandflash中. 其实我有一个问题一直没弄明白.S3C2440自带的RAM和ROM是多大?看了规格书说它能控制1G的8个b ...

  5. centos下载

    标题:   https://www.cnblogs.com/tony-brook/p/9849624.html DVD ISO:普通光盘完整安装版镜像,可离线安装到计算机硬盘上,包含大量的常用软件,一 ...

  6. bzoj2124: 等差子序列线段树+hash

    bzoj2124: 等差子序列线段树+hash 链接 https://www.lydsy.com/JudgeOnline/problem.php?id=2124 思路 找大于3的等差数列其实就是找等于 ...

  7. SPSS for Mac 安装教程

    Step1 下载安装文件 链接:https://pan.baidu.com/s/1M5Eh7ph3ys6mHRbAn_h_Wg 提取码:o0m7 Step2 解压安装 将下载好的压缩包解压,点击SPS ...

  8. Lintcode469-Same Tree-Easy

    469. Same Tree Check if two binary trees are identical. Identical means the two binary trees have th ...

  9. 【转载】Selenium WebDriver的简单操作说明

    转载自:http://blog.csdn.net/xiao190128/article/details/49784121 1.打开一个测试浏览器 对浏览器进行操作首先需要打开一个浏览器,接下来才能对浏 ...

  10. NYOJ 542 试制品(第五届河南省省赛)

    解法不唯一,但是还是set好理解而且用着爽,代码注释应该够详细了 #include<stdio.h> #include<string.h> #include<math.h ...