- sklearn模塊的線性回歸模型
from sklearn import datasets, linear_model
# 引入模型所在模塊。
………………
regr = linear_model.LinearRegression()
# 實(shí)例化模型。
regr.fit(X_parameters,Y_parameters)
# 為模型賦予數(shù)據(jù)X_parameters(訓(xùn)練數(shù)據(jù)),Y_parameters(目標(biāo)數(shù)據(jù))捧毛。
predict_outcome = regr.predict(predict_value)
# 輸入生成預(yù)測數(shù)據(jù)需要的參數(shù)predict_value.
predictions = {}
predictions['intercept'] = regr.intercept_
# 回歸模型的theta0參數(shù)
predictions['coefficient'] = regr.coef_
# 回歸模型的theta1參數(shù)
predictions['predicted_value']=predict_outcome
我們可以發(fā)現(xiàn),回歸模型需要的數(shù)據(jù)包括:
Paste_Image.png
所以让网,我們的任務(wù)是要找出X
(訓(xùn)練數(shù)據(jù))和Y
(目標(biāo)值)呀忧,X
的輸入形式可以是數(shù)組或矩陣,Y
只能是數(shù)組寂祥。
- 分析整理訓(xùn)練數(shù)據(jù)X和目標(biāo)值Y荐虐。已知房屋平米數(shù)和價(jià)格的關(guān)系數(shù)據(jù)如下:
Paste_Image.png
用函數(shù)將input_data.csv中的數(shù)據(jù)讀出來:
def get_data(file_name):
data = pd.read_csv(file_name)
# 讀取csv文件的方法
print data
X_parameter = [ ]
Y_parameter = [ ]
for single_square_feet, single_price_value in zip(data['square_feet'],data['price']):
# 通過列名調(diào)用數(shù)據(jù)。
X_parameter.append([float(single_square_feet)])
Y_parameter.append([float(single_price_value)])
pdb.set_trace()
return X_parameter,Y_parameter
下圖顯示丸凭,我們得到了想要的訓(xùn)練數(shù)據(jù)X和目標(biāo)值Y福扬。
Paste_Image.png
- 調(diào)用線性回歸模型
# Function for Fitting our data to linear model
def linear_model_main(X_parameters,Y_parameters,predict_value):
# Create linear regression object
pdb.set_trace()
regr = linear_model.LinearRegression()
regr.fit(X_parameters,Y_parameters)
predict_outcome = regr.predict(predict_value)
predictions = {}
predictions['intercept'] = regr.intercept_
predictions['coefficient'] = regr.coef_
predictions['predicted_value']=predict_outcome
return predictions
我們構(gòu)造了字典: 'predictions' ,將模型輸出的 θ0(regr.intercept_) ,θ1(regr.coef_) 以及預(yù)測值都存儲在字典中惜犀。
Paste_Image.png
- 檢驗(yàn)一下線性回歸的擬合情況铛碑,將原有的數(shù)據(jù)點(diǎn)用藍(lán)色標(biāo)記在圖中,求出對應(yīng)X_parameters的每個(gè)估計(jì)值虽界,將其用紅線連接起來汽烦。
# Function to show the results of linear fit model
def show_linear_line(X_parameters,Y_parameters):
regr = linear_model.LinearRegression()
regr.fit(X_parameters,Y_parameters)
plt.scatter(X_parameters,Y_parameters,color='blue')
plt.plot(X_parameters,regr.predict(X_parameters),color='red',linewidth=4)
plt.xticks(())
plt.yticks(())
plt.show()cges/4225992-b20e17ea38bacb91.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Paste_Image.png
從直觀上看,擬合的直線不錯(cuò)莉御!
5.這里討論的情況是在一維的情況下進(jìn)行的撇吞,也即只用一個(gè)自變量x(房屋的平米數(shù)),來估計(jì)房屋的價(jià)格礁叔。這里構(gòu)造x數(shù)組還是比較簡單牍颈,那如果是多個(gè)變量(平米數(shù)、房間數(shù)等)又該怎么琅关?我們可以同理處理煮岁,看下一集。
6.參考文獻(xiàn):
http://dataconomy.com/2015/02/linear-regression-implementation-in-python/