TensorFlow基础系列(逻辑回归)

开篇

接触TensorFlow也差不多一年多,因为论文的实验需要,中间间间断断的学习,东西或多或少会有所遗忘,所以着手开始写这一系列博客,希望能够坚持,磨炼技术,也为9月份的秋招打好扎实的基础。
那么这一系列博客能够让你学到什么呢,首先是tensorflow的基本操作,之后我们会用tensorflow实现一系列机器学习和深度学习的算法,深度学习优先,因为它毕竟是深度学习框架。本系列代码以代码为主,理论为辅,顺带博主的一些废话和一些实战中的小tips。欢迎大家批评指正,有问题也可以和我一起讨论研究。

因为之前博客一直在简书上连载,但是老实说简书不是码农的社区,看得人实在是太少了,所以我打算将这个系列放到CSDN上,首先放上我的开篇博客,下面是链接TensorFlow basic
Ok,废话不多说,下面开始我们的逻辑回归篇。

逻辑回归

老规矩,我们还是稍微讲一下逻辑回归是什么,逻辑回归首先也是个线性模型,它主要是为了解决二分类的问题,同时它也是神经网络的基础。它的模型函数也被称为sigmoid激活函数,在深度神经网络中常常被使用,LSTM中这种激活函数就扮演着重要的角色,我们后期也会渐渐看到它的作用。

首先我们要提的还是我们的三要素,模型函数,损失函数已经我们的优化算法,这三要素将贯穿我们全部的TensorFlow代码。

下面还是要放上我们的TensorFlow的运行机制:
TensorFlow运行机制

LR简介:我们还是放上它的模型图和数学表达形式,详细的理论解释不是我们的重点。

模型示例

公式

关于逻辑回归我在这边多提几句:
1、首先是一道腾讯的面试题,LR和SVM那个抗噪能力强一些?
LR对噪声是敏感的,这个特性和感知机是一样的,一点点噪声点就会干扰我们的模型,但是SVM泛化能力要强一些,它依靠支持向量来分类。
2、逻辑回归不是纯粹的判别模型,它来源于概率模型,从贝叶斯的角度是可以推导到我们的逻辑回归的函数模型的,具体见我的简书博客逻辑回归的由来,里面有详细地推导。
3、逻辑回归的损失函数是交叉熵,交叉熵可以判断两个分布之间的相似度(这也是一道大厂的面试题,我有点不记得是哪一家的了,大家可以去了解一下逻辑回归的损失函数,面试出境率很高,因为很基础)。

扯了这么多,下面让我们看一看逻辑回归在TensorFlow中是怎么实现的,如果您对以下代码有疑惑的话,请跳转到我开篇中提到的TensorFlow基础的博客。

import tensorflow as tf

x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]]

X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])

w = tf.Variable(tf.random_normal([2, 1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='basic')

#模型的定义部分(模型函数,损失函数,优化函数)
y = tf.sigmoid(tf.matmul(X, w) + b)
cost = -tf.reduce_mean(Y * tf.log(y) + (1-Y)*tf.log(1-y))
train=tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

#预测值和误差
pre = tf.cast(y > 0.5, dtype=tf.float32)
acc = tf.reduce_mean(tf.cast(tf.equal(pre, Y), dtype=tf.float32))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for step in range(2001):
        cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y: y_data})
        if step % 20 == 0:
            print(step, cost_val)

    h, c, a = sess.run([y, pre, acc], feed_dict={X: x_data, Y: y_data})
    print('\nmodel', h, '\npre', c, '\nacc', a)

Ok,下面让我们稍微解析一下代码,这次出现了一个我们之前没有见过的函数,那就是tf.cast(),代码中的这句表示将小于0.5的全部表示成0,大于0.5的全部表示成1. cast中文意思是映射,注意它的两个参数,第一个是原来的数据类型,第二个是我们映射之后的数据类型,我们这边原先的y>0.5是一个bool型,现在变成float型。

这里我再放一个大数据集的代码

'''
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_function

import 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)

# Parameters
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]))

# Construct model
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax

# Minimize error using 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)

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()

# Start training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for 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 loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))

    print("Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

OK,今天的TensorFlow系列就到这里,明天见!

猜你喜欢

转载自blog.csdn.net/ding_xiaofei/article/details/80082352