線性回歸模型應(yīng)該是機(jī)器學(xué)習(xí)里面一個(gè)基本的模型细燎,線性模型(linear model)試圖學(xué)得一個(gè)屬性的線性組合函數(shù)來進(jìn)行預(yù)測筹麸。
假設(shè)輸入的數(shù)據(jù)是:
那么,根據(jù)這個(gè)輸入的數(shù)據(jù),得到一個(gè)訓(xùn)練模型煎殷。然后預(yù)測一下一個(gè)700平方英尺的房子,價(jià)格是多少腿箩?
原理性的東西豪直,我是參考周志華的《機(jī)器學(xué)習(xí)》關(guān)于線性回歸的介紹和復(fù)習(xí)了一下最小二乘法思想。
實(shí)驗(yàn)的部分珠移,使用python來實(shí)現(xiàn)的弓乙。
實(shí)現(xiàn)
- 需要的python庫
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets,linear_model
2.訓(xùn)練集
x_parameter=[[150],[200],[250],[300],[350],[400],[600]]
y_parameter=[6450,7450,8450,9450,11450,15450,18450]
3.訓(xùn)練模型
def linear_model_main(x_parameter,y_parameter,predict_value):
regr=linear_model.LinearRegression()
regr.fit(x_parameter,y_parameter)
predict_outcome=regr.predict(predict_value)
predictions={}
predictions['intercept']=regr.intercept_
predictions['coefficient'] = regr.coef_
predictions['predicted_value'] = predict_outcome
return predictions
4.調(diào)用
predict_squre=700
result=linear_model_main(x_parameter,y_parameter,predict_squre)
5.畫圖顯示一下
def show_linear_line(X_parameters,Y_parameters):
# Create linear regression object
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()
源代碼:
https://github.com/zhaozhengcoder/Machine-Learning/blob/master/linear%20model.py
PS:
這里調(diào)用了sklearn 的庫,使用了linear_model.LinearRegression()函數(shù)钧惧,直接擬合了數(shù)據(jù)暇韧。但是,這個(gè)函數(shù)內(nèi)部是怎么做的浓瞪?是如何做到了懈玻?
就設(shè)計(jì)到了如何求解代價(jià)函數(shù)的最小值,最小二乘法乾颁,梯度下降等知識(shí)涂乌。
以后補(bǔ)充這個(gè)推理過程。