五、邏輯回歸實驗分析

所有代碼塊都是在Jupyter Notebook下進行調試運行,前后之間都相互關聯。
文中所有代碼塊所涉及到的函數里面的詳細參數均可通過scikit-learn官網API文檔進行查閱,這里我只寫下每行代碼所實現的功能,參數的調整讀者可以多進行試驗調試。多動手!!!

一、簡介

線性回歸是回歸問題,可以得到一個具體的回歸值;而邏輯回歸是分類問題,可以得到將兩種類別物體分類。
邏輯回歸借助sigmoid函數進行了數值映射,將求出的值轉換為0-1之間的概率,通過比較相關概率從而實現分類任務。

導包

import numpy as np
import os
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
import warnings
warnings.filterwarnings('ignore')
np.random.seed(42)

二、sigmoid函數

t = np.linspace(-10, 10, 100)
sig = 1 / (1 + np.exp(-t))
plt.figure(figsize=(9, 3))
plt.plot([-10, 10], [0, 0], "k-")
plt.plot([-10, 10], [0.5, 0.5], "k:")
plt.plot([-10, 10], [1, 1], "k:")
plt.plot([0, 0], [-1.1, 1.1], "k-")
plt.plot(t, sig, "b-", linewidth=2, label=r"$\sigma(t) = \frac{1}{1 + e^{-t}}$")
plt.xlabel("t")
plt.legend(loc="upper left", fontsize=20)
plt.axis([-10, 10, -0.1, 1.1])
plt.title('Figure 4-21. Logistic function')
plt.show()

在這里插入圖片描述
其對應的相關推導公式如下:在這里插入圖片描述

三、鳶尾花數據集

這個鳶尾花數據集是sklearn庫里面自帶的數據集,主要由三個類別的花,每種類別的花都有四個特征參數。
邏輯回歸可以實現二分類問題,對于三分類問題,只需要將剩余其他兩種類別的花當成一種(當成其他即可),依次分別進行三次二分類就可以實現三分類的任務。

Ⅰ,加載iris(鳶尾花)數據集

from sklearn import datasets
iris = datasets.load_iris()
list(iris.keys())#查看數據集中都有哪些屬性可以調用,這里主要使用data---x,target---y
"""
['data','target','frame','target_names','DESCR','feature_names','filename']
"""

Ⅱ,查看iris數據集的詳細信息描述

print (iris.DESCR)#當前iris鳶尾花數據集的所有信息的描述
"""
.. _iris_dataset:Iris plants dataset
--------------------**Data Set Characteristics:**:Number of Instances: 150 (50 in each of three classes):Number of Attributes: 4 numeric, predictive attributes and the class:Attribute Information:- sepal length in cm- sepal width in cm- petal length in cm- petal width in cm- class:- Iris-Setosa- Iris-Versicolour- Iris-Virginica:Summary Statistics:============== ==== ==== ======= ===== ====================Min  Max   Mean    SD   Class Correlation============== ==== ==== ======= ===== ====================sepal length:   4.3  7.9   5.84   0.83    0.7826sepal width:    2.0  4.4   3.05   0.43   -0.4194petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)============== ==== ==== ======= ===== ====================:Missing Attribute Values: None:Class Distribution: 33.3% for each of 3 classes.:Creator: R.A. Fisher:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov):Date: July, 1988The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other... topic:: References- Fisher, R.A. "The use of multiple measurements in taxonomic problems"Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions toMathematical Statistics" (John Wiley, NY, 1950).- Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.(Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.- Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New SystemStructure and Classification Rule for Recognition in Partially ExposedEnvironments".  IEEE Transactions on Pattern Analysis and MachineIntelligence, Vol. PAMI-2, No. 1, 67-71.- Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactionson Information Theory, May 1972, 431-433.- See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS IIconceptual clustering system finds 3 classes in the data.- Many, many more ..."""

Ⅲ,選出其中一種類別的花,將其余兩種花分為一類

X = iris['data'][:,3:]#選出所有數據中的其中一個特征
y = (iris['target'] == 2).astype(np.int)#將這種花設定為1,剩下的兩種花設定為0
y#很顯然,前面的0為其余兩種花,后面的1是當前這種花
"""
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
"""

Ⅳ,訓練模型及展示

