機器學習實戰之logistic回歸分類

利用logistic回歸進行分類的主要思想:根據現有數據對分類邊界建立回歸公式,并以此進行分類。

?

logistic優缺點:

優點:計算代價不高,易于理解和實現。
缺點:容易欠擬合,分類精度可能不高。 .
適用數據類型:數值型和標稱型數據。

?

sigmoid函數:

?

?

梯度上升法:

梯度:

該公式將一直被迭代執行,直至達到某個停止條件為止,比如迭代次數達到某個指定值或算
法達到某個可以允許的誤差范圍。

隨機梯度上升法:

?梯度上升算法在每次更新回歸系數時都需要遍歷整個數據集, 該方法在處理100個左右的數
據集時尚可,但如果有數十億樣本和成千上萬的特征,那么該方法的計算復雜度就太高了。一種
改進方法是一次僅用一個樣本點來更新回歸系數,該方法稱為隨機梯度上升算法。由于可以在新
樣本到來時對分類器進行增量式更新,因而隨機梯度上升算法是一個在線學習算法。與 “ 在線學
相對應,一次處理所有數據被稱作是批處理” 。

梯度下降法:

你最經常聽到的應該是梯度下降算法,它與這里的梯度上升算法是一樣的,只是公式中的
加法需要變成減法。因此,對應的公式可以寫成:

?

梯度上升算法用來求函數的最大值,而梯度下降算法用來求函數的最小值。

?

logistic預測疝氣病預測病馬的死亡率代碼:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import random# 加載數據集
def loadDataSet():dataMat = []labelMat = []fr = open('./testSet.txt')for line in fr.readlines():lineData = line.strip().split()dataMat.append([1.0, float(lineData[0]), float(lineData[1])])labelMat.append(int(lineData[2]))return dataMat, labelMat# sigmoid 函數
def sigmoid(inX):return 1.0 / (1 + np.exp(-inX))# 梯度上升
def gradAscent(dataMatIn, classLabels, maxCycles):dataMatrix = np.mat(dataMatIn)labelsMatrix = np.mat(classLabels).transpose() # 轉置,將行向量轉置為列向量m, n = np.shape(dataMatrix)alpha = 0.001W = np.ones((n, 1))for i in range(maxCycles):h = sigmoid(dataMatrix * W) # (100, 1)error = labelsMatrix - h # (100, 1)W = W + alpha * dataMatrix.transpose() * error # (3, 100) * (100, 1)return W #改進版隨機梯度上升
def stocGradAscent1(dataMatrixIn, classLabels, numIter=150):dataMatrix = np.array(dataMatrixIn)m,n = np.shape(dataMatrix)weights = np.ones(n)   #initialize to all onesfor j in range(numIter):dataIndex = list(range(m))for i in range(m):alpha = 4.0/(1.0+j+i)+0.01    #apha decreases with iteration, does not randIndex = int(random.uniform(0,len(dataIndex)))#go to 0 because of the constanth = sigmoid(sum(dataMatrix[randIndex]*weights))error = classLabels[randIndex] - hweights = weights + alpha * error * dataMatrix[randIndex]del(dataIndex[randIndex])return np.mat(weights.reshape(n, 1))def plotBestFit(weights, dataMat, labelMat):dataArr = np.array(dataMat)n = np.shape(dataArr)[0]xcord1 = []; ycord1 = []xcord2 = []; ycord2 = []for i in range(n):if labelMat[i] == 1:xcord1.append(dataArr[i, 1]); ycord1.append(dataArr[i, 2])else:xcord2.append(dataArr[i, 1]); ycord2.append(dataArr[i, 2])fig = plt.figure()ax = fig.add_subplot(111)ax.scatter(xcord1, ycord1, s = 30, c = 'red', marker = 's')ax.scatter(xcord2, ycord2, s = 30, c = 'green')x = np.arange(-4.0, 4.0, 0.1)y = ((np.array((-weights[0] - weights[1] * x) / weights[2]))[0]).transpose()ax.plot(x, y)plt.xlabel('X1')plt.ylabel('X2')plt.show()# 預測
def classifyVector(inX, weights):prob = sigmoid(sum(inX * weights))if prob > 0.5:return 1.0else:return 0.0# 對訓練集進行訓練,并且對測試集進行測試
def colicTest():trainFile = open('horseColicTraining.txt')testFile = open('horseColicTest.txt')trainingSet = []; trainingLabels = []for line in trainFile.readlines():currLine = line.strip().split('\t')lineArr = []for i in range(21):lineArr.append(float(currLine[i]))trainingSet.append(lineArr)trainingLabels.append(float(currLine[21]))# 開始訓練weights = stocGradAscent1(trainingSet, trainingLabels, 400)errorCount = 0.0numTestVec = 0.0for line in testFile.readlines():numTestVec += 1.0currLine = line.strip().split('\t')lineArr = []for i in range(21):lineArr.append(float(currLine[i]))if int(classifyVector(np.array(lineArr), weights)) != int(currLine[21]):errorCount += 1.0errorRate = errorCount / float(numTestVec)print("the error rate is:%f" % errorRate)return errorRate# 多次測試求平均值
def multiTest():testTimes = 10errorRateSum = 0.0for i in range(testTimes):errorRateSum += colicTest()print("the average error rate is:%f" % (errorRateSum / float(testTimes)))multiTest()

