机器学习实战--chapter 5 Logistic Regression(1)

1 大话Logistic Regression(LR)

首先谈线性拟合,线性拟合就是类似我们高中物理课实验,测得一些数据点,画在二维坐标图中,然后采用最小二乘法拟合一个曲线,逼近这些点。最小二乘法,顾名思义,就是曲线预测的点与实际测得的点的差值平方求和,然后让该和达到最小,从而得到该曲线的系数,即得到了模型。

逻辑斯回归在吴恩达老师讲义中描述如下:

For the logistic regression classifier we’ll take our features and multiply each one by a weight and then add them up. This result will be put into the sigmoid, and we’ll get a number between 0 and 1. Anything above 0.5 we’ll classify as a 1, and anything below 0.5 we’ll classify as a 0. You can also think of logistic regression as a probability estimate.

怎么理解呢?就是包含了回归和离散化。回归得到值是连续数值型的,然后结合sigmoid的函数就可以将大范围的值映射到[0, 1]之间。然后选取一个分界点作为判决。


2 函数模型

1.sigmoid函数

σ(z)=11+ez

code

import matplotlib
import matplotlib.pyplot as plt
from numpy import *

matplotlib.use('TkAgg')

x = arange(-10, 10, 0.1)
y = 1 / (1 + exp(-x))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
plt.xlabel('x'); plt.ylabel('Sigmoid')
plt.show()

Run
sigmoid

2.z线性的模型如下

z=w0x0+w1x1+w2x2+w3x3+...+wnxn


3 模型系数

梯度上升求最大值,梯度下降求最小值,一般凸函数的局部最优就是全局最优。

1.梯度上升

w:=w+αwf(w)

2.梯度下降

w:=wαwf(w)


4 代码

from numpy import *

#加载数据集,返回特征列表+tag列表
def loadDataSet():
    dataMat = []; labelMat = []
    fr = open('testSet.txt')
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
        labelMat.append(int(lineArr[2]))
    return dataMat,labelMat

#sigmoid函数
def sigmoid(inX):
    return 1.0/(1+exp(-inX))

#梯度上升法求w,迭代500次。每次计算所有样本
def gradAscent(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)             #将特征列表转换 NumPy matrix
    labelMat = mat(classLabels).transpose() #将tag列表转换 NumPy matrix,列矩阵
    m,n = shape(dataMatrix)
    alpha = 0.001
    maxCycles = 500
    weights = ones((n,1))
    for k in range(maxCycles):              #heavy on matrix operations
        h = sigmoid(dataMatrix*weights)     #m*n n*1 => h的维度为m*1
         error = (labelMat - h)              #vector subtraction
        weights = weights + alpha * dataMatrix.transpose()* error #所有特征都更新
    return weights

#画数据散点图及模型曲线
def plotBestFit(weights):
    import matplotlib
    import matplotlib.pyplot as plt
    matplotlib.use('TkAgg')
    dataMat,labelMat=loadDataSet()
    dataArr = array(dataMat)
    n = shape(dataArr)[0] 
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i])== 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
        else:
            xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
    ax.scatter(xcord2, ycord2, s=30, c='green')
    x = arange(-3.0, 3.0, 0.1)
    y = (-weights[0]-weights[1]*x)/weights[2]
    ax.plot(x, y)
    plt.xlabel('X1'); plt.ylabel('X2');
    plt.show()

#随机梯度上升法改进0,每来一个样本更新一下模型系数
def stocGradAscent0(dataMatrix, classLabels):
    m,n = shape(dataMatrix)
    alpha = 0.01
    weights = ones(n)   #initialize to all ones
    for i in range(m):
        h = sigmoid(sum(dataMatrix[i]*weights))
        error = classLabels[i] - h
        weights = weights + alpha * error * dataMatrix[i]
    return weights


#随机梯度上升法改进1,1.每次随机挑选样本更新系数; 2.步长下降,可以理解为先快后慢;3.增加迭代次数
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = shape(dataMatrix)
    weights = ones(n)   #initialize to all ones
    for j in range(numIter):
        dataIndex = range(m)
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #apha decreases with iteration, does not 
            randIndex = int(random.uniform(0,len(dataIndex)))#go to 0 because of the constant
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(dataIndex[randIndex])
    return weights

# 选择模型最后判决门限,此处选择0.5
def classifyVector(inX, weights):
    prob = sigmoid(sum(inX*weights))
    if prob > 0.5: return 1.0
    else: return 0.0

def main():
    print 'Test 1'
    dataArr, labelMat = loadDataSet()
    weights = gradAscent(dataArr, labelMat)
    print weights.getA()[0]

    #print 'Test 2 gradAscent'
    #plotBestFit(weights.getA())

    #print 'Test 3 stocGradAscent'
    #weights1 = stocGradAscent0(array(dataArr), labelMat)
    #plotBestFit(weights1)

    print 'Test 4 stocGradAscent1'
    weights2 = stocGradAscent1(array(dataArr), labelMat)
    plotBestFit(weights2)

if __name__ == '__main__':
    main()

5运行结果

/Users/tl/.pyenv/versions/2.7.13ML/bin/python /Users/tl/Works/MLiA/machinelearninginaction/Ch05/logRegres.py
Test 1
[[ 4.12414349]
 [ 0.48007329]
 [-0.6168482 ]]
Test 4 stocGradAscent1

stocGradAscent1


6 问题

1. RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.
参考
整理到此处:

#方法一:在用户的.bash_rc或.bash_profile下添加如下代码并source一下:
function frameworkpython {
    if [[ ! -z "$VIRTUAL_ENV" ]]; then
        PYTHONHOME=$VIRTUAL_ENV /usr/local/bin/python "$@"
    else
        /usr/local/bin/python "$@"
    fi
}

#方法二:在virtualenv的bin目录下新建frameworkpython文件并添加如下代码并source一下,如/Users/alan/.virtualenvs/machinelearning/bin/目录
#!/bin/bash
# what real Python executable to use
PYVER=2.7
PATHTOPYTHON=/usr/local/bin/
PYTHON=${PATHTOPYTHON}python${PYVER}

# find the root of the virtualenv, it should be the parent of the dir this script is in
ENV=`$PYTHON -c "import os; print(os.path.abspath(os.path.join(os.path.dirname(\"$0\"), '..')))"`

# now run Python with the virtualenv set as Python's HOME
export PYTHONHOME=$ENV
exec $PYTHON "$@"

#但以上两种方案仅在命令行中执行有效,而我们常常需要在PyCharm中编辑调试,这样就会很不方便
#方法三
#一、执行如下命令
echo "backend: TkAgg" > ~/.matplotlib/matplotlibrc
#二、在文件上方添加
import matplotlib
matplotlib.use('TkAgg')

由于本人环境是基于pycharm社区版,所以测试过上面第三种方法,该问题解决,其他两种方法未测试。


参考
1. 机器学习实战
2. 吴恩达老师讲义

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值