①模型訓練
from sklearn.linear_model import LogisticRegression#導入邏輯回歸包
log_res = LogisticRegression()#實例化
log_res.fit(X,y)#傳入參數訓練模型
"""
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='warn',n_jobs=None, penalty='l2', random_state=None, solver='warn',tol=0.0001, verbose=0, warm_start=False)
"""
X_new = np.linspace(0,3,1000).reshape(-1,1)#從0-3取1000個數
y_proba = log_res.predict_proba(X_new)#得出預測結果
y_proba#得出1000個樣本通過模型得出的概率值,左邊表示屬于當前類別的概率,右邊表示不屬于當前類別的概率
"""
array([[0.98554411, 0.01445589],[0.98543168, 0.01456832],[0.98531838, 0.01468162],...,[0.02618938, 0.97381062],[0.02598963, 0.97401037],[0.02579136, 0.97420864]])
"""
②可視化展示
plt.figure(figsize=(12,5))#整個一張圖繪制
decision_boundary = X_new[y_proba[:,1]>=0.5][0]#指定決策邊界所處的位置
plt.plot([decision_boundary,decision_boundary],[-1,2],'k:',linewidth = 2)#將邊界從上往下繪制
plt.plot(X_new,y_proba[:,1],'g-',label = 'Iris-Virginica')#是當前類別的花
plt.plot(X_new,y_proba[:,0],'b--',label = 'Not Iris-Virginica')#不是當前類別的花
plt.arrow(decision_boundary,0.08,-0.3,0,head_width = 0.05,head_length=0.1,fc='b',ec='b')#指定箭頭
plt.arrow(decision_boundary,0.92,0.3,0,head_width = 0.05,head_length=0.1,fc='g',ec='g')
plt.text(decision_boundary+0.02,0.15,'Decision Boundary',fontsize = 16,color = 'k',ha='center')#添加字符串指定決策邊界
plt.xlabel('Peta width(cm)',fontsize = 16)#x軸標簽,花瓣寬度
plt.ylabel('y_proba',fontsize = 16)#y軸標簽,最終預測的概率值
plt.axis([0,3,-0.02,1.02])#設置x和y軸的取值范圍
plt.legend(loc = 'center left',fontsize = 16)#顯示標簽,放在中間偏左位置

在這里插入圖片描述
遇到不太熟悉的函數,比如畫箭頭arrow,可以通過查閱幫助文檔進行解決

print (help(plt.arrow))
"""
Help on function arrow in module matplotlib.pyplot:arrow(x, y, dx, dy, **kwargs)Add an arrow to the axes.This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``.Parameters----------x, y : floatThe x/y-coordinate of the arrow base.dx, dy : floatThe length of the arrow along x/y-direction.Returns-------arrow : `.FancyArrow`The created `.FancyArrow` object.Other Parameters----------------**kwargsOptional kwargs (inherited from `.FancyArrow` patch) control thearrow construction and properties:Constructor arguments*width*: float (default: 0.001)width of full arrow tail*length_includes_head*: bool (default: False)True if head is to be counted in calculating the length.*head_width*: float or None (default: 3*width)total width of the full arrow head*head_length*: float or None (default: 1.5 * head_width)length of arrow head*shape*: ['full', 'left', 'right'] (default: 'full')draw the left-half, right-half, or full arrow*overhang*: float (default: 0)fraction that the arrow is swept back (0 overhang meanstriangular shape). Can be negative or greater than one.*head_starts_at_zero*: bool (default: False)if True, the head starts being drawn at coordinate 0instead of ending at coordinate 0.Other valid kwargs (inherited from :class:`Patch`) are:agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: float or Noneanimated: boolantialiased: unknowncapstyle: {'butt', 'round', 'projecting'}clip_box: `.Bbox`clip_on: boolclip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] color: colorcontains: callableedgecolor: color or None or 'auto'facecolor: color or Nonefigure: `.Figure`fill: boolgid: strhatch: {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}in_layout: booljoinstyle: {'miter', 'round', 'bevel'}label: objectlinestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}linewidth: float or None for default path_effects: `.AbstractPathEffect`picker: None or bool or float or callablerasterized: bool or Nonesketch_params: (scale: float, length: float, randomness: float) snap: bool or Nonetransform: `.Transform`url: strvisible: boolzorder: floatNotes-----The resulting arrow is affected by the axes aspect ratio and limits.This may produce an arrow whose head is not square with its stem. Tocreate an arrow whose head is square with its stem,use :meth:`annotate` for example:>>> ax.annotate("", xy=(0.5, 0.5), xytext=(0, 0),...             arrowprops=dict(arrowstyle="->"))None
"""

