from sklearn.linear_model import LinearRegression
clf = LinearRegression()
clf.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) # 模型訓練
'''
y = 0.5*x1 + 0.5*x2
'''
pre = clf.predict([[3, 3]]) # 模型預測
clf.coef_
clf.intercept_
print(pre)
- 輸出:
[3.]
# 波士頓房價數據迴歸分析
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline
bosten = load_boston() # 實例化
x = bosten.data[:, 5:6]
clf = LinearRegression()
clf.fit(x, bosten.target) # 模型訓練
clf.coef_ # 迴歸係數
y_pre = clf.predict(x) # 模型輸出值
plt.scatter(x, bosten.target) # 樣本實際分佈
plt.plot(x, y_pre, color='red') # 繪製擬合曲線
plt.show()