#加载包 import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline
path = 'LogiReg_data.txt' #header=None:表示文件中的第一行不会被默认设置成列名。 #names用来设置列名 pdData = pd.read_csv(path,header=None,sep = ',',names=['Exam 1','Exam 2','Admitted']) pdData.head() %head函数默认读取前五行
pdData.shape
#数据可视化展示 positive=pdData[pdData['Admitted']==1] negative=pdData[pdData['Admitted']==0] fig,ax = plt.subplots(figsize=(10,5)) #plt.subplots()是一个函数,返回一个包含figure和axes对象的元组。 #因此,使用fig,ax = plt.subplots()将元组分解为fig和ax两个变量。 ax.scatter(positive['Exam 1'],positive['Exam 2'],s=30,c='b',marker='o',label='Admitted') ax.scatter(negative['Exam 1'], negative['Exam 2'], s=30, c='r', marker='x', label='Not Admitted') ax.legend() ax.set_xlabel('Exam 1 Score') ax.set_ylabel('Exam 2 Score')
The logistic regression
目标:建立分类器(求解出三个参数012)
设定阈值,根据阈值判断录取结果
要完成的模块
sigmod:映射到概率的函数
model:返回预测结果值
cost:根据参数计算损失
gradient:计算每个参数的梯度方向
descent:进行参数更新
accuracy:计算精度
#sigmod:映射到概率的函数 def sigmoid(z): return 1/(1+np.exp(-z)) #创建一个从-10到10大小为20的向量 nums=np.arange(-10,10,1) fig,ax = plt.subplots(figsize=(12,4)) ax.plot(nums,sigmoid(nums),'r')
① np.arange()
函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是6,步长为1。
参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况
1)一个参数时,参数值为终点,起点取默认值0,步长取默认值1。
2)两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值1。
3)三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长。其中步长支持小数
#一个参数 默认起点0,步长为1 输出:[0 1 2]
a = np.arange(3)
#两个参数 默认步长为1 输出[3 4 5 6 7 8]
a = np.arange(3,9)
#三个参数 起点为0,终点为3,步长为0.1 输出[ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9]
a = np.arange(0, 3, 0.1)
#model:返回预测结果值(模型函数) def model(X,theta): return sigmoid(np.dot(X,theta.T)
② Dataframe.insert(loc, column, value, allow_duplicates=False): 在Dataframe的指定列中插入数据。参数介绍:
loc: int型,表示第几列;若在第一列插入数据,则 loc=0
column: 给插入的列取名,如 column='新的一列'
value:数字,array,series等都可(可自己尝试)
allow_duplicates: 是否允许列名重复,选择Ture表示允许新的列名与已存在的列名重复。
③ shape函数,返回的是元组
hg.shape返回的是hg的行数和列数
hg.shape[0]返回的是hg的行数,有几行
hg.shape[1]返回的是hg的列数,有几列
pdData.insert(0,'ones',1) #首列插入全是1的值,0代表第一列 orig_data = pdData.as_matrix() #数据格式转化为矩阵 cols = orig_data.shape[1] X=orig_data[:,0:cols-1] #提取特征 y =orig_data[:,cols-1:cols] #提取标签 theta = np.zeros([1,3]) #初始化三个参数
#计算损失函数 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)) #根据似然函数的目标函数列式
#decent比较三种不同的梯度下降方法 STOP_ITER = 0 #根据迭代次数终止 STOP_COST = 1 #根据损失值终止 STOP_GRAD = 2 #根据梯度终止 def stopCriterion(type,value,threshold): #设定三种不同的停止策略 if type == STOP_ITER: return value>threshold #threshold 指定阈值 elif type == STOP_COST: return abs(value[-1]-value[-2])③shuffle()是不能直接访问的,可以导入numpy.random模块,然后通过 numpy.random 静态对象调用该方法,shuffle直接在原来的数组上进行 *** 作,改变原来数组的顺序,无返回值(是对列表x中的所有元素随机打乱顺序,若x不是列表,则报错)。
import numpy.random #洗牌 def shuffleData(data): np.random.shuffle(data) cols = data.shape[1] X = data[:, 0:cols-1] y = data[:, cols-1: ] return X,y#decent方法如下 import time def descent(data, theta, batchSize,stopType,thresh,alpha): #梯度下降求解 init_time = time.time() i =0 #迭代次数 k=0 # batch X,y = shuffleData(data) grad = np.zeros(theta.shape) #计算的梯度 costs = [cost(X,y,theta)] while True: grad = gradient(X[k:k+batchSize],y[k:k+batchSize],theta) k += batchSize #取batch数量个数据--批处理 if k>= n: k=0 X,y = shuffleData(data) #重新洗牌 theta = theta - alpha*grad #参数更新 costs.append(cost(X,y,theta)) #计算新的损失 i+=1 if stopType == STOP_ITER: value = i elif stopType == STOP_COST: value = costs elif stopType == STOP_GRAD: value = grad if stopCriterion(stopType,value,thresh):break return theta,i-1,costs,grad,time.time() - init_time#画图工具如下 def runExpe(data, theta, batchSize, stopType, thresh, alpha): #import pdb; pdb.set_trace(); theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha) name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled" name += " data - learning rate: {} - ".format(alpha) if batchSize==n: strDescType = "Gradient" elif batchSize==1: strDescType = "Stochastic" else: 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 < {}".format(thresh) name += strStop print ("***{}nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format( name, theta, iter, costs[-1], dur)) fig, ax = plt.subplots(figsize=(12,4)) ax.plot(np.arange(len(costs)), costs, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title(name.upper() + ' - Error vs. Iteration') return theta(1)基于所有样本的批量梯度下降法:
# 根据迭代次数停止 n=100 runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)#根据损失值变化停止,设定阈值 1E-6, 差不多需要110 000次迭代 runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)#根据梯度变化停止设定阈值 0.05,差不多需要40000次迭代 runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)(2)随机梯度下降法
#根据迭代次数停止策略 runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)很不稳定,再来试试把学习率调小一些
#很不稳定,把学习率调小一点 runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)总结:随机梯度速度快,但稳定性差,需要很小的学习率。
(3)小批量梯度下降
#根据迭代次数停止策略 runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)浮动仍然比较大,我们来尝试下对数据进行标准化,将数据按其属性(按列进行)减去其均值,然后除以其标准差。最后得到的结果是对每个属性/每列来说所有数据都聚集在0附近,方差值为1。
(4)将数据预处理后的结果
①基于所有样本的批量梯度下降法
#根据迭代次数停止策略 from sklearn import preprocessing as pp scaled_data = orig_data.copy() scaled_data[:, 1:3] = pp.scale(orig_data[:, 1:3]) runExpe(scaled_data, theta, n, STOP_ITER, thresh=5000, alpha=0.001)代价函数值为0.38。代价函数越小越好。
#根据梯度变化停止策略 runExpe(scaled_data, theta, n, STOP_GRAD, thresh=0.02, alpha=0.001)②随机梯度下降法
#随机-根据梯度变化停止策略 theta = runExpe(scaled_data, theta, 1, STOP_GRAD, thresh=0.002/5, alpha=0.001)梯度下降法虽然快,但迭代次数多,所以可采用小批量下降法。
③小批量梯度下降法
#根据梯度变化停止策略--小批量 runExpe(scaled_data, theta, 16, STOP_GRAD, thresh=0.002*2, alpha=0.001)下面看模型的精度:
#精度 #设定阈值 def predict(X, theta): return [1 if x >= 0.5 else 0 for x in model(X, theta)] scaled_X = scaled_data[:, :3] y = scaled_data[:, 3] predictions = predict(scaled_X, theta) 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(correct) % len(correct)) print ('accuracy = {0}%'.format(accuracy))
(13条消息) 梯度下降求解逻辑回归实战篇_huahuaxiaoshao的博客-CSDN博客
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)