Ⅴ,笛卡爾積(棋盤操作)樣例

x0,x1 = np.meshgrid(np.linspace(1,2,2).reshape(-1,1),np.linspace(10,20,3).reshape(-1,1))#笛卡爾積
x0
"""
array([[1., 2.],[1., 2.],[1., 2.]])
"""
x1
"""
array([[10., 10.],[15., 15.],[20., 20.]])
"""
np.c_[x0.ravel(),x1.ravel()]#拼接
"""
array([[ 1., 10.],[ 2., 10.],[ 1., 15.],[ 2., 15.],[ 1., 20.],[ 2., 20.]])
"""

從運行結果也不難看出,笛卡爾積的操作就類似一個棋盤,(1,2,2)也就是從1-2之間選取2個數賦值給x0,(10,20,3)從10到20之間選取3個數賦值給x1。
拼接之后即可得到這幾個數的全部的排列組合情況。

Ⅵ,分類決策邊界

X[:,0].min(),X[:,0].max()#獲取標簽為0的數據的大致范圍為后續的畫圖做參考
"""
(1.0, 6.9)
"""
X[:,1].min(),X[:,1].max()#獲取標簽為1的數據的大致范圍為后續的畫圖做參考
"""
(0.1, 2.5)
"""
x0,x1 = np.meshgrid(np.linspace(2.9,7,500).reshape(-1,1),np.linspace(0.8,2.7,200).reshape(-1,1))
X_new = np.c_[x0.ravel(),x1.ravel()]#拼接
X_new#獲得測試數據
"""
array([[2.9       , 0.8       ],[2.90821643, 0.8       ],[2.91643287, 0.8       ],...,[6.98356713, 2.7       ],[6.99178357, 2.7       ],[7.        , 2.7       ]])
"""
X_new.shape#100000=500*200
"""
(100000, 2)
"""
y_proba = log_res.predict_proba(X_new)#通過訓練好的模型去預測測試數據的概率值
x0.shape#維度參數得與后續z軸一致
"""
(200, 500)
"""
x1.shape#維度參數得與后續z軸一致
"""
(200, 500)
"""
plt.figure(figsize=(10,4))#繪制圖片的框架大小
plt.plot(X[y==0,0],X[y==0,1],'bs')#展示數據點
plt.plot(X[y==1,0],X[y==1,1],'g^')#展示數據點zz = y_proba[:,1].reshape(x0.shape)#繪制z軸
contour = plt.contour(x0,x1,zz,cmap=plt.cm.brg)#繪制等高線
plt.clabel(contour,inline = 1)#等高線上添加概率值
plt.axis([2.9,7,0.8,2.7])#限制x和y軸的取值范圍
plt.text(3.5,1.5,'NOT Vir',fontsize = 16,color = 'b')#展示標簽
plt.text(6.5,2.3,'Vir',fontsize = 16,color = 'g')#展示標簽

在這里插入圖片描述

四、Softmax

如何實現之間對多列別進行分類,這里Softmax就派上用場了。
在這里插入圖片描述
由公式很明顯可知,softmax實際上就是先對數據求指數,然后目的就是為了拉大差距,之后再進行歸一化操作。
損失函數也就是對數,0-1之間聯想下對數函數。

