機器學(xué)習——線性回歸波士頓房價代碼理解(四)

摘要:關(guān)于簡書 - 寫文章 (jianshu.com)的代碼理解

參考:

(1)為什么一些機器學(xué)習模型需要對數(shù)據(jù)進行歸一化? - zhanlijun - 博客園 (cnblogs.com)

(2)(3條消息) 關(guān)于相關(guān)系數(shù)的一些理解誤區(qū)_witforeveryang的專欄-CSDN博客_皮爾遜相關(guān)系數(shù)的缺點

1.機器學(xué)習過程

(1)Look at the big picture

(2)Get the data

(3)Discover and visualize the data to gain insights

(4)Prepared the data for machine learning algorithms

(5)Select a model and train it

(6)Fine-tune ur model

(7)Present ur solution

(8)Launch, monitor and maintain ur system

7.整理回顧

通過波士頓房價的代碼,總算是畫出了一些圖,輸出了一些結(jié)果。個人對機器學(xué)習的過程也有了一些新的理解。簡單來說就是不停的調(diào)用各種包,常見的有model_selection用于數(shù)據(jù)集的分割,其中又有train_test_split包和KFold包兩種不同的處理方式,當然還有第三種自助法,后續(xù)再說;preprocessing包用于數(shù)據(jù)預(yù)處理,可對數(shù)據(jù)進行標準化與歸一化處理;linear_model線性模型里有線性回歸模型;每一個機器學(xué)習算法都是一個類,使用時需要實例化,使用不同的訓(xùn)練集可以訓(xùn)練出不同的實例,他們的預(yù)測結(jié)果也是不一樣的;可以使用metrics里的函數(shù)對模型進行評估,選出最優(yōu)的模型,或者選出最好的參數(shù)(參數(shù)調(diào)整也是很重要的一步,同一個訓(xùn)練集可以訓(xùn)練出參數(shù)不同的多個模型,至于選什么參數(shù)最好,還需要后續(xù)的優(yōu)化處理)。

7.1關(guān)于“為什么”

為什么要歸一化?

維基百科里對這個問題有如下解釋:1)歸一化后加快了梯度下降求最優(yōu)解的速度;2)歸一化有可能提高精度。至于為什么有這些優(yōu)點,為什么一些機器學(xué)習模型需要對數(shù)據(jù)進行歸一化? - zhanlijun - 博客園 (cnblogs.com)這篇文章講的很詳細。

為什么要計算相關(guān)系數(shù)?

簡書 - 寫文章 (jianshu.com)文章中給出了在csdn上找到的一個代碼,后續(xù)的幾篇理解里的代碼與這篇文章中的代碼不完全相同,這是因為有些內(nèi)容個人認為不太準確。比如相關(guān)系數(shù)。閱讀了(3條消息) 關(guān)于相關(guān)系數(shù)的一些理解誤區(qū)_witforeveryang的專欄-CSDN博客_皮爾遜相關(guān)系數(shù)的缺點之后,對相關(guān)系數(shù)有了更好的理解,這篇文章大家可以參考,結(jié)論就是不一定所有的線性回歸都需要計算相關(guān)系數(shù)。

7.2代碼

所有代碼以及歸一化和計算相關(guān)系數(shù)后的評估指標的對比(我發(fā)現(xiàn)啥都不做得出的最終模型是最好的,真是非常amazing,不知道是不是我處理有問題,歡迎大家指正)



#!/usr/bin/env?python

#?coding:?utf-8

#?In[1]:

import?numpy?as?np

import?pandas?as?pd

from?matplotlib?import?pyplot?as?plt

from?sklearn?import?datasets

from?sklearn?import?preprocessing

from?sklearn.model_selection?import?train_test_split

from?sklearn.linear_model?import?LinearRegression

from?sklearn.metrics?import?r2_score,?mean_squared_error

#?In[2]:

plt.rcParams['font.sans-serif']?=?['SimHei']

#?In[7]:

def?figure(title,?*datalist):

????plt.figure(facecolor='gray',?figsize=(20,?10))

????for?v?in?datalist:

????????plt.plot(v[0],?'-',?label=v[1],?linewidth=2)

????????plt.plot(v[0],?'o')


????plt.grid()

????plt.title(title,?fontsize=20)

????plt.legend(fontsize=16)

????plt.show()

#?In[3]:

boston?=?datasets.load_boston()

data?=?pd.DataFrame(boston.data,?columns=boston.feature_names)

data['Price']?=?boston.target

data

#?In[24]:

data.corr()['Price']

#?In[21]:

new_data?=?data.T[abs(data.corr()['Price'])>=0.5].T

new_data

#?In[15]:

x?=?boston.data

y?=?boston.target

x_train,?x_test,?y_train,?y_test?=?train_test_split(x,?y,?test_size=0.2,?random_state=0)

lr1?=?LinearRegression()

lr1.fit(x_train,?y_train)

y_train_pred?=?lr1.predict(x_train)

y_test_pred?=?lr1.predict(x_test)

print("The?mean_sqared_error?for?train?set?is:?{:.4f}".format(mean_squared_error(y_train,?y_train_pred)))

