python實(shí)現(xiàn)梯度下降和邏輯回歸
本文實(shí)例為大家分享了python實(shí)現(xiàn)梯度下降和邏輯回歸的具體代碼,供大家參考,具體內(nèi)容如下
import numpy as npimport pandas as pdimport os data = pd.read_csv('iris.csv') # 這里的iris數(shù)據(jù)已做過(guò)處理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)) # 隨機(jī)梯度下降def Stocgrad_descent(dataMatIn, classLabels): dataMatrix = np.mat(dataMatIn) # 訓(xùn)練集 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 # 步長(zhǎng) 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ù)模型預(yù)測(cè)的概率 # 預(yù)測(cè)結(jié)果二值化 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ù)集 # 第一次運(yùn)行此代碼時(shí)此步驟不要 data.to_csv('data_and_pred.csv', index=False, encoding='utf_8_sig') # 數(shù)據(jù)集保存pred_result(dataMatIn)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python常用擴(kuò)展插件使用教程解析2. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)3. Python安裝并操作redis實(shí)現(xiàn)流程詳解4. 部署vue+Springboot前后端分離項(xiàng)目的步驟實(shí)現(xiàn)5. idea設(shè)置自動(dòng)導(dǎo)入依賴(lài)的方法步驟6. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過(guò)程7. ajax post下載flask文件流以及中文文件名問(wèn)題8. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶(hù)登錄的步驟9. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺(tái)】10. PHP字符串前后字符或空格刪除方法介紹

網(wǎng)公網(wǎng)安備