自己建设网站流程,本周国内新闻,婚庆网站建设的需求分析,东莞网站系统后缀目录
1#xff09;数据处理
2#xff09;sigmoid函数
3#xff09;代价函数
4#xff09;梯度下降
5#xff09;预测函数 我们首先做一个练习#xff0c;问题是这样的#xff1a;设想你是大学相关部分的管理者#xff0c;想通过申请学生两次测试的评分#xff0c…目录
1数据处理
2sigmoid函数
3代价函数
4梯度下降
5预测函数 我们首先做一个练习问题是这样的设想你是大学相关部分的管理者想通过申请学生两次测试的评分来决定他们是否被录取。现在你拥有之前申请学生的可以用于训练逻辑回归的训练样本集。对于每一个训练样本你有他们两次测试的评分和最后是被录取的结果。为了完成这个预测任务我们准备构建一个可以基于两次测试评分来评估录取可能性的分类模型。
1数据处理
第三次建议我们拿到数据之后还是要先看看数据长什么样子
import numpy as np
import pandas as pd
import matplotlib.pyplot as pltpath ex2data1.txt
data pd.read_csv(path, headerNone, 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], s50, cb, markero, labelAdmitted)
ax.scatter(negative[Exam 1], negative[Exam 2], s50, cr, markerx, labelNot Admitted)
ax.legend()
ax.set_xlabel(Exam 1 Score)
ax.set_ylabel(Exam 2 Score)
plt.show() 2sigmoid函数
g 代表一个常用的逻辑函数logistic function为S形函数Sigmoid function公式为 逻辑回归模型的假设函数为 def sigmoid(z):return 1 / (1 np.exp(-z))
让我们做一个快速的检查来确保它可以工作。
nums np.arange(-10, 10, step1)fig, ax plt.subplots(figsize(12,8))
ax.plot(nums, sigmoid(nums), r)
plt.show() 3代价函数
代价函数 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梯度下降
形式和线性回归的梯度下降一致 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) - yfor 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])
现在可以用SciPys truncated newton实现寻找最优参数。
import scipy.optimize as opt
result opt.fmin_tnc(funccost, x0theta, fprimegradient, args(X, y))
result(array([-25.1613186 , 0.20623159, 0.20147149]), 36, 0)
让我们看看在这个结论下代价函数计算结果是什么个样子。
cost(result[0], X, y)0.20349770158947464
5预测函数
接下来我们需要编写一个函数用我们所学的参数theta来为数据集X输出预测。然后我们可以使用这个函数来给我们的分类器的训练精度打分。
当大于等于0.5时预测 y1
当小于0.5时预测 y0 。
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%的精确度。不坏记住这是训练集的准确性。我们没有保持住了设置或使用交叉验证得到的真实逼近所以这个数字有可能高于其真实值这个话题将在以后说明。 在本练习的第二部分中我们将介绍正则化逻辑回归这会大大提高我们模型的泛化能力。