?

轉載于:https://www.cnblogs.com/qiang-wei/p/10770285.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279624.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279624.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279624.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HDU 6343.Problem L. Graph Theory Homework-數學 (2018 Multi-University Training Contest 4 1012)

6343.Problem L. Graph Theory Homework 官方題解: 一篇寫的很好的博客: HDU 6343 - Problem L. Graph Theory Homework - [(偽裝成圖論題的)簡單數學題] 代碼: 1 //1012-6343-數學2 #include<iostream>3 #include<cstdio>4 #include<cstring>5 #include<…

Android GridView LruCache

照片墻這種功能現在應該算是挺常見了&#xff0c;在很多應用中你都可以經常看到照片墻的身影。它的設計思路其實也非常簡單&#xff0c;用一個GridView控件當作“墻”&#xff0c;然后隨著GridView的滾動將一張張照片貼在“墻”上&#xff0c;這些照片可以是手機本地中存儲的&a…

如何在Android TV上自定義推薦行

When you fire up Android TV, the first thing you see is a list of movies and shows the system thinks you’ll like. It’s often full of the latest flicks or hottest news, but sometimes it could just be things relevant to your interests and the apps you have…

遞歸 段錯誤 習題

段錯誤 遞歸里面算階乘 f(10000000)沒有輸出&#xff0c;使用gdb 顯示 SIGSEGV--段錯誤編譯后產生的可執行文件里面保存著什么&#xff1f;UNIX/Linux 用 ELFDOS下用COFFWindows用PE&#xff08;COFF擴充而得&#xff09;段&#xff08;segmentation&#xff09;二進制文件內的…

你知道你常用的dos和linux命令嗎?

功能 Linux MS-DOS 進入到該目錄 cd cd 列舉文件 ls dir 創建目錄 mkdir mkdir 清除屏幕 clear cls 復制文件 cp copy 移動文件 mv move 刪除文件 rm del 查看文件 less more 文件重命名 mv ren 比較文件內容 diff fc 查看當前路徑 pwd chd…

steam串流到手機_如何從手機將Steam游戲下載到PC

steam串流到手機Steam allows you to remotely install games from your smartphone, just like you can with a PlayStation 4 or Xbox One. You can download games to your gaming PC from anywhere, ensuring those big downloads are complete and the game is ready to p…

編寫安裝配置ftp-samba服務腳本

本腳本實例的要求如下&#xff1a; 1、公司有公共共享目錄public,所有員工均可讀寫&#xff0c;但不允許刪除其他員工的文件;不能匿名登錄 2、每部門均有共享目錄&#xff0c;部門經理可讀寫&#xff0c;部門員工可讀&#xff1b; 非本部門員工不能訪問&#xff08;caiwu、rens…

利用java實現excel轉pdf文件

在有些需求當中我們需要抓取字段并且填充到excel表格里面&#xff0c;最后將excel表格轉換成pdf格式進行輸出&#xff0c;我第一次接觸這個需求時&#xff0c;碰到幾個比較棘手的問題&#xff0c;現在一一列出并且提供解決方案。 1&#xff1a;excel轉pdf出現亂碼&#xff1a; …

