[机器学习]实验一:对数几率回归算法实践

线性回归,逻辑回归的实现

一、实验目的

掌握线性模型、对率回归算法原理。

二、实验项目内容

  1. 理解对率回归算法原理。
  2. 编程实现对数几率回归算法。
  3. 将算法应用于西瓜数据集分类问题。

三、实验过程或算法(源程序)

参考周志华《机器学习》一书P57,对数几率回归的理解,是一种用线性回归模型的预测结果去逼近真实标记的对数几率。是一种经典的二分类学习方法。

对率函数是任意阶可导的凸函数,是一种“sigmoid函数

sigmoid函数

逻辑回归算法具体实现

源代码如下:

# title: 对数几率回归
# author: DYBOY
# mail: dyboy2017@qq.com

import numpy as np
import matplotlib.pyplot as plt

#加载文件数据
def loaddata(filename):
    file = open(filename)
    x = []
    y = []
    for line in file.readlines():
        # 分成三列 0:密度 1:含糖率 3:好坏瓜
        line = line.strip().split()
        x.append([1, float(line[0]), float(line[1])]) # x (10,3)
        y.append(int(line[2]))
        xmat = np.mat(x)
        ymat = np.mat(y).T
    file.close()
    return xmat, ymat


def w_clac(xmat, ymat, alpha = 0.001, maxIter = 10000):
    # 初始化生成三行一列
    W = np.mat(np.random.randn(3, 1))
    w_save = []
    for i in range(maxIter):
        # W update
        H = 1/(1+np.exp(-xmat*W))   #dw (3, 1)
        dw = xmat.T * (H - ymat)
        W -= alpha * dw
        if(i%100 == 0):
            w_save.append([W.copy(), i])  #存入W 和 第i步
    return W, w_save


xmat, ymat = loaddata('test.txt')

# print('xmat:', xmat, xmat.shape)
# print('ymat', ymat, ymat.shape)

# 更新W 学习率0.0001
W, w_save = w_clac(xmat, ymat, 0.001, 10000)
print('W:', W)
for wi in w_save:
    plt.clf()  # 清除历史轨迹
    w0 = wi[0][0, 0]
    w1 = wi[0][1, 0]
    w2 = wi[0][2, 0]
    # 做泛化
    plotx1 = np.arange(0.000, 0.800, 0.001)
    plotx2 = -w0/w2-w1/w2*plotx1
    plt.plot(plotx1, plotx2, c='r', label='decision boundary')

    plt.scatter(xmat[:, 1][ymat == 0].A, xmat[:, 2][ymat == 0].A, marker='^', s=50, label='label=bad')
    plt.scatter(xmat[:, 1][ymat == 1].A, xmat[:, 2][ymat == 1].A, s=50, label='label=good')
    plt.grid()
    plt.legend()
    plt.title('iter:%s'%np.str(wi[1]))
    plt.pause(0.1)  #生成动画
    #plt.show()

数据集(Source:《机器学习》89页):

0.697 0.46 1
0.774 0.376 1
0.634 0.264 1
0.608 0.318 1
0.556 0.215 1
0.403 0.237 1
0.481 0.149 1
0.437 0.211 1
0.666 0.091 0
0.243 0.267 0
0.245 0.057 0
0.343 0.099 0
0.639 0.161 0
0.657 0.198 0
0.36 0.37 0
0.593 0.042 0
0.719 0.103 0

四、实验结果及分析

在迭代10000次结果下,此后更多迭代次数下,并不能较大改善模型结果

分类结果

分析可能原因:

  1. 原始数据存在噪音,并未排除
  2. 算法本身存在的问题,无法较好区别该数据集

源文件及数据下载地址(内附运行过程GIF):https://pan.baidu.com/s/1WTzkfZb95gisnBg3NdbLhQ 提取码: a5rn

发表评论 / Comment

用心评论~


Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23