99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀使用Python進(jìn)行線性回歸
使用Python進(jìn)行線性回歸
2017-05-09
收藏

使用Python進(jìn)行線性回歸

線性回歸是最簡(jiǎn)單同時(shí)也是最常用的一個(gè)統(tǒng)計(jì)模型。線性回歸具有結(jié)果易于理解,計(jì)算量小等優(yōu)點(diǎn)。如果一個(gè)簡(jiǎn)單的線性回歸就能取得非常不錯(cuò)的預(yù)測(cè)效果,那么就沒(méi)有必要采用復(fù)雜精深的模型了。
今天,我們一起來(lái)學(xué)習(xí)使用Python實(shí)現(xiàn)線性回歸的幾種方法:
    通過(guò)公式編寫矩陣運(yùn)算程序;
    通過(guò)使用機(jī)器學(xué)習(xí)庫(kù)sklearn;
    通過(guò)使用statmodels庫(kù)。
這里,先由簡(jiǎn)至繁,先使用sklearn實(shí)現(xiàn),再講解矩陣推導(dǎo)實(shí)現(xiàn)。
1.使用scikit-learn進(jìn)行線性回歸
設(shè)置工作路徑
#
import os
os.getcwd()
os.chdir('D:\my_python_workfile\Project\Writting')

加載擴(kuò)展包

import pandas as pd
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt

載入數(shù)據(jù)并可視化分析

這里,為了簡(jiǎn)單起見,使用sklearn中自帶的數(shù)據(jù)集鳶尾花數(shù)據(jù)iris進(jìn)行分析,探索『花瓣寬』和『花瓣長(zhǎng)』之間的線性關(guān)系。

from sklearn.datasets import load_iris
# load data
iris = load_iris()
# Define a DataFrame
df = pd.DataFrame(iris.data, columns = iris.feature_names)
# take a look
df.head()
#len(df)

# correlation
df.corr()

  

# rename the column name

df.columns = ['sepal_length','sepal_width','petal_length','petal_width']
df.columns

Index([u'sepal_length', u'sepal_width', u'petal_length', u'petal_width'], dtype='object')

plt.matshow(df.corr())

由上面分析可知,花瓣長(zhǎng)sepal length和花瓣寬septal width有著非常顯著的相關(guān)性。
下面,通過(guò)線性回歸進(jìn)一步進(jìn)行驗(yàn)證。
# save image
fig,ax = plt.subplots(nrows = 1, ncols = 1)
ax.matshow(df.corr())
fig.savefig('./image/iris_corr.png')

建立線性回歸模型

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

lr = LinearRegression()
X = df[['petal_length']]
y = df['petal_width']
lr.fit(X,y)
# print the result
lr.intercept_,lr.coef_

(-0.3665140452167297, array([ 0.41641913]))

# get y-hat
yhat = lr.predict(X = df[['petal_length']])

# MSE
mean_squared_error(df['petal_width'],yhat)

# lm plot
plt.scatter(df['petal_length'],df['petal_width'])
plt.plot(df['petal_length'],yhat)

#save image
plt.savefig('./image/iris_lm_fit.png')

2.使用statmodels庫(kù)

#import statsmodels.api as sm
import statsmodels.formula.api as sm

linear_model = sm.OLS(y,X)

results = linear_model.fit()

results.summary()

OLS Regression Results 


3.使用公式推導(dǎo)
線性回歸,即是使得如下目標(biāo)函數(shù)最小化:

使用最小二乘法,不難得到β的估計(jì):

從而,我們可以根據(jù)此公式,編寫求解β^的函數(shù)。
from numpy import *

#########################
# 定義相應(yīng)的函數(shù)進(jìn)行矩陣運(yùn)算求解。
def standRegres(xArr, yArr):
    xMat = mat(xArr)
    yMat = mat(yArr).T
    xTx = xMat.T * xMat
    if linalg.det(xTx) == 0.0:
        print "this matrix is singular, cannot do inverse!"
        return NA
    else :
        ws = xTx.I * (xMat.T * yMat)
        return ws

# test
x0 = np.ones((150,1))
x0 = pd.DataFrame(x0)
X0 = pd.concat([x0,X],axis  = 1)
standRegres(X0,y)

matrix([[-0.36651405],
        [ 0.41641913]])

結(jié)果一致。

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }