【逻辑回归算法】{3} ——实现逻辑回归算法

此处用代码展示一下,如何用梯度下降法获取逻辑回归算法的参数。


一、加载sklearn中的鸢尾花数据进行测试

为了数据可视化,我们选择2种类型的鸢尾花,并且只选择2个特征。

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris()

X = iris.data
y = iris.target

X = X[y<2, :2] # 只取前两个特征
y = y[y<2]

plt.scatter(X[y==0,0], X[y==0,1], color='red')
plt.scatter(X[y==1,0], X[y==1,1], color='blue')
plt.show()

Output:


二、编写逻辑回归算法

先在playML文件夹中写一个metrics模块,用于计算准确率:

import numpy as np

def accuracy_score(y_true, y_predict):
    """计算y_true和y_predict之间的准确率"""
    return np.sum(y_true == y_predict) / len(y_true)

接着在playML文件夹中编写逻辑回归算法:

import numpy as np
from .metrics import accuracy_score # .表示当前目录 
 
class LogisticRegression:
 
    def __init__(self):
        """初始化Logistic Regression模型"""
        self.coef_ = None
        self.intercept_ = None
        self._theta = None
 
    def _sigmoid(self, t):
        return 1. / (1. + np.exp(-t))
 
    def fit(self, X_train, y_train, eta=0.01, n_iters=1e4):
        """根据训练数据集X_train, y_train, 使用梯度下降法训练Logistic Regression模型"""
        def J(theta, X_b, y):
            y_hat = self._sigmoid(X_b.dot(theta))
            try:
                return - np.sum(y*np.log(y_hat) + (1-y)*np.log(1-y_hat)) / len(y)
            except:
                return float('inf')
 
        def dJ(theta, X_b, y):
            return X_b.T.dot(self._sigmoid(X_b.dot(theta)) - y) / len(y)
 
        def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):
 
            theta = initial_theta
            cur_iter = 0
 
            while cur_iter < n_iters:
                gradient = dJ(theta, X_b, y)
                last_theta = theta
                theta = theta - eta * gradient
                if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
                    break
 
                cur_iter += 1
 
            return theta
 
        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
        initial_theta = np.zeros(X_b.shape[1])
        self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)
 
        self.intercept_ = self._theta[0]
        self.coef_ = self._theta[1:]
 
        return self
 
    def predict_proba(self, X_predict):
        """给定待预测数据集X_predict,返回表示X_predict的结果概率向量"""
        X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
        return self._sigmoid(X_b.dot(self._theta))
 
    def predict(self, X_predict):
        """给定待预测数据集X_predict,返回表示X_predict的结果向量"""
        proba = self.predict_proba(X_predict)
        return np.array(proba >= 0.5, dtype='int')
 
    def score(self, X_test, y_test):
        """根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""
        y_predict = self.predict(X_test)
        return accuracy_score(y_test, y_predict)
 
    def __repr__(self):
        return "LogisticRegression()"

然后在playML文件夹中编写一个分割数据集的模块:

import numpy as np

def train_test_split(X, y, test_ratio=0.2, seed=None):
    """将数据 X 和 y 按照test_ratio分割成X_train, X_test, y_train, y_test"""
    if seed:
        np.random.seed(seed)

    shuffled_indexes = np.random.permutation(len(X))

    test_size = int(len(X) * test_ratio)
    test_indexes = shuffled_indexes[:test_size]
    train_indexes = shuffled_indexes[test_size:]

    X_train = X[train_indexes]
    y_train = y[train_indexes]

    X_test = X[test_indexes]
    y_test = y[test_indexes]

    return X_train, X_test, y_train, y_test

三、实现逻辑回归

from playML.model_selection import train_test_split
from playML.LogisticRegression import LogisticRegression

X_train, X_test, y_train, y_test = train_test_split(X, y, seed=666)

log_reg = LogisticRegression()
log_reg.fit(X_train, y_train) # 训练模型

print(log_reg._theta) # 参数
print(log_reg.score(X_test, y_test)) # 预测准确率
print(log_reg.predict_proba(X_test)) # X预测为各个类别的概率的概率值
print(y_test) # 实际值
print(log_reg.predict(X_test)) # 预测值

Output:

log_reg._theta:array([-0.69377193,  3.01796521, -5.04447145]) # 第1个是截距,后2个是相关参数
log_reg.score(X_test, y_test):1.0 # 因为数据比较少,且只取了2个特征
log_reg.predict_proba(X_test):array([0.92972035, 0.98664939, 0.14852024, 0.01685947, 0.0369836 ,
   									  0.0186637 , 0.04936918, 0.99669244, 0.97993941, 0.74524655,
   									  0.04473194, 0.00339285, 0.26131273, 0.0369836 , 0.84192923,
   									  0.79892262, 0.82890209, 0.32358166, 0.06535323, 0.20735334])
y_test:array([1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0])
log_reg.predict(X_test):array([1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0])

参考资料:bobo老师机器学习教程

发布了75 篇原创文章 · 获赞 267 · 访问量 5217

猜你喜欢

转载自blog.csdn.net/weixin_45961774/article/details/105357274
今日推荐