X = iris['data'][:,(2,3)]#獲取數據
y = iris['target']#獲取標簽
softmax_reg = LogisticRegression(multi_class = 'multinomial',solver='lbfgs')#指定多分類,指定求解的方法
softmax_reg.fit(X,y)#訓練
"""
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='multinomial',n_jobs=None, penalty='l2', random_state=None, solver='lbfgs',tol=0.0001, verbose=0, warm_start=False)
"""
softmax_reg.predict([[5,2]])#二維數據
"""
array([2])
"""
softmax_reg.predict_proba([[5,2]])#預測看看有幾個概率值,也就是分成了幾類,也就證實了這是個多分類的任務
"""
array([[2.43559894e-04, 2.14859516e-01, 7.84896924e-01]])
"""
#繪制等高線
x0, x1 = np.meshgrid(np.linspace(0, 8, 500).reshape(-1, 1),np.linspace(0, 3.5, 200).reshape(-1, 1),)
X_new = np.c_[x0.ravel(), x1.ravel()]y_proba = softmax_reg.predict_proba(X_new)
y_predict = softmax_reg.predict(X_new)zz1 = y_proba[:, 1].reshape(x0.shape)
zz = y_predict.reshape(x0.shape)plt.figure(figsize=(10, 4))
plt.plot(X[y==2, 0], X[y==2, 1], "g^", label="Iris-Virginica")
plt.plot(X[y==1, 0], X[y==1, 1], "bs", label="Iris-Versicolor")
plt.plot(X[y==0, 0], X[y==0, 1], "yo", label="Iris-Setosa")from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])plt.contourf(x0, x1, zz, cmap=custom_cmap)
contour = plt.contour(x0, x1, zz1, cmap=plt.cm.brg)
plt.clabel(contour, inline=1, fontsize=12)
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
plt.legend(loc="center left", fontsize=14)
plt.axis([0, 7, 0, 3.5])
plt.show()

在這里插入圖片描述

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

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

相關文章

二叉搜索樹的插入、刪除、修剪、構造操作(leetcode701、450、669、108)

目錄1、leetcode 701. 二叉搜索樹中的插入操作1、題目2、遞歸法3、迭代法2、leetcode 450. 二叉搜索樹中的插入操作1、題目2、思路遞歸法3、迭代法4、刪除結點的兩個方法以及注意點3、leetcode 669. 修剪二叉搜索樹1、題目2、思考與遞歸3、迭代法4、leetcode 108. 將有序數組轉…

Memcached查看和清理

1.一種telnet localhost 11211 #登陸stats #查看狀態flush_all #清理quit #退出2.又學到一個:echo flush_all | nc localhost 112113.1、數據存儲(假設key為test,value為12345) printf "set test 0 1 5\r\n12345\r\n" | nc localhost 11211STORED2.數據取回(假設key為…

模擬退火算法解決np_P和NP問題與解決方案| 演算法

模擬退火算法解決npP問題 (P Problems) P is the set of all the decision problems solvable by deterministic algorithms in polynomial time. P是多項式時間內確定性算法可解決的所有決策問題的集合。 NP問題 (NP Problems) NP is the set of all the decision problems t…

POJ2251Dungeon Master

http://poj.org/problem?id2251 題意 : 就是迷宮升級版,從以前的一個矩陣也就是一層,變為現在的L層," . "是可以走,但是“#”不可以走,從S走到E,求最短的路徑,若是找不到…

六、聚類算法

一、聚類概念 1,通俗易懂而言,聚類主要運用于無監督學習中,也就是將沒有標簽的東西如何分為幾堆兒。 2,無監督學習即沒有標簽,不知道這些玩意到底是啥。當然,有監督學習就是由標簽,我們是提前知…

Apache服務器通過.htaccess文件設置防盜鏈

用戶經常面對的一個問題就是服務器的流量問題,而站點文件被盜鏈是其中最為主要的部分。所謂盜鏈,是指其他網站直接鏈接我們網站上的文件,一般來 說,盜鏈的對象大多為很耗帶寬的大體積文件,如圖片、視頻等。這樣造成的后…

【C++grammar】string類和array類

目錄1、C11的string類1、創建 string 對象2、追加字符串append函數3、為字符串賦值assign函數4、at, clear, erase, and empty函數5、比較字符串compare()6、獲取子串at() 、substr()函數7、搜索字符串find()8、插入和替換字符串insert() 、replace()9、字符串運算符10、string…

六、聚類算法實戰

所有代碼塊都是在Jupyter Notebook下進行調試運行,前后之間都相互關聯。 文中所有代碼塊所涉及到的函數里面的詳細參數均可通過scikit-learn官網API文檔進行查閱,這里我只寫下每行代碼所實現的功能,參數的調整讀者可以多進行試驗調試。多動手…

