《meaching learning》机器学习学习记录2.逻辑回归

简介: 0831更新逻辑回归

机器学习学习记录2 - 逻辑回归

问题提出:

构建逻辑回归模型预测某个学生是否被大学录取

已知条件:

对于每一个训练样本有两次测试的评分和最终的录取结果

1.构建sigmoid函数

#通过Python定义sigmoid函数
def sigmoid(z):
    return 1 / (1 + np.exp(-z))
#sigmoid函数可视化
nums = np.arange(-10, 10, step=1)#返回一个
#print(nums)
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(nums, sigmoid(nums), 'r')
plt.show()

sigmoid函数可视化

2.编写代价函数

#编写代价函数
def cost(theta, X, y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))#np.multiply 两个参数相乘
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
    return np.sum(first - second) / (len(X))

3.导入数据并将其可视化

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

path = 'ex2data1.txt'
data = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
data.head()

#通过创建散点图表示正样本和负样本
positive = data[data['Admitted'].isin([1])]
negative = data[data['Admitted'].isin([0])]

fig, ax = plt.subplots(figsize=(12,8))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=50, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=50, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
plt.show()

散点图

通过对数据可视化我们可以看到正负样本之间有清晰的边界,因此可以通过逻辑回归来实现对结果预测

#添加偏置项
# add a ones column - this makes the matrix multiplication work out easier
data.insert(0, 'Ones', 1)#第0列添加偏置为1的标签项Ones

# set X (training data) and y (target variable)
cols = data.shape[1]
X = data.iloc[:,0:cols-1]
y = data.iloc[:,cols-1:cols]

# convert to numpy arrays and initalize the parameter array theta
X = np.array(X.values)
y = np.array(y.values)
theta = np.zeros(3)

可以通过调用cost函数计算代价

#此时初始化参数theat为0
cost(theat,X,y)

4.gradient descent(梯度下降)

def gradient(theta, X, y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    parameters = int(theta.ravel().shape[1])#ravel()多维转一维  shape[1]是取矩阵1*3中的3
    grad = np.zeros(parameters)
    
    error = sigmoid(X * theta.T) - y
    
    for i in range(parameters):
        term = np.multiply(error, X[:,i])
        grad[i] = np.sum(term) / len(X)
    
    return grad

gradient(theata,X,y)

该代码块仅仅执行一个梯度步长,接下来通过Scipy来寻找最优参数

import scipy.optimize as opt
#该函数用来寻找最优参数及theat的最优解
result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y))
result
#(array([-25.16131863,   0.20623159,   0.20147149]), 36, 0) result的结果
cost(result[0], X, y)#result[0]及就是优化后的theta
#结果:0.20349770158947458

5.预测

def predict(theta, X):
    probability = sigmoid(X * theta.T)
    return [1 if x >= 0.5 else 0 for x in probability]

theta_min = np.matrix(result[0])
predictions = predict(theta_min, X)
#zip是将对象中的元素打包成元组形式#判断predictions与y是否相等,若相等返回1否则返回0
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]
#计算准确率,用correct中两个元素相等的个数除以总个数也就是准确率。
accuracy = (sum(map(int, correct)) % len(correct))
print ('accuracy = {0}%'.format(accuracy))
#结果输出准确率为89%

因此得到了预测分类器的准确率为89%,之后将介绍使用交叉验证进行真实逼近


6.正则化逻辑回归

加入正则项有助于减少过拟合,提高模型的泛化能力

正则化代价函数

def costReg(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))#其他和上述保持一致
    reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[:,1:theta.shape[1]], 2))#正则化项,不能正则化第一项theta0(theta的第一列)
    return np.sum(first - second) / len(X) + reg

未对theta项进行正则化,因此,更新式子变为:

正则化梯度函数

#实现代码如下
def gradientReg(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    parameters = int(theta.ravel().shape[1])#将theta变为一维且得到其列数
    grad = np.zeros(parameters)
    
    error = sigmoid(X * theta.T) - y
    
    for i in range(parameters):
        term = np.multiply(error, X[:,i])
        
        if (i == 0):
            grad[i] = np.sum(term) / len(X)
        else:
            grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:,i])
    
    return grad

接着像之前一样初始化变量

# set X and y (remember from above that we moved the label to column 0)
cols = data2.shape[1]
X2 = data2.iloc[:,1:cols]
y2 = data2.iloc[:,0:1]

# convert to numpy arrays and initalize the parameter array theta
X2 = np.array(X2.values)
y2 = np.array(y2.values)
theta2 = np.zeros(11)

选择一个初始学习率和初始theta(为0)

learningRate = 1
costReg(theta2, X2, y2, learningRate)
#结果:0.6931471805599454

