logistic回归【逻辑斯蒂回归】

一、最大似然估计函数

对未知参数Θ进行估计的时候,在该参数可能的取值范围内选取,使样本获此观测值X1,X2,...Xn的概率最大值的参数值作为参数Θ的估计,这就是极大似然估计。下面是极大似然函数的定义。

logistic回归【逻辑斯蒂回归】

logistic回归【逻辑斯蒂回归】

求解极大似然函数的步骤

logistic回归【逻辑斯蒂回归】

以二项分布为例,讲解极大似然估计

logistic回归【逻辑斯蒂回归】

二、sigmoid函数及其导数

sigmoid函数如下所示:

                                                                                         logistic回归【逻辑斯蒂回归】

sigmoid函数图像如下所示:可以看到当x为0的时候,y值为0.5,当x趋近于正无穷的时候,y趋近于1。当x趋近于负无穷的时候,y趋近于0

logistic回归【逻辑斯蒂回归】

下面是sigmoid函数的导数求导公式

logistic回归【逻辑斯蒂回归】

下面是sigmoid导数的函数图像,可以看到sigmoid在中间导数值大,进行梯度下降的时候,运行的快。sigmoid在两侧导数小,进行梯度下降的时候,运行的慢。

logistic回归【逻辑斯蒂回归】

三、logistic回归原理

logistic回归本质上是一个二分类问题,运用极大似然函数来估计参数值。设X为数据的特征,W,b为要求的参数,f(x)为估计为正类的概率,1-f(x)为估计成负类的概率。则logistic转为二分类,可利用极大似然函数求解,参见上面讲解极大似然函数的例子。

logistic回归【逻辑斯蒂回归】

实际计算过程中一般取InL的负数,转化为求最小值

logistic回归【逻辑斯蒂回归】

 

四、logistic回归代码实现

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

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

def create_data():
    iris = load_iris()
    df = pd.DataFrame(iris.data,columns=iris.feature_names)
    df['label'] = iris.target
    df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
    df.insert(0,"ones",1)
    data = np.array(df.iloc[:100,[0, 1, 2, -1]])
    return data[:,:3],data[:,-1]

X,y = create_data()
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

#计算损失函数
def cost(theta,X,y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y.T,np.log(sigmoid(X*theta.T)))
    second = np.multiply((1-y).T,np.log(sigmoid(1-sigmoid(X*theta.T))))
    return np.sum(first-second)/(len(X))

#计算梯度
def gradient(theta,X,y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    error = sigmoid(np.dot(X,theta.T)) - y.T
    grad = np.dot(error.T,X)

    return grad

#进行迭代,求解最优值
theta = np.zeros(3)
for i in range(400):
    c = cost(theta,X_train,y_train)
    g = gradient(theta,X_train,y_train)
    theta = theta-g*0.005
print(theta)

#进行预测
def predict(theta,X):
    prbability = sigmoid(np.dot(X,theta.T))
    return [1 if x>=0.5 else 0 for x in prbability]


theta_min = np.matrix(theta)
predictions = predict(theta_min, X_test)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y_test)]
accuracy = sum(correct)/len(correct)
print ('accuracy = {}'.format(accuracy))