考核成績分類梯下降算法求邏輯回歸_第1頁
考核成績分類梯下降算法求邏輯回歸_第2頁
考核成績分類梯下降算法求邏輯回歸_第3頁
考核成績分類梯下降算法求邏輯回歸_第4頁
考核成績分類梯下降算法求邏輯回歸_第5頁
已閱讀5頁,還剩4頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

1、Logistic RegressionThe data我們將建立一個邏輯回歸模型來預(yù)測一個學(xué)生是否被大學(xué)錄取。假設(shè)你是一個大學(xué)系的管理員,你想根據(jù)兩次考試的結(jié)果來決定每個申請人的錄取機會。你有以前的申請人的歷史數(shù)據(jù),你可以用它作為邏輯回歸的訓(xùn)練集。對于每一個培訓(xùn)例子,你有兩個考試的申請人的分?jǐn)?shù)和錄取決定。為了做到這一點,我們將建立一個分類模型,根據(jù)考試成績估計入學(xué)概率。#三大件import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlineimport os#path = 'da

2、ta' + os.sep + 'LogiReg_data.txt'pdData = pd.read_csv("F:研究課程機器學(xué)習(xí)宇迪系列python數(shù)據(jù)分析與機器學(xué)習(xí)實戰(zhàn)-全-E唐宇迪-機器學(xué)習(xí)課程資料機器學(xué)習(xí)算法配套案例實戰(zhàn)梯度下降dataLogiReg_data.txt", header=None, names='Exam 1', 'Exam 2', 'Admitted')pdData.head()pdData.shapepositive = pdDatapdData'Admitted&#

3、39; = 1 # returns the subset of rows such Admitted = 1, i.e. the set of *positive* examplesnegative = pdDatapdData'Admitted' = 0 # returns the subset of rows such Admitted = 0, i.e. the set of *negative* examplesfig, ax = plt.subplots(figsize=(10,5)ax.scatter(positive'Exam 1', positi

4、ve'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&#

5、39;)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, ax = plt.subplots(figsize=(12,4)ax.plot(nums, sigmoid(nums), 'r')def model(X, theta): return sigmoid(np.dot(X, theta.T)pdData.insert(0, '

6、;Ones', 1) # in a try / except structure so as not to return an error if the block si executed several times# set 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.sh

7、ape1X = orig_data:,0:cols-1y = orig_data:,cols-1:cols# convert to numpy 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:5y:5def cost(X, y, theta): left = np.multiply(-y, np.log(model(X, theta) righ

8、t = np.multiply(1 - y, np.log(1 - model(X, theta)return np.sum(left - right) / (len(X)cost(X, y, theta)def gradient(X, y, theta): 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(t

9、erm) / len(X) return gradGradient descent比較3中不同梯度下降方法STOP_ITER = 0STOP_COST = 1STOP_GRAD = 2def stopCriterion(type, value, threshold): #設(shè)定三種不同的停止策略 if type = STOP_ITER: return value > threshold elif type = STOP_COST: return abs(value-1-value-2) < thresholdelif type = STOP_GRAD: return np.linal

10、g.norm(value) < thresholdimport numpy.random#洗牌def shuffleData(data): np.random.shuffle(data) cols = data.shape1 X = data:, 0:cols-1 y = data:, cols-1:return X, yimport timedef descent(data, theta, batchSize, stopType, thresh, alpha): #梯度下降求解 init_time = time.time() i = 0 # 迭代次數(shù) k = 0 # batch X,

11、y = shuffleData(data) grad = np.zeros(theta.shape) # 計算的梯度 costs = cost(X, y, theta) # 損失值 while True: grad = gradient(Xk:k+batchSize, yk:k+batchSize, theta) k += batchSize #取batch數(shù)量個數(shù)據(jù) if k >= n: k = 0 X, y = shuffleData(data) #重新洗牌 theta = theta - alpha*grad # 參數(shù)更新 costs.append(cost(X, y, theta

12、) # 計算新的損失 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_timedef runExpe(data, theta, batchSize, stopType, thresh, alpha):

13、#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 = "Gr

14、adient" 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 = "

15、;costs change < ".format(thresh) else: strStop = "gradient norm < ".format(thresh) name += strStop print ("*nTheta: - Iter: - Last cost: :03.2f - Duration: :03.2fs".format( name, theta, iter, costs-1, dur) fig, ax = plt.subplots(figsize=(12,4) ax.plot(np.arange(len(cos

16、ts), costs, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title(name.upper() + ' - Error vs. Iteration') return theta不同的停止策略設(shè)定迭代次數(shù)#選擇的梯度下降方法是基于所有樣本的n=100runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)根據(jù)損失值停止設(shè)定閾值 1E-6, 差不多需要110 000次

17、迭代runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)根據(jù)梯度變化停止設(shè)定閾值 0.05,差不多需要40 000次迭代runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)Mini-batch descentrunExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)浮動仍然比較大,我們來嘗試下對數(shù)據(jù)進行標(biāo)準(zhǔn)化 將數(shù)據(jù)按其屬性(按列進行)減去其均值,然后除以其

18、方差。最后得到的結(jié)果是,對每個屬性/每列來說所有數(shù)據(jù)都聚集在0附近,方差值為1from sklearn import preprocessing as ppscaled_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)它好多了!原始數(shù)據(jù),只能達到達到0.61,而我們得到了0.38個在這里! 所以對數(shù)據(jù)做預(yù)處理是非常重要的runExpe(scaled_data, theta, n, STOP_GRAD, thresh=0.02, alpha=0.001)精度#設(shè)定閾值def predict(X, theta):return 1 if x >= 0.5 else 0 for x in

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論