#执行一次梯度下降结果
gradientReg(theta2, X2, y2, learningRate)

#使用和第一部分一样的优化函数计算优化结果
result2 = opt.fmin_tnc(func=costReg, x0=theta2, fprime=gradientReg, args=(X2, y2, learningRate))
result2
(array([ 0.53010247,  0.29075567, -1.60725764, -0.58213819,  0.01781027,
        -0.21329507, -0.40024142, -1.3714414 ,  0.02264304, -0.95033581,
         0.0344085 ]),
 22,
 1)
#使用与第一部分同样的方法来监测准确度
theta_min = np.matrix(result2[0])
predictions = predict(theta_min, X2)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y2)]
accuracy = (sum(map(int, correct)) % len(correct))
print ('accuracy = {0}%'.format(accuracy))
#最终准确率为78%

7.scikit-learn方法解决

from sklearn import linear_model#调用sklearn的线性回归包
model = linear_model.LogisticRegression(penalty='l2', C=1.0)
model.fit(X2, y2.ravel())#ravel多维转一维
model.score(X2, y2)
#结果为0.6610169491525424

注:

我们可以看到这里的精度为0.66,比之前的0.78差了好多,但是该结果是在默认参数下计算的结果,可以通过调整参数获得与之前相同的精度。

相关文章
|
机器学习/深度学习 算法 知识图谱
【机器学习】逻辑回归原理(极大似然估计,逻辑函数Sigmod函数模型详解!!!)
【机器学习】逻辑回归原理(极大似然估计,逻辑函数Sigmod函数模型详解!!!)
|
机器学习/深度学习 存储 自然语言处理
【机器学习】基于逻辑回归的分类预测
【机器学习】基于逻辑回归的分类预测
|
机器学习/深度学习 存储 Linux
【机器学习 Azure Machine Learning】使用VS Code登录到Linux VM上 (Remote-SSH), 及可直接通过VS Code编辑VM中的文件
【机器学习 Azure Machine Learning】使用VS Code登录到Linux VM上 (Remote-SSH), 及可直接通过VS Code编辑VM中的文件
310 4
|
机器学习/深度学习 Ubuntu Linux
【机器学习 Azure Machine Learning】使用Aure虚拟机搭建Jupyter notebook环境,为Machine Learning做准备(Ubuntu 18.04,Linux)
【机器学习 Azure Machine Learning】使用Aure虚拟机搭建Jupyter notebook环境,为Machine Learning做准备(Ubuntu 18.04,Linux)
234 4
|
机器学习/深度学习 存储 算法
基于机器学习的地震预测(Earthquake Prediction with Machine Learning)(下)
基于机器学习的地震预测(Earthquake Prediction with Machine Learning)
413 0
|
机器学习/深度学习 存储 数据可视化
基于机器学习的地震预测(Earthquake Prediction with Machine Learning)(上)
基于机器学习的地震预测(Earthquake Prediction with Machine Learning)
533 0
|
机器学习/深度学习 运维 算法
【阿里天池-医学影像报告异常检测】3 机器学习模型训练及集成学习Baseline开源
本文介绍了一个基于XGBoost、LightGBM和逻辑回归的集成学习模型,用于医学影像报告异常检测任务,并公开了达到0.83+准确率的基线代码。
308 9
|
机器学习/深度学习 开发者 Python
Python 与 R 在机器学习入门中的学习曲线差异
【8月更文第6天】在机器学习领域,Python 和 R 是两种非常流行的编程语言。Python 以其简洁的语法和广泛的社区支持著称,而 R 则以其强大的统计功能和数据分析能力受到青睐。本文将探讨这两种语言在机器学习入门阶段的学习曲线差异,并通过构建一个简单的线性回归模型来比较它们的体验。
295 7
|
机器学习/深度学习 人工智能 自然语言处理
【机器学习】机器学习、深度学习、强化学习和迁移学习简介、相互对比、区别与联系。
机器学习、深度学习、强化学习和迁移学习都是人工智能领域的子领域,它们之间有一定的联系和区别。下面分别对这四个概念进行解析,并给出相互对比、区别与联系以及应用场景案例分析。
1173 1
|
机器学习/深度学习 人工智能 算法
【人工智能】机器学习、分类问题和逻辑回归的基本概念、步骤、特点以及多分类问题的处理方法
机器学习是人工智能的一个核心分支,它专注于开发算法,使计算机系统能够自动地从数据中学习并改进其性能,而无需进行明确的编程。这些算法能够识别数据中的模式,并利用这些模式来做出预测或决策。机器学习的主要应用领域包括自然语言处理、计算机视觉、推荐系统、金融预测、医疗诊断等。
582 1

热门文章

最新文章