版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Logistic RegressionThe data我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理 员,你想根据两次考试的结果来决定每个申请人的录取机会。你有以前的申请人的历史数据, 你可以用它作为逻辑回归的训练集。对于每一个培训例子,你有两个考试的申请人的分数和 录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。#三大件import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlineimport os#path = data
2、 + os.sep + LogiReg_data.txtpdData = pd.read_csv(F:W究课程机器学习宇迪系列python数据分析与机器学习实战- 全-E唐宇迪-机器学习课程资料机器学习算法配套案例实战梯度下降 dataWLogiReg_data.txt, header=None, names=Exam 1, Exam 2, Admitted)pdData.head()Exam 1Exam 2Admitted034.62366。78.024G930130.2BG71143.3949930235.8474097290219803G0.1S259986.3085521479.032
3、73875.3443761pdData.shapepositive = pdDatapdDataAdmitted = 1 # returns the subset of rows such Admitted = 1, i.e. the set of positive* examplesnegative = pdDatapdDataAdmitted = 0 # returns the subset of rows such Admitted = 0, i.e. the set of negative* examplesfig, ax = plt.subplots(figsize=(10,5)ax
4、.scatter(positiveExam 1, positiveExam 2, s=30, c=b, marker=o, label=Admitted) ax.scatter(negativeExam 1, negativeExam 2, s=30, c=r, marker=x, label=Not Admitted) ax.legend()ax.set_xlabel(Exam 1 Score)ax.set_ylabel(Exam 2 Score) Admittedxxx Not Admitted2030405060708090100110Exam 1 ScoreThe logistic r
5、egression目标:建立分类器(求解出三个委数 财阻)设定阚值,根据阚值判断录取结果要完成的模块sigmoid :映射到概率的函数model :返回预则结果值.cost:根据参数计算损失gradient :计算每个参数的梯度方向descent :进行参数更新accuracy计算精度sigmoid 函数def sigmoid(z):return 1 / (1 + np.exp(-z)nums = np.arange(-10, 10, step=1) #creates a vector containing 20 equally spaced values from -10 to 10fig,
6、 ax = plt.subplots(figsize=(12,4)ax.plot(nums, sigmoid(nums), r)Cjnatplotlib. 1 mes. Lme2D at Ok lbab41 d49bUSigmoid T |Q I |-双0) = 0上(-oo) =。g(+8)= Idef model(X, theta):return sigmoid(np.dot(X, theta.T) r i1(的仇化t)X工|=免+饥叫+毋口pdData.insert(0, Ones, 1) # in a try / except structure so as not to return
7、 an error if the block si executed several timesset X (training data) and y (target variable)orig_data = pdData.as_matrix() # convert the Pandas representation of the data to an array useful for further computationscols = orig_data.shape1X = orig_data:,0:cols-1y = orig_data:,cols-1:colsconvert to nu
8、mpy arrays and initalize the parameter array theta#X = np.matrix(X.values)#y = np.matrix(data.iloc:,3:4.values) #np.array(y.values)theta = np.zeros(1, 3)X:5array(1.,34.62365962,78.02469232,1.,30.20671077,43.39499752,1.,35.04740377,72.90219003,1.,60.10259939,86. 3035521 ,1.,79.03273605,75.34437644)y:
9、5array( 0., D.L 口 1., l.U)损失函数将对数似然函数去负号玖知(。0 = 一小g)-(I -y)log(l -h0(x) 求平均损失,=做)席)def cost(X, y, theta):left = np.multiply(-y, np.log(model(X, theta)right = np.multiply(1 - y, np.log(1 - model(X, theta)return np.sum(left - right) / (len(X)cost(X, y, theta)0.69314718055994529计算梯度def gradient(X, y, t
10、heta):grad = np.zeros(theta.shape)error = (model(X, theta)- y).ravel()for j in range(len(theta.ravel(): #for each parmeter term = np.multiply(error, X:,j) grad0, j = np.sum(term) / len(X)return gradGradient descent比较3中不同梯度下降方法STOP_ITER = 0STOP_COST = 1STOP_GRAD = 2 def stopCriterion(type, value, thr
11、eshold):#设定三种不同的停止策略return value thresholdreturn abs(value-1-value-2) thresholdreturn np.linalg.norm(value) = n:k = 0X, y = shuffleData(data) #重新洗牌theta = theta - alpha*grad # 参数更新costs.append(cost(X, y, theta) # 计算新的损失i += 1if stopType = STOP_ITER:value = ielif stopType = STOP_COST:value = costseli
12、f stopType = STOP_GRAD:value = gradif stopCriterion(stopType, value, thresh): breakreturn theta, i-1, costs, grad, time.time() - init_timedef runExpe(data, theta, batchSize, stopType, thresh, alpha):#import pdb; pdb.set_trace();theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType
13、, thresh, alpha) name = Original if (data:,12).sum() 1 else Scaledname += data - learning rate: ( - .format(alpha)if batchSize=n: strDescType = Gradientelif batchSize=1: strDescType = Stochasticelse: strDescType = Mini-batch ().format(batchSize)name += strDescType + descent - Stop:if stopType = STOP_ITER: strStop = iterations.format(thresh)elif stopType = STOP_COST: strStop = costs change .format(thresh)else: strStop = gradient norm = 0.5 else 0 for x in model(X, theta)scaled_X = scaled_data:, :3y = scaled_data:, 3pr
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2027届浙江省舟山市南海实验中学化学九上期中学业质量监测试题含解析
- 2027届四川省北师大广安实验学校化学九上期末经典试题含解析
- 凉山市重点中学2027届化学九上期中联考试题含解析
- 2027届江苏省连云港市赣榆县九上化学期中统考试题含解析
- 2027届广西来宾武宣县化学九上期末学业水平测试试题含解析
- 2026食品检测服务领域市场需求系统分析及技术手段与质量控制研究报告
- 2026皮革制品行业市场材料供需结构解析及品牌建设规划发展研究
- 2026中国渔业市场发展分析及发展趋势与投资前景研究报告
- 2026中国饲料加工行业环保政策应对与产业升级计划及智能化设备引进效果评估
- 2026年8月新疆红星电力有限公司面向社会招聘财务人员2人笔试题库及答案详解【新】
- 内蒙古赤峰市2025-2026学年高一下学期7月期末考试数学试卷
- 2026年学宪法讲宪法知识竞赛考试题库(含答案)
- 2026年文山州砚山县公安局第三批警务辅助人员招聘(46人)笔试备考试题及答案详解
- 2026中国压力传感器技术创新与下游应用领域拓展报告
- 中邮金融资产投资有限公司招聘笔试题库2026
- 美国糖尿病学会“2026年妊娠期高血糖诊治指南”解读
- 2026新教科版四年级科学上册知识点
- 自然灾害中的急救护理
- 2026年全国I卷高考语文真题解读暨2027届高三高考备考复习策略
- 肩关节不稳康复治疗方法
- GB/T 20961-2018单绳缠绕式矿井提升机
评论
0/150
提交评论