久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python實現梯度下降和邏輯回歸

瀏覽:2日期:2022-08-01 11:40:07

本文實例為大家分享了python實現梯度下降和邏輯回歸的具體代碼,供大家參考,具體內容如下

import numpy as npimport pandas as pdimport os data = pd.read_csv('iris.csv') # 這里的iris數據已做過處理m, n = data.shapedataMatIn = np.ones((m, n))dataMatIn[:, :-1] = data.ix[:, :-1]classLabels = data.ix[:, -1] # sigmoid函數和初始化數據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的行數,n:dataMatrix的列數 weights = np.ones((n, 1)) # 初始化回歸系數(n, 1) alpha = 0.001 # 步長 maxCycle = 500 # 最大循環次數 epsilon = 0.001 error = np.zeros((n,1)) for i in range(maxCycle): for j in range(m): h = sigmoid(dataMatrix * weights) # sigmoid 函數 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) # 根據模型預測的概率 # 預測結果二值化 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數據集 # 第一次運行此代碼時此步驟不要 data.to_csv('data_and_pred.csv', index=False, encoding='utf_8_sig') # 數據集保存pred_result(dataMatIn)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 轮台县| 扶风县| 新泰市| 松潘县| 集贤县| 深圳市| 虹口区| 崇文区| 大连市| 涞水县| 利川市| 沽源县| 都江堰市| 福鼎市| 理塘县| 若尔盖县| 兖州市| 城市| 陇南市| 阳城县| 元氏县| 城步| 洱源县| 丹寨县| 靖安县| 武定县| 新宁县| 辽中县| 嵩明县| 金川县| 丹阳市| 金坛市| 柳江县| 原阳县| 辰溪县| 彰武县| 白水县| 长海县| 蒙自县| 通化县| 崇明县|