逻辑回归学习笔记

逻辑回归学习:

1.损失函数/代价函数:
寻找一个超平面,将样本数据进行分类,找出损失函数的minimum值。
作用原理:
对于回归问题,可以用损失函数来求最优解,也常用的是平方误差代价函数/损失函数。
对于以下的假设函数:
Hypothesis: hθ(x) = θ0 + θ1x
里面有θ0和θ1这两个参数,需要找出的就是最优的θ0和θ1这两个参数使直线能够代表所有数据。
代价函数
http://blog.csdn.net/sd9110110/article/details/52863390
分类算法中的损失函数
http://blog.csdn.net/google19890102/article/details/50522945

2.逻辑回归模型:
http://blog.chinaunix.net/uid-20761674-id-4336428.html
逻辑回归的Hypothesis输出介于0,1之间,即:
0≤hθ(x)≤1
线性回归无法做到,因此引入函数g,另逻辑回归的Hypothesis表示为:
hθ(x)=g(θTx)
g为sigmoid function or logistic function,表达式:
g(z) = 1/(1+exp-z)
再次回顾sigmoid function的图形,也就是g(z)的图形:
这里写图片描述
当g(z)≥0.5时, z≥0;
对于hθ(x)=g(θTx)≥0.5, 则θTx≥0, 此时意味着预估y=1;
决策边界即为:θTx = 0
反之,当预测y = 0时,θTx<0;
我们可以认为θTx = 0是一个决策边界,当它大于0或小于0时,逻辑回归模型分别预测不同的分类结果。例如,
hθ(x)=g(θ0+θ1x1+θ2x2)
θ0,θ1,θ2分别取-3, 1, 1,
则当?3+x1+x2≥0时, y = 1; 则x1+x2 =3是一个决策边界也就是超平面,图形表示如下:
这里写图片描述
也可以得到非线性决策边界
其中,在求决策边界时,会用到上面提到的损失函数,
在计算参数theta时,使用梯度下降的方法来学习参数
http://blog.csdn.net/han_xiaoyang/article/details/49123419
链接中有梯度下降算法的详解。
当需要给一个非线性的数据找到决策边界时,使用正则化来解决这一问题。
http://www.cnblogs.com/jianxinzhou/p/4083921.html

具体的数据分析流程http://blog.yhat.com/posts/logistic-regression-and-python.html

# -*- coding: utf-8 -*-
"""
Created on Thu Jun 15 16:18:27 2017

@author: gc125128
"""

import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

from scipy.optimize import minimize

from numpy import dot 

from sklearn.preprocessing import PolynomialFeatures

#load and show data
def loaddata(file, delimiter1):
    data = np.loadtxt(file,delimiter=delimiter1)
    print('Dimension:', data.shape)
    print(data[1:6,:])
    return data
    pass

def plotData(data, label_x, label_y, label_pos, label_neg, axes = None):
    neg = data[:,2] == 0 #获得的负样本下标为0
    pos = data[:,2] == 1 #获得的正样本下标为1

    if axes == None:
        axes = plt.gca()
    axes.scatter(data[pos][:,0], data[pos][:,1], marker='+', c='k', s=60, linewidth=2, label=label_pos)
    axes.scatter(data[neg][:,0], data[neg][:,1], c='y', s=60, label=label_neg)
    axes.set_xlabel(label_x)
    axes.set_ylabel(label_y)
    axes.legend(frameon= True, fancybox = True);
    pass

data = loaddata('D:\predictive analytics\data1.txt', ',')

X = np.c_[np.ones((data.shape[0],1)), data[:,0:2]]
y = np.c_[data[:,2]]

plotData(data,'Exam 1 score', 'Exam 2 score', 'Pass', 'Fail')

# http://old.sebug.net/paper/books/scipydoc/numpy_intro.html#ndarray help to understand the numpy functions
# compute the sigmoid funcion
def sigmoid(z):
    return 1/(1+np.exp(-z))
    pass

# compute the cost function
def costFunction(theta, X, y):
    m = y.size
    h = sigmoid(X.dot(theta))

    J = -1.0*(1.0/m)*(np.log(h).T.dot(y)+np.log(1-h).T.dot(1-y))

    if np.isnan(J[0]):
        return(np.inf)
    return J[0]
    pass

#compute the gradient descent
def gradient(theta, X, y):
    m = y.size
    h = sigmoid(X.dot(theta.reshape(-1,1)))

    grad =(1.0/m)*X.T.dot(h-y)

    return(grad.flatten())
    pass

initial_theta = np.zeros(X.shape[1])
cost = costFunction(initial_theta, X, y)
grad = gradient(initial_theta, X, y)
print('Cost: \n', cost)
print('Grad: \n', grad)

res = minimize(costFunction, initial_theta, args=(X,y), jac=gradient, options={'maxiter':400})
res


def predict(theta, X, threshold=0.5):
    p = sigmoid(X.dot(theta.T)) >= threshold
    return(p.astype('int'))
    pass

plt.scatter(45, 85, s=60, c='r', marker='v', label='(45, 85)')
plotData(data, 'Exam 1 score', 'Exam 2 score', 'Admitted', 'Not admitted')
x1_min, x1_max = X[:,1].min(), X[:,1].max(),
x2_min, x2_max = X[:,2].min(), X[:,2].max(),
xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
h = sigmoid(np.c_[np.ones((xx1.ravel().shape[0],1)), xx1.ravel(), xx2.ravel()].dot(res.x))
h = h.reshape(xx1.shape)
plt.contour(xx1, xx2, h, [0.5], linewidths=1, colors='b');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值