最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實(shí)現(xiàn)梯度下降和邏輯回歸

 更新時(shí)間:2020年03月24日 15:49:07   作者:hllingg  
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)梯度下降和邏輯回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python實(shí)現(xiàn)梯度下降和邏輯回歸的具體代碼,供大家參考,具體內(nèi)容如下

import numpy as np
import pandas as pd
import os
 
data = pd.read_csv("iris.csv") # 這里的iris數(shù)據(jù)已做過處理
m, n = data.shape
dataMatIn = 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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

锡林郭勒盟| 新乐市| 沙坪坝区| 南丰县| 乐亭县| 枞阳县| 怀来县| 中西区| 井陉县| 增城市| 栾城县| 巴林左旗| 湘乡市| 高雄市| 墨脱县| 绥江县| 湘潭市| 平谷区| 九江县| 丹棱县| 安平县| 浑源县| 虎林市| 云霄县| 遂宁市| 古田县| 耿马| 宜君县| 门源| 云龙县| 林州市| 齐齐哈尔市| 云浮市| 义乌市| 合水县| 洪雅县| 郯城县| 宜兰县| 仙游县| 石城县| 清河县|