超圖軟件試用許可操作步驟_軟件中的操作步驟

超圖軟件試用許可操作步驟The software comprises of three things: Program code, Documentation, and the Operating Procedures. The Program code is the entire software code. The Documentation is produced while the development of the software itself for the time…

mysql 2013錯誤

參考資料: 自由呼吸的世界-mysql 2013錯誤解決 windows下mysql日志文件開啟 今天,莫名其妙的來了個mysql 2013錯誤,導致無法登陸mysql gui工具,而且dos也進不去,提示ping 127.0.0.1,百度google后: 這是在使…

【嵌入式系統】STM32配置FreeRTOS以及利用多線程完成流水燈、按鍵、蜂鳴器、數碼管工作

目錄1、利用STM32CubeMX配置FreeRTOS2、完成流水燈、按鍵、蜂鳴器數碼管工作1、在gpio.c和.h文件里面書寫并聲明按鍵掃描和led、數碼管子程序2、在freertos.c文件里面設置全局變量并且在各自任務中載入程序3、關于FreeRTOS的注意事項1、利用STM32CubeMX配置FreeRTOS 假設我們之…

學好Java開發的關鍵七步

在學習編程的過程中,我覺得不止要獲得課本的知識,更多的是通過學習技術知識提高解決問題的能力,這樣我們才能走在最前方,本文主要講述如何學好Java開發的關鍵七步,更多Java專業知識,廣州瘋狂Java培訓為你講…

css模糊_如何使用CSS模糊圖像?

css模糊Introduction: 介紹: Sometimes even the professional developers tend to forget the various basic properties which can be applied to solve very simple problems, therefore the fundamentals of developing a website or web page should be very …

七、決策樹算法和集成算法

一、決策樹算法 Ⅰ,樹模型 決策樹:從根節點開始一步步走到葉子節點(決策) 所有的數據最終都會落到葉子節點,既可以做分類也可以做回歸 對于分類:是由眾數決定的,例如爺爺奶奶媽媽都是負數&…

leetcode 538. 把二叉搜索樹轉換為累加樹 思考分析

題目 給出二叉 搜索 樹的根節點,該樹的節點值各不相同,請你將其轉換為累加樹(Greater Sum Tree),使每個節點 node 的新值等于原樹中大于或等于 node.val 的值之和。 提醒一下,二叉搜索樹滿足下列約束條件&…

SQL中GROUP BY語句與HAVING語句的使用

最近在學習SQL Server相關知識,一直不知道怎么使用GROUP BY語句,經過研究和練習,終于明白如何使用了,在此記錄一下同時添加了一個自己舉的小例子,通過寫這篇文章來加深下自己學習的效果,還能和大家分享下&a…

scala語言示例_var關鍵字與Scala中的示例

scala語言示例Scala var關鍵字 (Scala var keyword) The var Keyword in scala is used to declare variables. As Scala does not require explicit declaration of data type of the variable, var keyword is used. The variable declared using the var keyword as mutable…

八、決策樹算法實驗可視化展示

一、樹模型的可視化展示 官網下載安裝包 右擊管理員身份運行,直接下一步即可。 配置環境變量: 將安裝好的可視化軟件的bin文件夾路徑添加到系統環境變量Path下即可 打開cmd,輸入dot -version,出現相關信息即安裝成功 二、決策…

關于在頁面中針對不同版本的IE瀏覽器實現不同的JS或者CSS樣式

一般會用到<!--[if IE]>這里是正常的html代碼<![endif]--> 條件注釋只能在windows Internet Explorer(以下簡稱IE)下使用&#xff0c;因此我們可以通過條件注釋來為IE添加特別的指令。因為這只是IE瀏覽器支持的注釋。 1&#xff0c;條件注釋的基本結構和HTML的注釋…

機器學習筆記:PCA的簡單理解以及應用建議

用notability做的筆記&#xff0c;比較隨意&#xff0c;對于第五點的PCA錯誤使用需要特別強調。 目錄1、PCA與線性回歸2、PCA主成分數量選擇3、壓縮重現4、PCA應用建議5、PCA的錯誤使用1、PCA與線性回歸 2、PCA主成分數量選擇 3、壓縮重現 4、PCA應用建議 5、PCA的錯誤使用