預(yù)備知識及相關(guān)文檔博客
- 學(xué)習(xí)吳恩達(dá)機器學(xué)習(xí)課程筆記帮哈,并用python實現(xiàn)算法
- python numpy基本教程: numpy相關(guān)教程
- 數(shù)據(jù)來自于UCI的機器學(xué)習(xí)數(shù)據(jù)庫: UCI的機器學(xué)習(xí)數(shù)據(jù)庫
- python繪制圖形所用包matplotlib文檔: matplotlib相關(guān)教程
- 數(shù)據(jù)計算處理工具pandas相關(guān)博客: pandas相關(guān)博客
數(shù)據(jù)介紹
- 數(shù)據(jù)介紹: Auto-mpg 汽車性能相關(guān)參數(shù):
共有398個樣本娘侍,以及9個變量咖刃,分別是mpg(燃料效率)憾筏、cylinders(發(fā)動機里的氣缸數(shù)量)、displacement(發(fā)動機的位移)枫浙、horsepower(發(fā)動機的馬力古拴,有缺失值)、weight(汽車的重量)黄痪、acceleration(汽車的加速性能)、model year(汽車類型的生產(chǎn)年份)焕参、car name(汽車品牌)等等
梯度下降算法及線性回歸算法介紹
- 回歸分析:
數(shù)學(xué)意義上來說是給定一個點集油额,能夠用一條曲線去擬合之,如果這個曲線是一條直線潦嘶,那就被稱為線性回歸,線性回歸在這里也不過多解釋掂僵,這篇文章主要是為了實現(xiàn)算法。在回歸分析中幔睬,只包括一個自變量和一個因變量芹扭,即y=θ0+θ1X稱為一元線性回歸分析。若是包含多個因變量則是多元線性回歸舱卡,即y=θ0+θ1X1+θ2X2+…+θnXn。
簡單來說就是給你一堆數(shù)據(jù)矫钓,你從幾個不同變量中找出它們之間的函數(shù)關(guān)系,并求出這些匹配不同變量的系數(shù)新娜,如θ0,θ1等匆帚。 - 梯度下降算法:
梯度下降法是一種最優(yōu)化算法旁钧,它是用迭代的方法求解目標(biāo)函數(shù)得到最優(yōu)解吸重,是在cost function(成本函數(shù))的基礎(chǔ)上歪今,利用梯度迭代求出局部最優(yōu)解嚎幸。
這里不過多解釋寄猩,下面實現(xiàn)代碼時會給出公式推導(dǎo)。
算法實現(xiàn)
-
相關(guān)數(shù)據(jù)截圖:
UCI的機器學(xué)習(xí)數(shù)據(jù)庫
- 網(wǎng)站的數(shù)據(jù)是以csv文件形式給出的替废,因此可以用pandas的
read_csv()
讀取泊柬,但由于這個網(wǎng)站的數(shù)據(jù)沒有表頭,所以我們在讀取時要加上表頭兽赁,下面是代碼,并且后面會針對部分代碼給出解釋
from io import StringIO
from urllib import request
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import ssl
import pandas as pd
import numpy as np
import linearRegrassion as lg
ssl._create_default_https_context = ssl._create_unverified_context
names =["mpg","cylinders","displacement","horsepower",
"weight","acceleration","model year","origin","car name"]
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data'
s = request.urlopen(url).read().decode('utf8')
dataFile = StringIO(s)
cReader = pd.read_csv(dataFile,delim_whitespace=True,names=names) # 將流 轉(zhuǎn)換為可迭代的 reader(csv row)
- names是加上的表頭惊科,作為
read_csv()
的參數(shù)傳給它 -
read_csv()
還有一個參數(shù)filepath_or_buffer :
str亮钦,pathlib。str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)
可以是URL蜂莉,可用URL類型包括:http, ftp, s3和文件 -
這里要注意一下,直接讀取url:
pd.read_csv(url,delim_whitespace=True,names=names)
會報urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)>
的錯誤
因此要import ssl
并加上下面這幾行語句
ssl._create_default_https_context = ssl._create_unverified_context
s = request.urlopen(url).read().decode('utf8')
dataFile = StringIO(s) # 將字符串轉(zhuǎn)換為 StringIO對象,使其具有文件屬性
-
觀察加載后的數(shù)據(jù)(如下圖)男公,截圖較短,你可以對照上下表或是元數(shù)據(jù)集觀察
加上表頭后的數(shù)據(jù)
我們可以發(fā)現(xiàn),有一定變化幅度并且比較相關(guān)聯(lián)的幾個量是mpg(燃料效率)澄阳,displacement(發(fā)動機的位移)踏拜,horsepower(發(fā)動機的馬力,有缺失值)速梗,acceleration(汽車的加速性能)
通常情況下,我們關(guān)注汽車性能時主要看它的加速性能枕赵,所以我們選取acceleration為關(guān)鍵性能位隶,考量mpg拷窜,displacement對其的影響涧黄,以此做一個回歸分析
- 其實horsepower與加速性能也很相關(guān),但由于有缺失值懊昨,需要額外操作挽鞠,在此我們還是要把重心放到實現(xiàn)算法本身上,所以先不予考慮
- 我們首先將上面代碼得到的數(shù)據(jù)集繪制散點圖信认,觀察一下它的分布,代碼如下:
ax = plt.subplot(111, projection='3d') # 創(chuàng)建一個三維的繪圖工程
ax.scatter(cReader["mpg"][:100],cReader["displacement"][:100],cReader["acceleration"][:100],c='y')
#根據(jù)不同數(shù)據(jù)范圍散點取不同顏色以便于區(qū)分
ax.scatter(cReader["mpg"][100:250],cReader["displacement"][100:250],cReader["acceleration"][100:250],c='r')
ax.scatter(cReader["mpg"][250:],cReader["displacement"][250:],cReader["acceleration"][250:],c='b')
ax.set_zlabel('acceleration') # 坐標(biāo)軸
ax.set_ylabel('displacement')
ax.set_xlabel('mpg')
plt.show()
# 繪制mpg和displacement的二維散點圖其掂,其實也是三維散點圖在x,y平面上的投影
plt.scatter(cReader["mpg"],cReader["displacement"])
plt.xlabel('mpg')
plt.ylabel('displacement')
plt.show()
得到的散點圖:
3d散點圖.png
mpg和displacement的二維散點圖:
Figure_2d.png
- 在這篇文章里我們介紹了一些準(zhǔn)備知識潦蝇,并且通過python的pandas模塊獲取了相關(guān)數(shù)據(jù)集并將其可視化,在下面的系列文章里我會介紹如何處理這些數(shù)據(jù)并且實現(xiàn)算法:
第二篇已更新: Python實現(xiàn)梯度下降求多元線性回歸(二)