python實現(xiàn)梯度下降和邏輯回歸
本文實例為大家分享了python實現(xiàn)梯度下降和邏輯回歸的具體代碼,供大家參考,具體內(nèi)容如下
import numpy as npimport pandas as pdimport os data = pd.read_csv('iris.csv') # 這里的iris數(shù)據(jù)已做過處理m, n = data.shapedataMatIn = np.ones((m, n))dataMatIn[:, :-1] = data.ix[:, :-1]classLabels = data.ix[:, -1] # sigmoid函數(shù)和初始化數(shù)據(jù)def sigmoid(z): return 1 / (1 + np.exp(-z)) # 隨機梯度下降def Stocgrad_descent(dataMatIn, classLabels): dataMatrix = np.mat(dataMatIn) # 訓練集 labelMat = np.mat(classLabels).transpose() # y值 m, n = np.shape(dataMatrix) # m:dataMatrix的行數(shù),n:dataMatrix的列數(shù) weights = np.ones((n, 1)) # 初始化回歸系數(shù)(n, 1) alpha = 0.001 # 步長 maxCycle = 500 # 最大循環(huán)次數(shù) epsilon = 0.001 error = np.zeros((n,1)) for i in range(maxCycle): for j in range(m): h = sigmoid(dataMatrix * weights) # sigmoid 函數(shù) weights = weights + alpha * dataMatrix.transpose() * (labelMat - h) # 梯度 if np.linalg.norm(weights - error) < epsilon: break else: error = weights return weights # 邏輯回歸def pred_result(dataMatIn): dataMatrix = np.mat(dataMatIn) r = Stocgrad_descent(dataMatIn, classLabels) p = sigmoid(dataMatrix * r) # 根據(jù)模型預測的概率 # 預測結果二值化 pred = [] for i in range(len(data)): if p[i] > 0.5: pred.append(1) else: pred.append(0) data['pred'] = pred os.remove('data_and_pred.csv') # 刪除List_lost_customers數(shù)據(jù)集 # 第一次運行此代碼時此步驟不要 data.to_csv('data_and_pred.csv', index=False, encoding='utf_8_sig') # 數(shù)據(jù)集保存pred_result(dataMatIn)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. js select支持手動輸入功能實現(xiàn)代碼2. PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程3. asp.net core項目授權流程詳解4. html中的form不提交(排除)某些input 原創(chuàng)5. CSS3中Transition屬性詳解以及示例分享6. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼7. vue使用moment如何將時間戳轉為標準日期時間格式8. 開發(fā)效率翻倍的Web API使用技巧9. jsp文件下載功能實現(xiàn)代碼10. ASP常用日期格式化函數(shù) FormatDate()