print("The?mean_sqared_error?for?test?set?is:?{:.4f}".format(mean_squared_error(y_test,?y_test_pred)))

print("The?r2_core?for?train?set?is:?{:.4f}".format(lr1.score(x_train,?y_train)))

print("The?r2_core?for?test?set?is:?{:.4f}".format(lr1.score(x_test,?y_test)))

figure("預(yù)測值與真實值圖模型的$R^2={:.4f}$".format(r2_score(y_test,?y_test_pred)),?[y_test,?"ture"],?[y_test_pred,?"pred"])

#?In[17]:

x?=?boston.data

y?=?boston.target

x_train,?x_test,?y_train,?y_test?=?train_test_split(x,?y,?test_size=0.2,?random_state=0)

min_max_scaler?=?preprocessing.MinMaxScaler(feature_range=(0,?1))

x_train?=?min_max_scaler.fit_transform(x_train)

x_test=?min_max_scaler.fit_transform(x_test)

y_train?=?min_max_scaler.fit_transform(y_train.reshape(-1,?1))

y_test?=?min_max_scaler.fit_transform(y_test.reshape(-1,?1))

lr2?=?LinearRegression()

lr2.fit(x_train,?y_train)

y_train_pred?=?lr2.predict(x_train)

y_test_pred?=?lr2.predict(x_test)

print("The?mean_sqared_error?for?train?set?is:?{:.4f}".format(mean_squared_error(y_train,?y_train_pred)))

print("The?mean_sqared_error?for?test?set?is:?{:.4f}".format(mean_squared_error(y_test,?y_test_pred)))

print("The?r2_core?for?train?set?is:?{:.4f}".format(lr2.score(x_train,?y_train)))

print("The?r2_core?for?test?set?is:?{:.4f}".format(lr2.score(x_test,?y_test)))

figure("預(yù)測值與真實值圖模型的$R^2={:.4f}$".format(r2_score(y_test,?y_test_pred)),?[y_test,?"ture"],?[y_test_pred,?"pred"])

#?In[22]:

x?=?np.array(new_data.iloc[:,?:-1])

y?=?np.array(new_data.iloc[:,?-1:])

x_train,?x_test,?y_train,?y_test?=?train_test_split(x,?y,?test_size=0.2,?random_state=0)

lr1?=?LinearRegression()

lr1.fit(x_train,?y_train)

y_train_pred?=?lr1.predict(x_train)

y_test_pred?=?lr1.predict(x_test)

print("The?mean_sqared_error?for?train?set?is:?{:.4f}".format(mean_squared_error(y_train,?y_train_pred)))

print("The?mean_sqared_error?for?test?set?is:?{:.4f}".format(mean_squared_error(y_test,?y_test_pred)))

print("The?r2_core?for?train?set?is:?{:.4f}".format(lr1.score(x_train,?y_train)))

print("The?r2_core?for?test?set?is:?{:.4f}".format(lr1.score(x_test,?y_test)))

figure("預(yù)測值與真實值圖模型的$R^2={:.4f}$".format(r2_score(y_test,?y_test_pred)),?[y_test,?"ture"],?[y_test_pred,?"pred"])

#?In[23]:

x?=?np.array(new_data.iloc[:,?:-1])

y?=?np.array(new_data.iloc[:,?-1:])

x_train,?x_test,?y_train,?y_test?=?train_test_split(x,?y,?test_size=0.2,?random_state=0)

min_max_scaler?=?preprocessing.MinMaxScaler(feature_range=(0,?1))

x_train?=?min_max_scaler.fit_transform(x_train)

x_test=?min_max_scaler.fit_transform(x_test)

y_train?=?min_max_scaler.fit_transform(y_train.reshape(-1,?1))

y_test?=?min_max_scaler.fit_transform(y_test.reshape(-1,?1))

lr2?=?LinearRegression()

lr2.fit(x_train,?y_train)

y_train_pred?=?lr2.predict(x_train)

y_test_pred?=?lr2.predict(x_test)

print("The?mean_sqared_error?for?train?set?is:?{:.4f}".format(mean_squared_error(y_train,?y_train_pred)))

print("The?mean_sqared_error?for?test?set?is:?{:.4f}".format(mean_squared_error(y_test,?y_test_pred)))

print("The?r2_core?for?train?set?is:?{:.4f}".format(lr2.score(x_train,?y_train)))

print("The?r2_core?for?test?set?is:?{:.4f}".format(lr2.score(x_test,?y_test)))

figure("預(yù)測值與真實值圖模型的$R^2={:.4f}$".format(r2_score(y_test,?y_test_pred)),?[y_test,?"ture"],?[y_test_pred,?"pred"])



圖1
圖2
圖3
圖4
圖5
圖6
圖7

吐槽一下,沒法插入文件可真是太難了

補充一下:

最后可以輸出線性模型的系數(shù):

# 線性回歸的系數(shù)

print('線性回歸的系數(shù)為:\n w = {} \n b = {}'.format(lr1.coef_, lr1.intercept_))


圖8
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容