Jmeter HTTP請求后響應數據顯示亂碼解決方法

Jmeter請求后結果樹里無論是text還是html響應數據顯示亂碼&#xff0c;這是因為jmeter 編碼格式配置文件默認不開啟導致的&#xff0c;解決方法如下&#xff1a; 1&#xff09;進入jmeter-***\bin目錄下&#xff0c;找到jmeter.properties文件&#xff0c;以文本文件形式打開 2…

禁用windows10更新_如何在Windows 10中禁用投影

禁用windows10更新The drop shadows on applications in the Windows 10 preview are really big and suspiciously similar to the ones in OS X, and if they aren’t your speed, you can easily remove them. We actually think they look good, but since somebody out th…

如何訪問 Service?- 每天5分鐘玩轉 Docker 容器技術(99)

前面我們已經學習了如何部署 service&#xff0c;也驗證了 swarm 的 failover 特性。不過截止到現在&#xff0c;有一個重要問題還沒有涉及&#xff1a;如何訪問 service&#xff1f;這就是本節要討論的問題。 為了便于分析&#xff0c;我們重新部署 web_server。 ① docker se…

sqlyog下載

sqlyog下載&#xff08;附注冊碼&#xff09;&#xff1a;http://www.onlinedown.net/soft/24926.htm轉載于:https://www.cnblogs.com/shujuxiong/p/9474496.html

Linux配置手冊(二)配置DHCP服務器

1.檢查是否安裝DHCP服務器軟件 2.掛在RHEL5系統光盤 3.安裝DHCP服務軟件 4.將模板配置文件復制并覆蓋現在的配置文件 5.配置修改dhcpd.conf文件 配置信息 默認租約時間 default-lease-time 最大租約時間 max-lease-time 局域網內所有主機的域名 option domain-name 客戶機所使用…

什么是Google Play保護以及如何確保Android安全?

Android is open, flexible, and all about choice. Unfortunately, that flexibility comes more potential security issues. The good news is that Google has a system in place named Play Protect that helps keep Android secure. Android開放&#xff0c;靈活且具有多…

如何使計算機為您讀取文檔

Since the beginning of the computer age, people have always enjoyed making computers talk to them. These days, that functionality is built right into Windows and you can easily use it to have your PC read documents to you. 自計算機時代開始以來&#xff0c;人…

面試中常問的List去重問題,你都答對了嗎?

2019獨角獸企業重金招聘Python工程師標準>>> 面試中經常被問到的list如何去重&#xff0c;用來考察你對list數據結構&#xff0c;以及相關方法的掌握&#xff0c;體現你的java基礎學的是否牢固。 我們大家都知道&#xff0c;set集合的特點就是沒有重復的元素。如果集…

Coolite Toolkit學習筆記五:常用控件Menu和MenuPanel

Coolite Toolkit里的Menu控件和其他的.NET Web控件不一樣&#xff0c;如果只是設計好了Menu或是通過程序初始化菜單項&#xff0c;菜單是不會呈現在界面上的&#xff0c;因為Coolite Toolkit規定Menu控件需要一個容器來做依托&#xff0c;而這個讓Menu依托的控件就是MenuPanel&…

剛接觸git,提交文件時,遇到no changes added to commit

第一次用git 在提交&#xff08;git commit -m add 文件名&#xff09;的時候&#xff0c;遇到了一個no changes added to commit&#xff0c;大體意思是沒有將改變的東西提交成功&#xff0c;查了很多博客&#xff0c;才解決這個問題&#xff0c;然后自己也做一下筆記&#…

CSS中!important的使用

本篇文章使用最新的IE10以及firefox與chrome測試&#xff08;截止2013年5月27日22:23:22&#xff09;http://www.cnblogs.com/yudy/archive/2013/05/27/3102825.html CSS的原理&#xff1a; 我們知道&#xff0c;CSS寫在不同的地方有不同的優先級&#xff0c; .css文件中的定義…

windows命令提示符_如何個性化Windows命令提示符

windows命令提示符Command line interfaces can be downright boring and always seem to miss out on the fresh coats of paint liberally applied to the rest of Windows. Here’s how to add a splash of color to Command Prompt and make it unique. 命令行界面可能非常…