吴恩达机器学习作业(3):逻辑回归

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/cg129054036/article/details/84780877

目录

1)数据处理

2)sigmoid函数

3)代价函数

4)梯度下降

5)预测函数


我们首先做一个练习,问题是这样的:设想你是大学相关部分的管理者,想通过申请学生两次测试的评分,来决定他们是否被录取。现在你拥有之前申请学生的可以用于训练逻辑回归的训练样本集。对于每一个训练样本,你有他们两次测试的评分和最后是被录取的结果。为了完成这个预测任务,我们准备构建一个可以基于两次测试评分来评估录取可能性的分类模型。

1)数据处理

第三次建议,我们拿到数据之后,还是要先看看数据长什么样子:

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])]#选取为 1的样本
negative = data[data['Admitted'].isin([0])]#选取为 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()

2)sigmoid函数

g 代表一个常用的逻辑函数(logistic function)为S形函数(Sigmoid function),公式为:

                                                                g(z)=\frac{1}{1+e^{-z}}

逻辑回归模型的假设函数为:

                                                                {{h}_{\theta }}\left( x \right)=\frac{1}{1+{{e}^{-{{\theta }^{T}}X}}}\\

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

让我们做一个快速的检查,来确保它可以工作。

nums = np.arange(-10, 10, step=1)

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(nums, sigmoid(nums), 'r')
plt.show()

3)代价函数

代价函数:

                  J\left( \theta \right)=\frac{1}{m}\sum\limits_{i=1}^{m}{[-{{y}^{(i)}}\log \left( {{h}_{\theta }}\left( {{x}^{(i)}} \right) \right)-\left( 1-{{y}^{(i)}} \right)\log \left( 1-{{h}_{\theta }}\left( {{x}^{(i)}} \right) \right)]}

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)))
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
    return np.sum(first - second) / (len(X))

现在我们需要对数据进行一下处理,和我们在线性回归练习中的处理很相似

# add a ones column 
data.insert(0, 'Ones', 1)

# 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)

我们可以计算初始化参数的代价函数值:(theta为0)

cost(theta, X, y)

0.6931471805599453

4)梯度下降

形式和线性回归的梯度下降一致:

                                                                     $$\frac{\partial J\left( \theta \right)}{\partial {{\theta }_{j}}}=\frac{1}{m}\sum\limits_{i=1}^{m}{({{h}_{\theta }}\left( {{x}^{(i)}} \right)-{{y}^{(i)}})x_{_{j}}^{(i)}}$$

def gradient(theta, X, y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    parameters = int(theta.ravel().shape[1])
    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

注意在这里我们并不执行梯度下降——我们计算一个梯度步长。既然我们在用 python ,我们可以使用 SciPy 的优化 API 来实现相同功能。

我们看看用我们的数据和初始参数为0的梯度下降法的结果。

gradient(theta, X, y)

array([ -0.1       , -12.00921659, -11.26284221])

现在可以用SciPy's truncated newton实现寻找最优参数。

import scipy.optimize as opt
result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y))
result

(array([-25.1613186 ,   0.20623159,   0.20147149]), 36, 0)

让我们看看在这个结论下代价函数计算结果是什么个样子。

cost(result[0], X, y)

0.20349770158947464

5)预测函数

接下来,我们需要编写一个函数,用我们所学的参数theta来为数据集X输出预测。然后,我们可以使用这个函数来给我们的分类器的训练精度打分。

h_\theta大于等于0.5时,预测 y=1

h_\theta小于0.5时,预测 y=0 。

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)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]
accuracy = (sum(map(int, correct)) % len(correct))
print ('accuracy = {0}%'.format(accuracy))

accuracy = 89%

我们的逻辑回归分类器预测正确,如果一个学生被录取或没有录取,达到89%的精确度。不坏!记住,这是训练集的准确性。我们没有保持住了设置或使用交叉验证得到的真实逼近,所以这个数字有可能高于其真实值(这个话题将在以后说明)。

在本练习的第二部分中,我们将介绍正则化逻辑回归,这会大大提高我们模型的泛化能力。

猜你喜欢

转载自blog.csdn.net/cg129054036/article/details/84780877